1
$\begingroup$

I have a table 9x10000, and I need to manipulate in the following way: if one element of the fifth line is equal to zero, the corresponding columns has to be deleted, otherwise it has to be left.

I tried with an if and drop inside a for loop, but it does not work. Many thanks

$\endgroup$
1
  • $\begingroup$ One way is to apply this composed function to your data: Composition[Transpose, DeleteCases[{_, _, _, _, 0, _, _, _, _}], Transpose] $\endgroup$ – Gustavo Delfino Apr 28 '20 at 12:36
1
$\begingroup$
ClearAll[f]
f = Transpose @ Delete[Position[#[[5]], 0]] @ Transpose @ # &;

Example:

SeedRandom[1234]
table = RandomInteger[5, {9, 10}];

MatrixForm[MapAt[Style[#, Blue] &, #, {5, All}] /. 
    Style[0, _] :> Style[0, Red, Bold]] & @ table

enter image description here

table2 = f @ table;
MatrixForm[table2]

enter image description here

Also

ClearAll[f2]
f2 = #[[All, Complement[Range@Length@#, Flatten@Position[#, 0]] &@#[[5]]]] &;

f2 @ table == f @ table
 True
$\endgroup$
1
  • $\begingroup$ Thanks...works! $\endgroup$ – federica Apr 28 '20 at 15:20
0
$\begingroup$

Two variants using Position and streamlining a bit.

Kindly stealing kglr's matrix,

SeedRandom[1234]
table = RandomInteger[5, {9, 10}];

With Fold and Drop:

SetRow = 5;
RemCol = Flatten[Position[table[[SetRow]], 0]];
output = Fold[Drop[#1, None, {#2}] &, table, Reverse[RemCol]]

With MapThread

SetRow = 5;
RemCol = Position[table[[SetRow]], 0];
output = MapThread[Delete, {table, ConstantArray[RemCol, Length[table]]}]

I do not know about efficiency, and I believe many ways that use Apply or custom functions can be used.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.