How to Speed Up matlab for cycle?
Show older comments
im actually doing a code to use in a program based in the rain flow counting algorithm. The code has to read some huge vectors (ex:200000x1) and the cycle that im using is too slow. Could somebody help me to turn it faster, please???
A part of the code that im using is written below:
for i=1:N-1
if A(i+1) > A(i)
i=i+1;
maximo = A(i);
j= j + 1;
locais(j) = maximo;
elseif A(i+1) < A (i)
i=i+1;
minimo = A(i);
j= j + 1;
locais(j) = minimo;
end
end
locais=locais(:);
for k=1:j
B(k)=locais(k)';
end
B=B(:);
%%RAINFLOW METHOD
i=1;
for i=1:j
valores(i) = B(i);
aux(i)=valores(i);
i=i+1;
end
num=i;
d=1;
for d=1:N
i=1;
for i=1:j
valores(i)=aux(i);
end
k=length(valores);
for i=2:k-2
if valores(i-1)~=valores(i+1)
if valores(i-1) <= valores(i+1) && valores(i+1) < valores(i) ...
&& valores(i) <= valores(i+2)
guarda(i,1)=1;
S=abs(valores(i)-valores(i+1));
guarda(i,2)=S;
aux(i)=0;
aux(i+1)=0;
elseif valores(i-1) >= valores(i+1) && valores(i+1) > valores(i) ...
&& valores(i) >= valores(i+2)
guarda(i,1)=1;
S=abs(valores(i)-valores(i+1));
guarda(i,2)=S;
aux(i)=0;
aux(i+1)=0;
end
else
end
end
valores=[];
aux(find(aux==0)) = [];
j=length(aux);
d = d + 1;
end
Y_cf1=guarda(:,1);
Z_cf1=guarda(:,2);
Y_cf1=Y_cf1(Y_cf1~=0);
Z_cf1=Z_cf1(Z_cf1~=0);
Sc_cf1=[Y_cf1,Z_cf1] %Ciclos Completos
j=length(aux);
for i=1:j-1
if aux(i+1) > aux(i)
minimo = aux(i);
i = i + 1;
maximo = aux(i);
guarda_2(i,1)=0.5;
S2=abs(maximo-minimo);
guarda_2(i,2)=S2;
elseif aux(i+1) < aux(i)
maximo = aux(i);
i = i + 1;
minimo = aux(i);
guarda_2(i,1)=0.5;
S2=abs(maximo-minimo);
guarda_2(i,2)=S2;
else
end
end
Thanks in advance. Greetings Fagner Furtado
Accepted Answer
More Answers (1)
dpb
on 28 Jun 2013
OK, since the same thing is done under both branches of the if...else construct, one can replace the loop by logical addressing
f1=[0; (v(3:end-1)~=v(1:end-3))]'; % first if logical vector
% The if and else conditions...
f2=[0; v(1:N-3)<=v(3:N-1) & v(3:N-1)<v(2:N-2) & v(2:N-2)<=v(4:N)]';
f3=[0; v(1:N-3)>=v(3:N-1) & v(3:N-1)>v(2:N-2) & v(2:N-2)>=v(4:N)]';
% so, the clauses are executed if f1 and either f2 or f3...
f=f1&(f2|f3);
% then
g(f,1)=1;
g(f,2)=abs(diff(v(f)));
I've not had time to test but that appears to be ok methinks...
Can you explain the role of d? One poster in clf had a routine in Fortran that appears to be the algorithm and says the d is a residual but there aren't a lot of comments and those there are are in French which I don't read well enough to follow, unfortunately.
Or, a link to the reference would be good...
Again, I've posted the above in a thread in the newsgroup where it's much easier to interact if you want to follow up further.
Categories
Find more on Language Support 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!