How to get the three maximum values from a vector
22 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi, I want to know an efficient way of getting the three maximum values of a vector. Here is the whole question.
First I have a binary row vector of size n^2. This whole string can be split into substrings to form a matrix of order nxn. Then I sum the values of each column and it gives me a vector of size n of integers. for example, the string
0 0 1 0 1 0 - 0 0 0 1 1 1 -1 1 0 0 1 0 - 1 0 0 0 0 0 - 1 1 1 1 1 0
I used the next code to do the sum described above
for i=1:5
suma=0;j=i;
while(j<=5*5)
suma=prueba(j)+suma;
j=j+5;
end
vectorExito(i)=suma;
end
The vectorExito must be (3 2 2 2 4 1). I want to create a vector which has 1's in the positions that contains the three maximum values, otherwise 0's.
In this case I want the vector (1 1 1 1 1 0 ). Other example, if vectorExito is (2 3 4 4 5 1) then I want the vector (0 1 1 1 1 0). Other If vectorexito is (5 5 5 4 4 3) then the vector I want is ( 1 1 1 1 1 1).
How do I get the final binary vector given some vectorExito?
1 Kommentar
Image Analyst
am 18 Sep. 2012
You have 6 groups of five 0 or 1 values, so how can you group that into a 5x5 square array?
Akzeptierte Antwort
Azzi Abdelmalek
am 18 Sep. 2012
Bearbeitet: Azzi Abdelmalek
am 18 Sep. 2012
v=[5 2 4 4 1];
c=[0 0 unique(sort(v))];
res=zeros(1,length(v));
res(find(ismember(v,c(end-2:end))))=1
2 Kommentare
Azzi Abdelmalek
am 18 Sep. 2012
Bearbeitet: Azzi Abdelmalek
am 18 Sep. 2012
ismember(v,c(end-2:end))=
1 1 1 1 0
%what I need is the index corresponding to the true values
find(ismember(v,c(end-2:end)))=
1 2 3 4
% why [0 0 ?
in case
v=[2 2 2 2 2]
unique(sort(v))=2
then I can't compute c(end-2:end)
Weitere Antworten (2)
Image Analyst
am 18 Sep. 2012
Bearbeitet: Image Analyst
am 18 Sep. 2012
Try this:
% Generate sample data.
prueba = [0 0 1 0 1 0 0 0 0 1 1 1 1 1 0 0 1 0 1 0 0 0 0 0 1 1 1 1 1 0]
% Reshape into a 5 row by 6 column array.
m5x6 = reshape(prueba, [6 5])'
% Sum columns.
vectorExito = sum(m5x6)
% Sort in descneding order to find the highest values.
[sortedValues sortedIndexes] = sort(vectorExito, 'descend')
% Option below (depends on how you define the "third highest value"):
% sortedValues = fliplr(unique(sortedValues))
% Create the logical (boolean) output vector that is wanted.
% First get the third highest value.
thirdHighestValue = sortedValues(3);
wantedVector = vectorExito >= thirdHighestValue
Results:
prueba =
Columns 1 through 14
0 0 1 0 1 0 0 0 0 1 1 1 1 1
Columns 15 through 28
0 0 1 0 1 0 0 0 0 0 1 1 1 1
Columns 29 through 30
1 0
m5x6 =
0 0 1 0 1 0
0 0 0 1 1 1
1 1 0 0 1 0
1 0 0 0 0 0
1 1 1 1 1 0
vectorExito =
3 2 2 2 4 1
sortedValues =
4 3 2 2 2 1
sortedIndexes =
5 1 2 3 4 6
wantedVector =
1 1 1 1 1 0
0 Kommentare
Siehe auch
Kategorien
Mehr zu Cell Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!