Matlab: add vector to matrix

假装没事ソ 提交于 2019-11-29 20:00:21

问题


I have a 3XN matrix representing a list of 3D coordinates,something like

33    33    33    33    34    34    34    34    34    35    35
17    18    19    20    16    17    18    19    20    16    17
10    10    10    10    10    10    10    10    10    10    10 

I want to shift all coordinates by some vector v=[1 2 3], that is add the 3D vector to each column of the matrix.

I know how to do that with a for loop, but how can I do it without a loop? Surely there's a way...


回答1:


you mean like this?

D=[33    33    33    33    34    34    34    34    34    35    35;
17    18    19    20    16    17    18    19    20    16    17;
10    10    10    10    10    10    10    10    10    10    10 ];

A=[1 2 3]';

C= bsxfun(@plus, D, A)

C =

    34    34    34    34    35    35    35    35    35    36    36
    19    20    21    22    18    19    20    21    22    18    19
    13    13    13    13    13    13    13    13    13    13    13



回答2:


Use repmat:

M = randn(3, N);           % your 3 x N matrix
v = randn(3, 1);           % your vector
r = M + repmat(v, [1 N]);  % add v to every column of M


来源:https://stackoverflow.com/questions/7516402/matlab-add-vector-to-matrix

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