1

I have a matrix with the first row and the first column are data. Based on the row and the column, I wanna to find values in the matrix. For example, I have the matrix look like this

A =

0.1000    1.0000   10.0000  100.0000
1.0000    0.9000    0.4000    0.5000

If the row data is 1 (the second row) and the column data is 10 (the third column), then I get 0.4 value. Is there a way to find that value? In case of the row data is 0.2 and the column data is 0.2, for example. How can I find values from that matrix? Thank you for your respond.

ironzionlion
  • 832
  • 1
  • 7
  • 28
Hung
  • 13
  • 2

1 Answers1

3

Exact match case

%// Inputs (Added One more row to original post to include multiple match case)
A =[
    0.1000    1.0000   10.0000  10.0000
    1.0000    0.9000    0.4000    0.5000
    1.0000    0.6000    0.5000    0.6000]
row_data = 1.0;
column_data = 10.0;

Now, if you are looking to find the values corresponding to all the matches, use this -

value = A(find(A(:,1)==row_data),find(A(1,:)==column_data))

giving us -

value =
    0.4000    0.5000
    0.5000    0.6000

Otherwise, if you are looking to find the value corresponding to just the first match, use this -

value = A(find(A(:,1)==row_data,1),find(A(1,:)==column_data,1))

giving us -

value =
    0.4000

Also, please be mindful of the precision issues involved with floating point numbers. This shouldn't be a problem here because we have specifically mentioned the numbers and no other calculations had been done between matching and inputting the inputs.


Inexact match case

For cases when there aren't exact matches available, you can use interpolation as shown in codes next -

x = A(1,2:end)
y = A(2:end,1)
[X,Y] = meshgrid(x,y)
V = A(2:end,2:end)

row_data = 1.0;
column_data = 10.0;

value = interp2(X,Y,V,column_data,row_data)

If your Xq or Yq values are outside the X and Y ranges respectively, you need to do extrapolation, for which I think you can use scatteredInterpolant instead of interp2.

Community
  • 1
  • 1
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • I appreciate your answer. As you mentioned in your answer, in case of my row data is 0.2 and my column data is 0.2 (between 0.1 and 1). Do we need to interpolate to find the value. Can we use an interp2 function in this situation? Thanks Divakar – Hung Aug 03 '14 at 15:27
  • @Divakar this can also be accomplished with logical indexing: `A(logical(double(A(:,1)==row_data) * double(A(1,:)==column_data)))` Unfortunately, the conversions to double and back are necessary. – dberm22 Sep 30 '15 at 18:18