How to calculate this in matlab without loop

Since matlab is slower to execute for a loop, I usually avoid a loop for all my codes and turn them into a matrix calculation, which would be fast. But here is a problem that I cannot find in a smart way:

I have an nxn matrix

A=[a1,a2,a3,...,an], 

here a1, a2, a3 .... an are the columns of the matrix.

Another nxn matrix

 B=[b1,b2,b3,...,bn], 

similarly b1, b2, b3 ... are also columns B.

As well as nxn matrix M.

I want to calculate nxn matrix

 C=[c1,c2,c3,...,cn], thus (M+diag(ai))*ci = bi. 

namely

 ci = (M+diag(ai))\bi. 

I know one way without a loop:

 C(:)=( blkdiag(M)+diag(A(:)) )\B(:). 

But this will do too many calculations than necessary.

Any smart solutions? You can assume that there is no problem with the feature in the calculation.

+5
matrix for-loop matlab
03 Dec '12 at 6:35
source share
1 answer

The statement "for loops is slow in Matlab" is no longer true because Matlab ... euhm, R2008a? (someone please email me about this :)

In any case, try the following:

 clc clear all M = rand(50); a = rand(50); b = rand(50); % simple loop approach tic c = zeros(size(b)); for ii = 1:size(b,2) c(:,ii) = ( M+diag(a(:,ii)) ) \ b(:,ii); end toc % not-so-simple vectorized approach tic MM = repmat({M}, 50,1); c2 = (blkdiag(MM{:})+diag(a(:)))\b(:); toc norm(c(:)-c2(:)) 

Results:

 Elapsed time is 0.011226 seconds. % loop Elapsed time is 1.049130 seconds. % no-loop ans = 5.091221148787843e-10 % results are indeed "equal" 

There may be a better way to vectorize an operation, but I doubt it will be much faster than the version of the JIT'ed loop.

Some problems are simply not suitable for vectorization. I think this is one thing.

+2
Dec 03 '12 at 11:36
source share



All Articles