如何在表中添加循环变量的值并在另一个函数中调用表

如何在表中添加循环变量的值并在另一个函数中调用表

问题描述:

for it=1:10 
    x=rand(10,1) 
    y=x.^2 
    datastore=table(i,x,y) % all iteration values are not stored 
end 

function z=summation(x,y) 
z=x+y %here I want to call table for other math operations also 
end 

创建表并存储每次迭代的i,x和y的值。我想避免使用全局变量并使用函数或变量范围,以最合适的为准。 如何做?如何在表中添加循环变量的值并在另一个函数中调用表

看看你的循环。首先,我假设这是一个错字,for it=1:10应该是for i=1:10。其次,在循环的每次迭代中,您将覆盖database变量。

为什么数据必须存储到表中?你可以在一个单一的循环中轻松做到这一点。

for i=1:10 % define loop variable 
x(:,i)=rand(10,1); % generate random vector and store into 'i'th column of x 
y(:,i)=x(:,i).^2; % find 2nd power of vector, store into 'i'th column of y 
z(:,i) = x(:,i) + y(:,i); % summate 'i'th vector of x and y and store in z 
end 

或者,如果你真的想,你可以做x和y的表格通过在循环后做table(x,y)和表传递到你的函数。

+0

问题的一部分是如何将它称为另一个函数,没有全局变量。并用变量或函数作用域。你能延长一点吗? –

+0

定义循环后的表格,然后将你的表格放入函数中作为函数z = summation(table) – Eppicurt