Matlab List Comprehension

Can I write the following in a one liner?

x = [1,3,5,7,9]
res = zeros(1,size(x,2));
for i=1:size(x,2);
    res(i) = foo(x(i));
end;

Assume that the foo function does not handle arrays as expected. In my case foo returns a scalar even when giving an array as argument.

In Python, for instance, it would look like this:

x = [1,3,5,7,9]
res = [foo(y) for y in x]

2 Answers

arrayfun is what you need. For example:

res = arrayfun(@foo, x)

Since foo always returns a scalar, the above will work and res will also be a vector of the same dimensions as x. If foo returns variable length output, then you will have to set 'UniformOutput' to false or 0 in the call to arrayfun. The output will then be a cell array.

3

Just to add to the good answer of @yoda, instead of using UniformOutput, you can also use {} brackets:

res = arrayfun(@(t){foo(t)}, x)

Also, in some occasions, foo is already vectorized.

x = 1:10;
foo = @(t)(power(t,2));
res = foo(x);
2

Your Answer

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

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest