简体   繁体   中英

finding minimum number in each matrix row

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!

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM