0

I am attempting to write a code to find a minimum number from the 'distance' matrix, excluding zeroes from the matrix.

distance=[0    0.44    0.40    0.63    0.89
0.44    0       0.44    0.72    1.00
0.40    0.44    0       0.28    0.56
0.63    0.72    0.28    0       0.28
0.89    1.00    0.56    0.28    0]

for  i=1:Nodes
    for  j=1:Nodes
        if (distance(i,j)~=0)

        [mini(i,:)]=[min(distance(i,:))];
        end
    end
end

Any help is appreciated! Thank you!

4
  • What results does the code that you have give you? Commented Jul 15, 2013 at 22:19
  • it gives me an array of zeros :( Commented Jul 15, 2013 at 22:20
  • use dinstead of distance. Commented Jul 15, 2013 at 22:20
  • that ain't the issue, sir!! Commented Jul 15, 2013 at 22:22

2 Answers 2

5

The correct answer is:

d = distance;
d(~d) = inf;
mini = min(d);

First you get rid of the zero entries, then you let Matlab calculate the minimum per row.

You should always try to avoid loops in Matlab.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! I will try and avoid loops in my further programs!
Very nice, this definately answers the question as it was asked. However @happyme as it is a distance matrix, you usually may be more interested in this instead: d(logical(eye(size(d)))) = Inf This enables you to calculate the minimum distance to 'other' points. (Same result for your example matrix)
0

Though I would recommend a vectorized solution as @ypnos offered, here is one way to make your loop work.

mini = inf(1,Nodes)
for  i=1:Nodes
    for  j=1:Nodes
        if (distance(i,j)~=0) %Consider using if i~=j if you want the distance to 'other' points
            mini(j)=min(distance(i,j),mini(j));
        end
    end
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.