簡體   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