我是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并在结束时得到结果吗?提前致谢.对不起我的英语不好.
你能用prod(sum(x,2))吗?我想如果你重新排列总和中的术语,你会发现你可以将你的行的总和相乘,你会得到同样的东西.(但也许我误解了你正在寻找的东西).
例如:
>> x=[1 2 3 ; 4 5 6; 7,8,9]
x =
1 2 3
4 5 6
7 8 9
>> prod(sum(x,2))
ans =
2160
>> 1*4*7 + 1*4*8 + 1*4*9 + 1*5*7 + 1*5*8 + 1*5*9 + 1*6*7 + 1*6*8 + 1*6*9 + 2*4*7 + 2*4*8 + 2*4*9 + 2*5*7 + 2*5*8 + 2*5*9 + 2*6*7 + 2*6*8 + 2*6*9 + 3*4*7 + 3*4*8 + 3*4*9 + 3*5*7 + 3*5*8 + 3*5*9 + 3*6*7 + 3*6*8 + 3*6*9
ans =
2160
Run Code Online (Sandbox Code Playgroud)
如果你真的需要使用组合方法递归地执行此操作,您应该能够将D作为输入传入,并将其作为函数的输出返回,如下所示:
function D = combination(n,A,x, D) % 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)];
D = combination(n-1,A,x, D);
if length(A)>=1
A = A(1:length(A)-1);
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
然后最初调用它D等于零.
不要担心这里通过引用传递.MATLAB没有通过引用传递(它有变量具有引用语义,但这是一个不同的东西),但它使用了写时复制,并且对可以就地完成的计算进行了特殊优化,作为计算与D可以在这里.