Trouble with vectorization of the following code containing for loops and logical indexing

조회 수: 12 (최근 30일)
I have been working on vectorizing my code mostly using bsxfun, but I came across a scenario that I can't quite crack. Here is a small sample of problem. I would like to remove the for loops in this code, but I am having a hard time with the tempEA line.
Index = [2; 3; 4;];
dTime = [25; 26; 27; 28; 25; 26; 27; 28; 27; 28];
dIndex = [3; 3; 3; 2; 1; 3; 2; 4; 4; 2];
aTime = [30; 38; 34; 39; 30; 38; 34; 39; 34; 39];
aIndex = [4; 2; 5; 4; 5; 4; 4; 2; 2; 4];
EA = zeros(numel(Index));
for i = 1:numel(Index)
for j = 1:numel(Index)
tempEA = aTime(Index(i) == dIndex(:,1) & Index(j) == aIndex(:,1));
if i == j
elseif tempEA > 0
EA(i,j) = min(tempEA);
else
EA(i,j) = 50;
end
end
end
The answer should look like this:
EA =
0 50 34
38 0 30
34 50 0
Thanks for help in advance.

채택된 답변

Andrei Bobrov
Andrei Bobrov 2013년 11월 2일
편집: Andrei Bobrov 2013년 11월 2일
ai = bsxfun(@eq,Index(:)',reshape(aIndex,1,1,[]));
di = bsxfun(@eq,Index(:),reshape(dIndex,1,1,[]));
ii = bsxfun(@and,ai,di);
A = bsxfun(@times,ii,reshape(aTime,1,1,[]));
A(A==0)=inf;
EA = min(A,[],3);
EA(1:size(EA,1)+1:end) = 0;
EA(isinf(EA)) = 50;

추가 답변 (0개)

카테고리

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