0%

matlab小程序简记:用于矩阵或向量,提取出前N大的元素并返回其大小和位置

今天用matlab写了DIP中的大津算法和霍夫算法(直线),写后者时产生了这个衍生品,后来发现不用这个衍生品也可以写完Hough算法,但是个人认为这个函数还比较实用,所以记录在这里备忘。


源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
function [MaxValueVector,MaxIndexVector] = SortNValues(Matrix,n)
%SortNValues 给定一个矩阵或者向量,排出前五个最大的数,返回这五个数的数量(从大到小,vector)以及位置



MaxValueVector = zeros(1,n);
MaxIndexVector = zeros(2,n);

if(size(Matrix,1)==0||size(Matrix,2)==0)
return;
end


for i = 1:n
MaxValueVector(1,i) = max(Matrix,[],'all');

[MaxIndexRow,MaxIndexCol] = find(Matrix==max(Matrix,[],'all'));

MaxIndexRow1 = 0;
MaxIndexCol1 = 0;

if(size(MaxIndexRow,1)~=1||size(MaxIndexCol,2)~=1)
MaxIndexRow1 = MaxIndexRow(1);
MaxIndexCol1 = MaxIndexCol(1);
else
MaxIndexRow1 = MaxIndexRow;
MaxIndexCol1 = MaxIndexCol;
end



MaxIndexVector(:,i) = [MaxIndexRow1;MaxIndexCol1];
Matrix(MaxIndexRow1,MaxIndexCol1) = -Matrix(MaxIndexRow1,MaxIndexCol1);



end

end

简单的使用例


输入的是矩阵

1
2
3
4
5
6
7
8
a = 1:10;
b = 2:11;
c = [a;b];
[m,n] = SortNValues(c,5);
%m = [11,10,10,9,9]
%n = [
% 2,2,1,2,1;
% 10,9,10,8,9]

输入的是向量

1
2
3
4
5
6
a = 1:10;
[m,n] = SortNValues(a,5);
%m = [10,9,8,7,6]
%n = [
% 1,1,1,1,1;
% 10,9,8,7,6]