Got Questions? Get Answers.
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Parfor statements

Subject: Parfor statements

From: Alex

Date: 10 Feb, 2012 11:50:28

Message: 1 of 2

Dear all,,
could you please help me convert the code below to parfor statements



matrixToReturn=Gmatrix;
for i=1:size(Gmatrix,1) % for number of rows do
                matrixToReturn(i,i)=Gmatrix(i,i)/ (Gmatrix(i,i)^2 + lambda);
end
inverseDiagMatrix=matrixToReturn;

matlab complains about that for loop.

could you please help me adjust it to be parfor compilant?

Regards
Alex

Subject: Parfor statements

From: Edric M Ellis

Date: 10 Feb, 2012 13:37:10

Message: 2 of 2

"Alex " <alaios@yahoo.com> writes:

> could you please help me convert the code below to parfor statements
> matrixToReturn=Gmatrix;
> for i=1:size(Gmatrix,1) % for number of rows do
> matrixToReturn(i,i)=Gmatrix(i,i)/ (Gmatrix(i,i)^2 + lambda);
> end
> inverseDiagMatrix=matrixToReturn;
>

Here's one way:

--8<----8<----8<----8<----8<--
[N, M] = size(Gmatrix);
assert( N == M ) % the following (probably) assumes Gmatrix is square.
% Extract the diagonal to operate on it
diagOfG = diag(Gmatrix);
parfor i=1:N
    diagOfM(i)=diagOfG(i)/ (diagOfG(i)^2 + lambda);
end

% ... But this is probably faster than PARFOR:
% diagOfM = diagOfG ./ ( diagOfG.^2 + lambda );

% Build inverseDiagMatrix
inverseDiagMatrix = Gmatrix;

% Get the indices corresponding to the diagonal
subsToAssign = sub2ind([N, N], 1:N, 1:N);

% And assign into inverseDiagMatrix
inverseDiagMatrix(subsToAssign) = diagOfM;
--8<----8<----8<----8<----8<--

Note that PARFOR "variable slicing" requires that the loop index appears
only once, hence why I extracted the diagonal of Gmatrix outside the
loop. Also note that the vectorized operation on diagOfG is highly
likely to be faster.

Assigning back into the diagonal of inverseDiagMatrix is a bit fiddly,
there might well be a tidier way of doing that....

Cheers,

Edric.

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us