For-loop vectorization to record logical values

1 回表示 (過去 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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by