简体   繁体   English

Matlab如何通过列表迭代函数

[英]Matlab How to iterate a function through a list

I need some help iterating over a function that depends on two variables. 我需要一些迭代取决于两个变量的函数的帮助。

So let's say I have a function that depends on two variables. 假设我有一个依赖于两个变量的函数。 Let's call it f = x + y 我们称它为f = x + y

Now, I have a two lists, one of x variables and one of y variables. 现在,我有两个列表,x变量之一和y变量之一。 For example, xlist = [1 2 3] and ylist = [4 5 6] 例如,xlist = [1 2 3]和ylist = [4 5 6]

And I want to go through each element of the lists and plug it into f. 我想遍历列表的每个元素并将其插入f。 For example, set x=1 and then evaluate f for y=4, then y=5, then y=6... and repeat for x=2 and x=3. 例如,设置x = 1,然后对f进行y = 4,然后y = 5,然后y = 6 ...,然后对x = 2和x = 3重复。

Finally, I want to return a matrix of the calculated values. 最后,我想返回一个计算值的矩阵。 For the example above, the answer should be [5 6 7];[6 7 8];[7 8 9] 对于上面的示例,答案应为[5 6 7]; [6 7 8]; [7 8 9]

How would I go about doing this? 我将如何去做呢?

Assuming the function can't be vectorized and thus you really need to iterate, a simple way is via ndgrid (to create x , y values that describe all possible pairs) and arrayfun (to iterate over the two x , y values at the same time): 假设函数不能被向量化 ,因此您真的需要进行迭代,一种简单的方法是通过ndgrid (创建描述所有可能对的xy值)和arrayfun (在同一位置迭代两个xy值)时间):

f = @(x,y) x+y; % Or f = @fun, if fun is a function defined elsewhere
xlist = [1 2 3];
ylist = [4 5 6];
[xx, yy] = ndgrid(xlist, ylist); % all pairs
result = arrayfun(f, xx, yy);

In many cases the function can be vectorized , which results in faster code. 在许多情况下, 可以对函数进行矢量化处理 ,从而加快代码速度。 For the example function this would be done defining f as 对于示例函数,可以将f定义为

f = @(x,y) bsxfun(@plus, x(:), y(:).');

or in recent Matlab versions you can exploit implicit singleton expansion and just write 或在最新的Matlab版本中,您可以利用隐式单例扩展,然后编写

f = @(x,y) x(:)+y(:).';

In either case, note that the two arguments of addition are forced to be a column vector ( x(:) ) and a row vector ( y(:).' ), so that singleton expansion will automatically create all pairs: 无论哪种情况,请注意,两个加法参数被强制为列向量( x(:) )和行向量( y(:).' ),因此单例扩展将自动创建所有对:

xlist = [1 2 3];
ylist = [4 5 6];
result = f(xlist, ylist);

Another way to do it would be to use two for loops: 另一种方法是使用两个for循环:

x_values=[2,4,6,8];
y_values=[1,3,5,7];
%initialize a matrix with zeros
output_matrix=zeros(length(x_values),length(y_values));
for i=1:length(x_values)
    for j=1:length(y_values)
        output_matrix(i,j)=x_values(i)+y_values(j);
    end 
end

output_matrix

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM