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$ Commented Apr 28, 2020 at 12:36

5 Answers 5

2
$\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
    Commented Apr 28, 2020 at 15:20
1
$\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$
1
$\begingroup$

Using kglr's data

SeedRandom[1234];

m = RandomInteger[5, {9, 10}];

p = Prepend[All] /@ Position[m[[5]], 0]

{{All, 2}, {All, 8}}

Using ReplaceAt (new in 13.1)

ReplaceAt[_ :> Nothing, p] @ m // MatrixForm

enter image description here

Using MapAt

MapAt[Nothing, p] @ m // MatrixForm

(* same result *)

$\endgroup$
1
$\begingroup$
SeedRandom[1234];

m = RandomInteger[5, {9, 10}];

Grabbing kglr's data and using ReplacePart:

p = Position[m[[5]], 0];

ReplacePart[#1, #2 -> Nothing] & @@@ Thread[{#, Array[p &, Length@#]}] &@m;

% // MatrixForm

enter image description here

$\endgroup$
0
$\begingroup$
SeedRandom[1234];
table = RandomInteger[5, {9, 10}]; (* Using @kglr's data *)

f = If[#[[5]] == 0, Nothing, #] &;

res = ArrayReduce[f, table, 1] // Transpose;
MatrixForm /@ {table, res}

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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