tobiuchiha
tobiuchiha

Reputation: 73

Finding minimum value of a set of numbers in a column vector in Matlab

I am trying to find minimum value of a set of numbers in a column vector which is part of a matrix. More specifically, if I have a matrix as follows,

 1 2 3  4  2.7
 7 2 3  8  2.3
 5 2 3  9 12.5
10 4 5 12  1.1
11 4 5 13  5.6
14 5 6  7  1.2
15 5 6  8  0.5
16 5 6  9  3.4
17 5 6 12  6.8

then, I would like the output to be as follows,

 7 2 3  8 2.3
10 4 5 12 1.1
15 5 6  8 0.5

I thought about dividing the matrix based on whether columns 2 and 3 are same, and then finding the minimum value of column 5 in every sub-matrix, but I wasn't able to implement it effectively. (Edit: What I tried to do, I first separated the 2nd and 3rd columns of the matrix (say, A), then I used unique to get number of occurrences of repeating rows as follows,

      A_dup = A(:,2:3)
      [A_uni,~,u_id] = unique(A_dup,'rows')
      num_occur = histc(u_id, unique(u_id)) 

The vector 'num_occur' will tell me how to divide the matrix A in sub-matrices. This is not much, but I was stuck after this.)

If there is a better way to do it, I would be glad to know that.

Upvotes: 1

Views: 153

Answers (1)

Sardar Usama
Sardar Usama

Reputation: 19689

Sort the matrix based on the elements of the 5th column using sortrows and get the indices of the sorted elements. Find the row subscripts of the unique rows of the 2nd and 3rd columns of the new matrix . Use these row subscripts with the indices found before to get the row subscripts to be kept from the original matrix. Sort them to maintain the order. Use the sorted new row subscripts to get the required result.

[req, idxA] = sortrows(A, 5);           
[~, idxtmpA] = unique(req(:,2:3), 'rows');
req = A(sort(idxA(idxtmpA)), :);

Upvotes: 1

Related Questions