Message Boards Message Boards

0
|
7687 Views
|
2 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Use IF, condition with {} ?

Hi, i Have

H = {1.5, 0.4}; 
cp4p = {{{1, 2}, {3, 4}, {5, 6}}, { }}; 
For[i = 1, i <= Length[H], i ++, If[cp4p[[i,All,All]]=="{}" , Delete[H,i], H[[i]]]]

But the instruction doesn't work, why?

I would as result

`H={1.5}`

This is un exemple that generalize my case.

Thank you for your attention. Margherita

2 Replies

There are multiple errors: an empty list is:

 {} 

without quotes, otherwise it is a string. Moreover Delete[H,i] will not update the variable H, so you need to assign it yourself:

H = Delete[H, i]

so the code changes to:

H = {1.5, 0.4};
cp4p = {{{1, 2}, {3, 4}, {5, 6}}, {}};
For[i = 1, i <= Length[H], i++, 
 If[cp4p[[i]] == {}, H = Delete[H, i]]]
H

Note that the 'else' case in the If not necessary.

Many alternate ways are possible:

H = {1.5, 0.4};
cp4p = {{{1, 2}, {3, 4}, {5, 6}}, {}};
H = Pick[H, # == {} & /@ cp4p, False]

or

H = {1.5, 0.4};
cp4p = {{{1, 2}, {3, 4}, {5, 6}}, {}};
H = Table[If[cp4p[[i]] == {}, Nothing, H[[i]]], {i, Length[H]}]

or

H = {1.5, 0.4};
cp4p = {{{1, 2}, {3, 4}, {5, 6}}, {}};
H = MapThread[If[#1 == {}, Nothing, #2] &, {cp4p, H}]

or

H = {1.5, 0.4};
cp4p = {{{1, 2}, {3, 4}, {5, 6}}, {}};
H = Select[Transpose[{H, cp4p}], #[[2]] =!= {} &][[All, 1]]

or...

POSTED BY: Sander Huisman

thanks a lot

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract