[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
## Re: adding vectors and matrices

**From**: |
Ted Harding |

**Subject**: |
Re: adding vectors and matrices |

**Date**: |
Fri, 22 Aug 1997 20:01:22 +0100 (GMT+0100) |

( Re Message From: O. Scott Sands )
>* *
>* Ted Harding wrote:*
>* > *
>* > ( Re Message From: Andreas Heitmann )*
>* > >*
>* > > I'm using octave for some time now, but I'm still wondering if there*
>* > > is a simple way to add a fixed column vector to a number of other*
>* > > column vectors stored in a matrix. Currently i'm using a loop like the*
>* > > following:*
>* > >*
>* > > v=[1;2;3];*
>* > > for i=1:columns(x)*
>* > > y(:,i)=x(:,i)+v;*
>* > > endfor*
>* > >*
>* > > Is it possible to compute y without a loop statement?*
>* > *
>* > Hi,*
>* > *
>* > y = x + v*ones(1,columns(x));*
>* > *
>* > will do it. I understand John Eaton plans to incorporate a syntax like*
>* > *
>* > y = x .+ v*
>* > *
>* > for a future release which will do the same thing (and the corresponding*
>* > thing if v is a row vector with as many elements as x has columns, i.e.*
>* > add v to each row of x).*
>* > *
>* > Best wishes,*
>* > Ted. (address@hidden)*
>* *
>* nononononononono!*
>* *
>* Octave supports zero-one indexing (ala MATLAB) so you*
>* can use "Tony's Trick" (see Mathworks archives)*
>* *
>* y=x+v(:,ones(1,columns(x)));*
>* *
>* The indexing functions done in with Tony's Trick*
>* are much faster than the multiply operations *
>* suggested by y=x+v*ones(1,columns(x)). Try it!*
Just did, and I'm not sure you're right:
X = rand(20,200); v = rand(20,1);
tic;
for i=1:10000,
Y=0; Y=X+v*ones(1,200);
endfor
toc ## -----> 23 seconds
tic;
for i=1:10000,
Y=0; Y=X+v(:,ones(1,200));
endfor
toc ## -----> 34 seconds
And the same with the two methods in reverse order.
>* Since this issue appears periodically in the *
>* mailing list here, maybe it should be put in *
>* the manual?*
Let's make sure we're right about it first ... but I agree it's
definitely a FAQ!
Ted. (address@hidden)