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

1 view (last 30 days)
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.

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 2 Nov 2013
Edited: Andrei Bobrov on 2 Nov 2013
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;

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!