Matlab - 从 [MxN] 矩阵元素中快速减去 [1xN] 数组

发布于 2024-11-06 08:19:40 字数 620 浏览 1 评论 0原文

可能的重复:
如何从 a 的每一行中减去一个向量矩阵?
如何划分每一行矩阵的固定行?

我有 M 行和 4 列的矩阵 (M1)。我有另一个 1 行 4 列的数组 (M2)。我想将 M1 中的每个元素减去 M2 中相应的列元素。换句话说,M1的每一列都需要减去M2中相同列位置的标量。我可以调用repmat(M2,M,1),这将创建一个大小为MxN的新矩阵,其中列中的每个元素都是相同的,然后逐个元素进行减法:

M2new = repmat(M2,M,1)
final = M1 - M2new

但是,这是两行代码,并在内存中创建一个新元素。执行此操作最快且占用内存最少的方法是什么?

Possible Duplicates:
How to subtract a vector from each row of a matrix?
How can I divide each row of a matrix by a fixed row?

I have matrix (M1) of M rows and 4 columns. I have another array (M2) of 1 row and 4 columns. I'd like to subtract every element in M1 by its respective column element in M2. In other words, each column of M1 needs to be subtraced by the scalar in the same column position in M2. I could call repmat(M2,M,1), which would create a NEW matrix of size MxN, where each element in a column was the same, and then do a element by element subtraction:

M2new = repmat(M2,M,1)
final = M1 - M2new

, however, this is two lines of code and creates a new element in memory. What is the fastest and least memory intensive way of performing this operation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

摇划花蜜的午后 2024-11-13 08:19:40

使用 bsxfun,如以下示例所示。

x=magic(4);
y=x(1,:);
z=bsxfun(@minus,x,y)

z =

     0     0     0     0
   -11     9     7    -5
    -7     5     3    -1
   -12    12    12   -12

这里的 z 是通过从每一行中减去第一行来获得的。只需将 x 替换为矩阵,将 y 替换为行向量,就可以了。

Use bsxfun like in the following example.

x=magic(4);
y=x(1,:);
z=bsxfun(@minus,x,y)

z =

     0     0     0     0
   -11     9     7    -5
    -7     5     3    -1
   -12    12    12   -12

Here z is obtained by subtracting the first row from every row. Just replace x with your matrix and y with your row vector, and you'r all set.

街道布景 2024-11-13 08:19:40

bsxfun(.) 可能会更高效,但作为一个老朋友,我个人建议不要完全忽略基于线性代数的解决方案,例如:

> M1= magic(4)
M1 =
   16    2    3   13
    5   11   10    8
    9    7    6   12
    4   14   15    1
> M2= M1(1, :)
M2 =
   16    2    3   13
> M1- ones(4, 1)* M2
ans =
    0    0    0    0
  -11    9    7   -5
   -7    5    3   -1
  -12   12   12  -12

让实际用例和分析器来决定实际使用的功能。

bsxfun(.) can potentially be more efficient, but personally as an old timer, I'll would recommend not to totally ignore linear algebra based solutions, like:

> M1= magic(4)
M1 =
   16    2    3   13
    5   11   10    8
    9    7    6   12
    4   14   15    1
> M2= M1(1, :)
M2 =
   16    2    3   13
> M1- ones(4, 1)* M2
ans =
    0    0    0    0
  -11    9    7   -5
   -7    5    3   -1
  -12   12   12  -12

Let the actual use case and profiler to decide the functionality actually utilized.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文