2014-05-07 127 views
2

任何人都可以帮助我找出不同大小矩阵的元素求和的方法Matlab在Matlab中求和不同大小矩阵元素的方法

让我说我有2个矩阵的数字。 实施例:

A=[1 2 3; 
    4 5 6; 
    7 8 9] 

B=[10 20 30; 
    40 50 60] 

我想创建矩阵Ç填充用总和(基质A和B的绝对减法)。

MS Excel中的示例。 enter image description here

D10 = ABS(D3-I3)+ ABS(E3-J3)+ ABS(F3-K3)

E10 = ABS(D4-I3)+ ABS(E4-J3)+ ABS (F4-K3)

F10 = ABS(D5-I3)+ ABS(E5-J3)+ ABS(F5-K3)

然后(如上面)

D11 = ABS(D3 -I4)+ ABS(E3-J4)+ ABS(F3-K4)

E11 = ABS(D4- I4)+ ABS(E4-J4)+ ABS(F4-K4)

F11 = ABS(D5-I4)+ ABS(E5-J4)+ ABS(F5-K4)

实际上甲是30x8矩阵,B是10x8矩阵。

如何在Matlab中编写此代码?

+0

我觉得你可以编辑自己的矩阵这样的 - 'A = [1 2 3; 4 5 6; 7 8 9],B = [10 20 30; 40 50 60]' – Divakar

+0

谢谢,功能很好。工作。 但是**实际上A是30x8矩阵,B是10x8矩阵。** 请帮帮我。 – user3455066

+0

试过在这里提供的答案为大案? – Divakar

回答

2

代码

%%// Spread out B to the third dimension so that the singleton 
%%// second dimension thus created could be used with bsxfun for expansion in 
%%// that dimension 
t1 = permute(B,[3 2 1]) 

%%// Perform row-wise subtraction and then summing of their absolute values 
%%// as needed 
t2 = sum(abs(bsxfun(@minus,A,t1)),2) 

%%// Since the expansion resulted in data in third dimension, we need to 
%%// squeeze it back to a 2D data 
out = squeeze(t2)' 
+0

你能解释这个表达吗? 尤其是**挤压,排列(B,[3 2 1]),2)。** – user3455066

+1

@ user3455066请尝试按照添加的注释以及代码作为编辑。 – Divakar

+0

好的!感谢你的好意。 :) – user3455066

相关问题