谁能帮我找出在Matlab中对不同大小矩阵的元素求和的方法吗?
假设我有 2 个带有数字的矩阵。 示例:
A=[1 2 3;
4 5 6;
7 8 9]
B=[10 20 30;
40 50 60]
我想创建矩阵C填充总和(矩阵A和B的绝对减法)。
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 中编写此代码?
最佳答案
代码
%%// 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)'
关于matlab - Matlab中不同大小矩阵元素求和的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23528289/