我有以下matlab代码,它执行变量嵌套循环:
function rec_function(numLoops, loopVars, index, NINT)
if numLoops == 0
loopVars
return
end
for k = 1:NINT(1,index)
loopVars(1,index) = (k-1)/(NINT(1,index)-1);
rec_function(numLoops-1, loopVars, index+1, NINT);
end
end
突出显示的部分将执行以下操作:
>> rec_function(2,zeros(1,2),1, [2 2])
loopVars =
0 0
loopVars =
0 1
loopVars =
1 0
loopVars =
1 1
我想问一下如何将每个循环的向量loopVars保存在矩阵中以供进一步使用,例如:
A = [0 0; 0 1; 1 0; 1 1]
答案 0 :(得分:1)
一个简单的解决方案是使用global variables:
function rec_function(numLoops, loopVars, index, NINT)
global loopVars_all;
if numLoops == 0
loopVars_all(end + 1, :) = loopVars;
return
end
for k = 1:NINT(1,index)
loopVars(1,index) = (k-1)/(NINT(1,index)-1);
rec_function(numLoops-1, loopVars, index+1, NINT);
end
end
你这样称呼它:
global loopVars_all;
loopVars_all = [];
rec_function(2, zeros(1,2), 1, [2 2]);
loopVars_all
loopVars_all =
0 0
0 1
1 0
1 1