有人可以帮我找出 Matlab 中不同大小矩阵元素总和的方法吗?
假设我有两个带数字的矩阵。 例如:
A=[1 2 3;
4 5 6;
7 8 9]
B=[10 20 30;
40 50 60]
我想用sum(矩阵A和B的绝对减法)创建矩阵 C 。
MS Excel中的示例。
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)
实际上A是30x8矩阵,B是10x8矩阵。
我怎样才能在Matlab中写这个?
答案 0 :(得分: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)'