Matlab列表理解 [英] Matlab list comprehension
问题描述
我可以在一个衬里写以下内容吗?
Can I write the following in a one liner?
x = [1,3,5]
res = zeros(1,size(x,2));
for i=1:size(x,2);
res(i) = foo(x(i);
end;
假定foo函数未按预期处理数组.就我而言,即使将数组作为参数,foo也会返回标量.
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.
例如,在Python中,它看起来像这样:
In Python, for instance, it would look like this:
x = [1,3,5]
res = [foo(y) for y in x]
推荐答案
arrayfun
is what you need. For example:
res = arrayfun(@foo, x)
由于foo
始终返回标量,因此上面的方法将起作用,并且res
还将是与x
相同尺寸的向量.如果foo
返回可变长度输出,则必须在对arrayfun
的调用中将'UniformOutput'
设置为false
或0
.输出将是一个cell
数组.
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.
这篇关于Matlab列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!