Matlab - 从 [MxN] 矩阵元素中快速减去 [1xN] 数组
我有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
bsxfun
,如以下示例所示。这里的 z 是通过从每一行中减去第一行来获得的。只需将
x
替换为矩阵,将y
替换为行向量,就可以了。Use
bsxfun
like in the following example.Here
z
is obtained by subtracting the first row from every row. Just replacex
with your matrix andy
with your row vector, and you'r all set.bsxfun(.)
可能会更高效,但作为一个老朋友,我个人建议不要完全忽略基于线性代数的解决方案,例如:让实际用例和分析器来决定实际使用的功能。
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:Let the actual use case and profiler to decide the functionality actually utilized.