【问题标题】:multiplying arrays with different dimensions将不同维度的数组相乘
【发布时间】:2014-03-30 22:02:51
【问题描述】:

我有两个问题。 如何将不同维度的数组相乘?

Question 1 Example:

    A1=1,2,3,4,5,6
    A2=1,2,3
    The answer I would like to get would be
    A1*A2 =1,4,9,4,10,18

我想只使用 repmat,但这是最好的方法吗?

还有

Question 2 Example:
A1=1,2,3,4,5,6,7  (notice the addition of another value the number 7)
A2=1,2,3
The answer I would like to get would be
A1*A2 =1,4,9,4,10,18,7 (notice the addition of another value the number 7)

我在考虑 for 循环,但数组非常大,有 500,000+ 个值,需要很长时间才能完成。

有没有办法编写一些适用于两个问题/示例的 matlab/代码?

【问题讨论】:

  • 1,4,9...?我不确定你是如何获得 1,4,6...
  • 你在做元素乘法(A1.*A2)吗?您的代码显示矩阵乘法 (A1*A2)...
  • @Mad Physicist 感谢我将 6 更改为 9 并更新了问题
  • @kkuilla 我不确定我应该使用哪一个,这就是为什么我将示例与我试图获得的答案一起提供
  • 我认为您正在寻找逐元素乘法 (A1.*A2)。

标签: arrays matlab multidimensional-array octave


【解决方案1】:

您可以使用mod 循环遍历较短数组的元素:

result = A1.*A2(mod(0:numel(A1)-1,numel(A2))+1);

或者,如果一个长度是另一个长度的整数倍(第一个示例),您可以reshape 较大的向量,使一个维度匹配较短的向量,然后使用bsxfun

result = bsxfun(@times, reshape(A1,numel(A2),[]), A2(:));
result = result(:).';

【讨论】:

  • 我试过你的代码两种方式 A1=1,2,3,4,5,6; A2=1,2,3;结果 = bsxfun(@times, reshape(A1,numel(A2),[]), A2(:));结果 = 结果(:)。' A1=1,2,3,4,5,6; A2=1,2,3;结果 = A1.*A2(mod(0:numel(A1)-1,numel(A2))+1);但是我的问题的答案没有出现我做错了什么吗?
  • 要定义向量A1A2,您需要使用括号A1=[1,2,3,4,5,6]; A2=[1,2,3];
【解决方案2】:

这是一个代数解,如果A2'*A1的大小是合理的:

B = spdiags(A2'*A1,0:numel(A2):numel(A1))
result = B(1:numel(A1))

【讨论】:

  • 我试了你的代码,发现尺寸不匹配 A1=1,2,3,4,5,6; A2=1,2,3; B = spdiags(A1'*A2,0:numel(A1):numel(A2)) 结果 = B(1:numel(A2))
  • @RickT 抱歉,我切换了 A1 和 A2。现在更正了。您还需要 A1 和 A2 的括号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多