How to optimaze for loop
Show older comments
Hello.
I have this for loop.
[rows,cols]=size(A);
for i=1:1:rows
this_col=A(i:rows,i);
this_col_abs=abs(this_col);
[max_value,max_position]=max(this_col_abs);
max_position=max_position+i-1;
if max_position~=i
max_row=A(max_position,i:cols);
max_row_val=B(max_position);
A(max_position,i:cols)=A(i,i:cols);
B(max_position)=B(i);
A(i,i:cols)=max_row;
B(i)=max_row_val;
end
ss=A(i,i);
A(i,i:cols)=A(i,i:cols)/ss;
B(i)=B(i)/ss;
B(i+1:rows)=B(i+1:rows)-B(i)*A(i+1:rows,i)/A(i,i);
A(i+1:rows,1:cols)=A(i+1:rows,1:cols)-A(i+1:rows,i)*A(i,1:cols)/A(i,i);
end
How can I optimaze this loop;
2 Comments
James Tursa
on 13 Sep 2017
Instead of your readers trying to read your undocumented code and trying to figure out what it is doing, maybe you could give us a description of what the input is and the desired output, and how you are currently going about it. Commenting your code is generally a very good practice.
per isakson
on 14 Sep 2017
- See Profile to Improve Performance
- Nearly all the time is spent in the last line, A(i+1:rows,1:cols)=A(...
Answers (1)
Andrei Bobrov
on 14 Sep 2017
Edited: Andrei Bobrov
on 14 Sep 2017
M = [A,B];
[m,n] = size(M);
for ii = 1:m
D = M(ii:m,ii:n);
[~,k] = max(abs(D(:,1)));
D([1,k],:) = D([k,1],:);
D(1,:) = D(1,:)/D(1,1);
D(2:end,:) = D(2:end,:) - D(2:end,1)*D(1,:);
M(ii:m,ii:n) = D;
end
Categories
Find more on Assembly in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!