2014-05-07 126 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

相關問題