[英]how to store return values from a function into column matrix (octave)
While calling a function inside a for loop I need to store all return values into a column matrix nx1 if n is number of times loop iterates: 在for循环内调用函数时,如果n是循环迭代的次数,则需要将所有返回值存储到列矩阵nx1中:
for (i = 1:n)
function(arg);
end
After storing these values I need to get top five values as well. 存储这些值后,我还需要获取前五个值。
Assuming that your argument res
depends on the index i
, ie result(i) = yourfunction(arg(i))
, you can use the more compact expression: 假设您的参数res
取决于索引i
,即result(i) = yourfunction(arg(i))
,则可以使用更紧凑的表达式:
result = arrayfun(@yourfunction,arg);
. 。
You can use following code: 您可以使用以下代码:
res = zeros(n,1);
for (i = 1:n)
res(i)=function(arg);
end
Allocation before loop is required to be sure that you have column matrix instead row. 需要在循环前分配,以确保您具有列矩阵而不是行。
Edit : 编辑 :
Answer for last question: After storing these values I need to get top five values as well. 最后一个问题的答案:存储这些值后,我还需要获取前五个值。
You can use sort function to receive best values: 您可以使用排序功能来接收最佳值:
res=sort(res);
result=res(1:5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.