Matlab列表理解 [英] Matlab list comprehension

查看:108
本文介绍了Matlab列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在一个衬里写以下内容吗?

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'设置为false0.输出将是一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆