How to optimaze for loop

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 个评论

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.

请先登录,再进行评论。

回答(1 个)

Andrei Bobrov
Andrei Bobrov 2017-9-14
编辑:Andrei Bobrov 2017-9-14
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

类别

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by