matlab - Matlab中不同大小矩阵元素求和的方法

标签 matlab matrix sum dimension

谁能帮我找出在Matlab中对不同大小矩阵的元素求和的方法吗?

假设我有 2 个带有数字的矩阵。 示例:

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

B=[10 20 30;
   40 50 60]

我想创建矩阵C填充总和(矩阵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)

实际上 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/

相关文章:

haskell - 如何在accelerate-haskell中定义矩阵乘积

mysql - 无法对求和值执行 ORDER BY

matlab - 将 3D 数据点转换为 matlab 中的标准化(2D)图形点

matlab - 在 Matlab 中缩短它

javascript - 从 ES6 生成器创建多维数组

c++ - OpenCV 3:如何将 cv::Mat 作为可选参数传递

matlab - 在matlab中更改刻度标签和轴之间的间距(与刻度标签和ylabel或xlabel相同)

matlab - 通过在 MATLAB 中获取上下包络来封装信号

Javascript 复选框计算不正确

mysql - 内部连接和 sum()