Prev: Debug commands greyed out
Next: Sum of a cell
From: Doug Schwarz on 7 Apr 2010 18:14 In article <hpip5f$iij$1(a)fred.mathworks.com>, "Matt Fig" <spamanon(a)yahoo.com> wrote: > But Doug, by the example given: > > > M = magic(2)*pi; > V = [sqrt(2);sqrt(3)]; > > % Juliette's technique: > P(:,1)=M(:,1).*V; > P(:,2)=M(:,2).*V > > % BSXFUN > P2 = bsxfun(@times,M,V) > > > >>isequal(P,P2) > ans = > 1 You're right, of course -- I must be getting old. :-( -- Doug Schwarz dmschwarz&ieee,org Make obvious changes to get real email address.
From: Juliette Salexa on 7 Apr 2010 18:16 Thanks Matt and Steve, I always look up command documentation on the MW website rather than typing the help command , because I find that it's incredibly faster. When I type: help bsxfun the command window says "busy" for about 25 seconds before the help page comes up. And the website has more functionality. but in the future I know where to look if I'm wondering the etymology of a command!
From: Matt J on 7 Apr 2010 19:23
"Juliette Salexa" <juliette.physicist(a)gmail.com> wrote in message <hpikta$bjd$1(a)fred.mathworks.com>... > > I am currently doing: > > P(:,1)=M(:,1).*V > P(:,2)=M(:,2).*V > > > The only way I can think of generalizing this to larger dimensions would be using loops. =============== Note, that for-loops have been found to be more optimal than bsxfun when one the dimensions of M is very small. For example, if M is 10000x10 and V is 10000x1 it would probably be better to loop over the 10 columns of M as you've proposed. Similarly, if there are a small number of rows, you would loop over those. Here is a function which I use in situations like these (and which I was forced to use before bsxfun came along). It analyzes the optimum looping strategy based on the dimensions of M: function M=matmvec(M,v) %"Matrix times vector". Multiplies a vector into columns or rows of matrix. % % M_out=mattvec(M,v) % %The input M is a matrix. % %If v is a row vector, it will be multiplied into every row of M. % %If v is a column vector it will be multiplied into every column of M. % %It might be faster to do M*diag(v) or similar, but this route %conserves more memory. [Mrows,Mcols]=size(M); vlen=length(v); mindim=min([Mrows,Mcols]); if size(v,2)==1 %v is a column vector if vlen~=Mrows; error 'Sizes not compatible'; end if Mcols==mindim, %loop over columns for ii=1:Mcols M(:,ii)=M(:,ii).*v; end else %loop over rows for ii=1:vlen M(ii,:)=M(ii,:).*v(ii); end end else %v is a row vector if vlen~=Mcols; error 'Sizes not compatible'; end if Mcols==mindim %loop over columns for ii=1:Mcols M(:,ii)=M(:,ii).*v(ii); end else %loop over rows for ii=1:Mrows M(ii,:)=M(ii,:).*v; end end end |