For-loop vectorization to record logical values
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Hello, I would like to vectorize the following for-loop.
The idea is to record in the LT matrix links specified in the NEc variable (a logical variable of zeros and ones).
%%Build Link Table
LT = false(nIP,nIP); % [logical] - Link Table (each IP has 4 Neighbors)
% Near Edges
NEIP = NaN(max(sum(NEc)),NE_NoOT); % Near Edge Intersection Points
Nlvi = NaN(NE_NoOT,1); % last valid index for NEIP variable
I=cell(NE_NoOT,1); J=I;
for i = 1:NE_NoOT % Spanning all Near Edge traces
n = find(NEc(:,i)); % i-th NE trace IP indexes
Nlvi(i) = size(n,1); % NEIP last valid index for i-th NE curve
NEIP(1:Nlvi(i),i) = n; % IPs
end
% Far Edges
FEIP = NaN(max(sum(FEc)),FE_NoOT); % Far Edge Intersection Points
Flvi = NaN(FE_NoOT,1); % last valid index for FEIP variable
for i = 1:FE_NoOT % Spanning all Far Edge traces
n = find(FEc(:,i)); % i-th FE trace IP indexes
Flvi(i) = size(n,1);
for j = 1:Flvi(i)-1 % Spanning Fear Edge points on the i-th FE trace
LT(n(j),n(j+1)) = 1; % record link
LT(n(j+1),n(j)) = 1; % record same link
end
FEIP(1:Flvi(i),i) = n;
end
After the loop I need to keep the LT, NEIP and Nlvi variables.
Any idea?
Thank you
PD: you can answer this question also on Stack Overflow to gain reputation: http://stackoverflow.com/q/15295191/2133028
0 comentarios
Respuestas (1)
Matt J
el 8 de Mzo. de 2013
Editada: Matt J
el 8 de Mzo. de 2013
I don't anticipate any benefit to getting rid of the outer loop, especially if you really do need all those intermediate variables. However, you can eliminate the inner loop as follows;
I=cell(NE_NoOT,1); J=I;
for i = 1:NE_NoOT % Spanning all Near Edge traces
n = find(NEc(:,i)); % i-th NE trace IP indexes
I{i}=n(1:end-1).'; J{i}=n(2:end).';
Nlvi(i) = length(N); % NEIP last valid index for i-th NE curve
NEIP(1:Nlvi(i),i) = n;
end
LT=sparse([I{:}],[J{:}],true,nIP,nIP);
LT=LT|LT.';
4 comentarios
Matt J
el 12 de Mzo. de 2013
I=cell(NE_NoOT,1); J=I;
for i = 1:NE_NoOT % Spanning all Near Edge traces
n = find(NEc(:,i)); % i-th NE trace IP indexes
Nlvi(i) = size(n,1); % NEIP last valid index for i-th NE curve
NEIP(1:Nlvi(i),i) = n; % IPs
n = find(FEc(:,i)); % i-th NE trace IP indexes
I{i}=n(1:end-1).'; J{i}=n(2:end).';
Flvi(i) = length(n); % NEIP last valid index for i-th NE curve
FEIP(1:Nlvi(i),i) = n;
end
LT=sparse([I{:}],[J{:}],true,nIP,nIP);
LT=LT|LT.';
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!