繁体   English   中英

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

[英]how to add values of looped variable to table and call the table in another function

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

或者,如果您确实想要,可以通过在循环后执行table(x,y)将x和y制成表,并将该表传递给函数。

暂无
暂无

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

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