Reputation: 189
I have a piece a code for an exam, what They want me to do in order to achieve a better grade is to implement the same thing without a second "for" statement.
The code is:
piv = 1:n; %// piv: position vector
for k = 1:n-1 %// for each column :
if ((max(abs(A(piv(k:n),k)))) > eps(normA)) %// if pivot is non zero
[~, I] = max(A(piv(k:n),k)); %// find the max index
I = I + (k-1);
piv([k,I]) = piv([I,k]); %// swap pivot elements
A(piv(k+1:n),k) = A(piv(k+1:n),k)/A(piv(k),k); %// calculate the multipliers and save them in the column
for j = k+1:n
A(piv(j),k+1:n) = A(piv(j),k+1:n) - (A(piv(k),k+1:n)*A(piv(j),k)); %// multiply for multipliers and subtract them by the row
end
end
end
This is the Gauss factorizing method but doesn't matter, the matter is I need to have the same result without the second for e and the j variable.
Upvotes: 3
Views: 461
Reputation: 221524
You can certainly kill the innermost loop with bsxfun
. I am leaving it to you to explain to your prof on how it does what it does. Going through the bsxfun docs would be a good idea and in this process you might learn some vectorization techniques
. Here's the implementation -
parte2 = bsxfun(@times,A(piv(k),k+1:n),A(piv(k+1:n),k))
A(piv(k+1:n),k+1:n) = A(piv(k+1:n),k+1:n) - parte2
Upvotes: 3