Converting for loop to vectors

1 次查看(过去 30 天)
for i=1:size(ScFreq,1)
if (ScFreq(i,1)== -Prim)&&(ScFreq(i,5)== 1)
Scr = ScFreq(i,3);
Freq = ScFreq(i,4);
else
if (ScFreq(i,1)== -Prim)&&(ScFreq(i,5)== 2)
if (Scr ~= -1)
ScFreq(i,3) = Scr;
ScFreq(i,4) = Freq;
Scr = -1;
end
end
end
end

采纳的回答

Jan
Jan 2017-6-20
I assume you do not mean "to vectors", but "vectorizing". Most likely you want to accelerate the code. Let's start with some cleaning:
for i = 1:size(ScFreq,1)
if ScFreq(i,1) == -Prim
if ScFreq(i,5) == 1
Scr = ScFreq(i,3);
Freq = ScFreq(i,4);
elseif ScFreq(i,5) == 2 && Scr ~= -1
ScFreq(i,3) = Scr;
ScFreq(i,4) = Freq;
Scr = -1;
end
end
end
It seems, like this code looks for the position of sequences of ScFreq(i,5) == 2 and replaces the first occurence with the last value of ScFreq(i,5) == 1. Now it would be useful to know, of 1 and 2 are the only possible values for the 5th column. Comments and explanations would be useful at all in the forum.
Now it matters how large the matrix is and how frequently ScFreq(i,5) == 2 occurs. A speed optimization without real input data need a lot of guessing. So perhaps:
C1 = (ScFreq(:,1) == -Prim);
C2 = (ScFreq(:,5) == 1 & C1);
index = find(ScFreq(:,5) == 2 & C1).';
for k = index
for m = k-1:-1:1
if C2(m)
ScFreq(k, 3:4) = ScFreq(m, 3:4);
break; % Break for m loop
end
end
end
This might be faster or slower. Please try it and if you want to get more ideas, attach some relevant input data.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by