필터 지우기
필터 지우기

For-loop vectorization to record logical values

조회 수: 2 (최근 30일)
Alfredo
Alfredo 2013년 3월 8일
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

답변 (1개)

Matt J
Matt J 2013년 3월 8일
편집: Matt J 2013년 3월 8일
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
Alfredo
Alfredo 2013년 3월 12일
Yes it is, but it adds information to the LT matrix and I can't see how to merge the two sections of my whole code in just one loop. Thank you.
Matt J
Matt J 2013년 3월 12일
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.';

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by