Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: subtract vector from matrix rows without for loop
Replies: 13   Last Post: Jun 14, 2017 7:34 AM

 Messages: [ Previous | Next ]
 Remus Posts: 5 Registered: 7/31/11
Re: subtract vector from matrix rows without for loop
Posted: Dec 6, 2012 11:48 PM

"Matt J" wrote in message <hesupb\$i07\$1@fred.mathworks.com>...
> "Patrick Diviacco" <patrick.diviacco@gmail.com> wrote in message <hesm3s\$3sn\$1@fred.mathworks.com>...
> > hi,
> >
> > can I subtract the same vector to each row of a matrix without using a for loop ?
> > thanks

>
> For loops may be optimal (looping along the smallest dimension of the matrix), when the smallest dimension is small enough.

I like Matt's answer... here is another way of doing it, slightly more efficient.

A = magic(3);
B = [ 1 2 3];
C = A-diag(B)*ones(size(A));

In essence is the same thing.

Date Subject Author
11/28/09 Patrick Diviacco
11/28/09 okogidi
11/28/09 mike zander
11/28/09 Matt J
11/29/09 Matt J
12/6/12 Remus
3/7/16 Zhun
12/6/12 Remus
9/13/15 Yuval Carmel
6/14/17 Hazem
6/14/17 Loren Shure
12/6/16 Muhammed Alavi
12/6/16 Bruno Luong
12/8/16 Loren Shure