Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I perform something like List comprehension in Matlab?

My question is: How could I perform something like List comprehension in Matlab similar to Haskell or Python? To accomplish the function in Matlab like below:

for xxx 
    if condition
        expression1;    
    else 
        expression2;
     end 
end 

My original aim is to make use of the vectorized operations and reduce the for-loop in my code to make it running faster.

EDIT: My expect to the answer is not necessary something related to the arrayfun, the vectoried operation method is more welcomed.

There is another question related to this question (through the function named "arrayfun"). The anonymous function in Matlab seams to be only 1 line, then how could I write the if-else expression in it ?

Thanks everyone ~~

like image 785
freealbert Avatar asked Oct 22 '22 06:10

freealbert


1 Answers

You cannot use if in anonymous functions in Matlab. However, you could work around this a bit using arrayfun, by defining your own function that will execute the statements and conditions, e.g.

function result = iff(condition, v1, v2)
  if condition
    result = v1;
  else
    result = v2;
  end

Then in arrayfun you can do something such as this:

arrayfun(@(x) iff(mod(x,2)==0, x , 0), [1:10])

results in:

0     2     0     4     0     6     0     8     0    10

This is based on the answer to similar question here.

like image 132
Marcin Avatar answered Oct 31 '22 18:10

Marcin