xxsou
xxsou

Reputation: 43

Find row with closest first element

I have a matrix like

a = [ 4.1    45    65    84    84 , 
      4.2    62    78    83    43 , 
      4.3    84    94    93    94 ]

and a vector like

b = [ 4.123  4.21   4.31   4.19 ] 

For every element in vector b, I want to find the row in a, for which the element in the first column is closest to this element from b. Finally, I want to concatenate the elements of b and the corresponding row to form a new matrix c.

So the final matrix looks like

c = [ 4.123   45    65    84    84 ,
      4.21    62    78    83    43 , 
      4.31    84    94    93    94 ,
      4.19    62    78    83    43 ]

Upvotes: 2

Views: 93

Answers (1)

hbaderts
hbaderts

Reputation: 14371

You can use the bsxfun function to create a matrix, which contains the difference between each element in b and each element of the first column of a:

bsxfun(@minus,b,a(:,1))
ans =
   -0.0230   -0.1100   -0.2100   -0.0900
    0.0770   -0.0100   -0.1100    0.0100
    0.1770    0.0900   -0.0100    0.1100

Each row of the matrix corresponds to one element in a(:,1), and each column to one element in b. i.e. the element (3,1) is equal to b(1)-a(3,1).

To find the nearest values, let's look at the absolute values abs() and find the smallest value of every column using the min function. The first return value of min is the minimal value of each column, the second return value is the index. We only need the index, so we discard the first return value using ~.

[~,minRow] = min(abs(bsxfun(@minus,a(:,1),b)))
minRow =
     1     2     3     2

We now know, which row of a we have to use, so we can construct the matrix by concatenating b and the correct row of a into one matrix:

c = [ b.', a(minRow,2:end) ];
c =
    4.1230   45.0000   65.0000   84.0000   84.0000
    4.2100   62.0000   78.0000   83.0000   43.0000
    4.3100   84.0000   94.0000   93.0000   94.0000
    4.1900   62.0000   78.0000   83.0000   43.0000

Upvotes: 7

Related Questions