Pregunta

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.

¿Fue útil?

Solución

This uses bsxfun; no loops. It assumes you don't have NaN's among your aTimevalues.

N = numel(Index);
ii = bsxfun(@eq, dIndex.', Index); %'// selected values according to each i
jj = bsxfun(@eq, aIndex.', Index); %'// selected values according to each j
[ igrid jgrid ] = ndgrid(1:N); %// generate all combinations of i and j
match = double(ii(igrid(:),:) & jj(jgrid(:),:)); %// each row contains the matches for an (i,j) combination
match(~match) = NaN; %// these entries will not be considered when minimizing
result = min(bsxfun(@times, aTime, match.')); %'// minimize according to each row of "match"
result = reshape(result,[N N]);
result(isnan(result)) = 50; %// set NaN to 50
result(result<=0) = 50; %// set nonpositive values to 50
result(1:N+1:end) = 0; %// set diagonal to 0

The line result(result<=0) = 50; is only necessary if your aTime can contain nonpositive values. Can it? Or is your elseif tempEA > 0 just a way of checking that tempEA is not empty?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top