【问题标题】:Method to sum of the elements of different sized matrix in MatlabMatlab中不同大小矩阵元素求和的方法
【发布时间】:2014-05-07 20:57:31
【问题描述】:

谁能帮我找出在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 中编写?

【问题讨论】:

  • 我认为你可以像这样编辑你的矩阵 - A=[1 2 3; 4 5 6; 7 8 9], B=[10 20 30; 40 50 60]
  • 谢谢,很棒的功能。工作。但实际上 A 是 30x8 矩阵,B 是 10x8 矩阵。请帮帮我。
  • 尝试过这里提供的更大案例的答案吗?
  • 再次感谢!此功能也适用于更大的情况。非常感谢!

标签: matlab matrix sum dimension


【解决方案1】:

代码

%%// 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)'

【讨论】:

  • 你能解释一下这个表达式吗?特别是squeeze,permute(B,[3 2 1]),2)。
  • @user3455066 请尝试按照与代码一起添加的 cmets 作为编辑。
  • 好的!谢谢你的好意。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
  • 2012-07-02
  • 2014-10-24
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多