Matlab - Quickly subtract [1xN] array from [MxN] matrix elements [duplicate]

笑着哭i 提交于 2019-12-06 23:23:53

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5967940/matlab-quickly-subtract-1xn-array-from-mxn-matrix-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!