[英]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. 首先,您摆脱了零项,然后让Matlab计算每行的最小值。
You should always try to avoid loops in Matlab. 您应该始终尝试避免在Matlab中出现循环。
Though I would recommend a vectorized solution as @ypnos offered, here is one way to make your loop work. 尽管我会推荐@ypnos提供的矢量化解决方案,但这是使循环工作的一种方法。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.