我是matlab的初学者,我想计算从不同行中挑选的(3*n)矩阵元素的每个可能组合的乘积之和.
例如,如果矩阵是x = [1 2 3,4 4 6]我想要结果D = 1*4 + 1*5 + 1*6 + 2*4 + 2*5 + 2*6 + 3*4 + 3*5 + 3*6.
我写了下面的递归代码,但我有通过引用传递变量的问题.
function combination(n,A,x) % n= number of rows ,A= empty array, x = the matrix
if n == 0
D = D + prod(A);
else
for i = 1:1:3
A = [A x(n,i)];
combination(n-1,A,x);
if length(A)>=1
A = A(1:length(A)-1);
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
我需要D参数但是当我将D声明为全局时它没有帮助.无论如何在matlab中我可以在函数中通过引用传递D并在结束时得到结果吗?提前致谢.对不起我的英语不好.