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

时间:2017-11-04 04:26:58

标签: matlab datatables functional-programming structure

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值。我想避免使用全局变量并使用函数或变量作用域,以最合适的为准。 怎么做?

1 个答案:

答案 0 :(得分:0)

看看你的循环。首先,我假设这是一个错字,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

或者如果你真的想要,你可以在循环后通过table(x,y)创建一个包含x和y的表,并将表传递给你的函数。