Help optimizing/vectorizing a code in which loops are used to fill several vectors

1 次查看(过去 30 天)
Hello,
I'm trying to fill in several vectors from the info that I have on a text file. I load the different columns of that file o severall Arrays A, B, C, D, E, F, and G.
The size of my vectors is quite big, (10^6 or 10^7) elements so the code I show next takes a long time to run.
Can someone help me with a vectorization of this in order to make it faster?
[A,B,C,D,E,F,G] = textread(strcat(PathName,FileName),'%f %d %d %d %d %s %s');
n=size(A,1);
for i=1:n
if C(i) == 0 && D(i) == 0
prim(i)=A(i);
elseif C(i)==0 && D(i) ~= 0
sc(i)=A(i);
elseif C(i)~=0 && C(i) ==0
sc2(i)=A(i);
end
if C(i)+D(i)==1
o1(i)=A(i);
elseif C(i)+D(i)==2
o2(i)=A(i);
elseif C(i)+D(i)==3
o3(i)=A(i);
elseif C(i)+D(i)==4
o4(i)=A(i);
elseif C(i)+D(i)>4
osup(i)=A(i);
end
end
  1 个评论
Kevin Holst
Kevin Holst 2012-7-31
I haven't looked into your code too much but I believe this line is incorrect anyways:
elseif C(i)~=0 && C(i) ==0
shouldn't it be:
elseif C(i)~=0 && D(i) ==0

请先登录,再进行评论。

采纳的回答

John Petersen
John Petersen 2012-7-31
Here's one way to do it
sc = [];
i = (~C & D);
sc(i) = A(i);
o3 = zeros(n,1);
CpD = C + D;
i3 = find(CpD ==3);
i4 = find(CpD ==4);
o3(i3) = A(i3);
o4(i4) = A(i4);
Follow similar logic for the rest of your code.

更多回答(1 个)

carlos Uribe
carlos Uribe 2012-8-1
Thanks very much for taking a look at this...worked like a charm

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by