Question

Can anybody help me to find out the method to sum of the elements of different sized matrix in Matlab ?

Let say that I have 2 matrices with numbers. Example:

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

B=[10 20 30;
   40 50 60]

I wanna create matrix C filling with sum(absolute subtract of matrix A and B).

Example in 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)

And then (Like above)

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)

Actually A is a 30x8 matrix and B is a 10x8 matrix.

How can i write this in Matlab?

Was it helpful?

Solution

Code

%%// 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)'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top