|
"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.
|