Finding column 2 values for column 1 value in a multidimensional array

I have a (:,2) array of data, where column 1 are x-values and column 2 are y-values.
I have a calculated y-value saved as a variable (like B shown below), and I want to:
(1) locate the y-values closest to my variable B and (2) extract the x-values that correspond to these y-values.
For the example below, I would want to find the y-values 0.11 and then extract the x-values 0.22 and 0.33 into an array.
Here is a simplified version of my issue:
A = [0.22 0.11; 0.33 0.11; 0.55 0.66]
A =
0.2200 0.1100
0.3300 0.1100
0.5500 0.6600
B = 0.12;
B1 = 0.12 + 0.01;
B2 = 0.12 - 0.01;
idx = find(A < B1 && A > B2);
I get this error: Operands to the || and && operators must be convertible to logical scalar values.
Can I not use variables when setting conditions for find? I am a MATLAB novice so any help would be much appreciated!

 Accepted Answer

A = [0.22 0.11; 0.33 0.11; 0.55 0.66];
B = 0.12;
idx=ismembertol(A,B,0.1);
x=A(any(idx,2),1)
y=A(any(idx,2),2)
Gives:
x =
0.2200
0.3300
y =
0.1100
0.1100

4 Comments

This works perfectly for this data set.
I looked into ismembertol and the 0.1 tolerance you set will only work for this data set.
This was just an example set for me, my actual data has vastly different x-values from y-values ( ex. x = 49.05 y = 0.1014). What should I do in this case when I can't set a tolerance?
I think mucking around with the uniquetol will solve my issue. Thank you!
Anytime :) , if my answer helped you solve your problem make sure to accept the answer.

Sign in to comment.

More Answers (1)

The comparisons A < B1 or A > B2 each product a logical vector. So you need to do an AND operation element by element with &. You used && which takes two scalar variables. So this should work:
indexes = find(A < B1 & A > B2);
You will now get linear indexes (not logical since were using the find function) where BOTH of those conditions are true.

2 Comments

I get:
idx =
0×1 empty double column vector
when I change my code to idx = find(A < B1 & A > B2)
Correct! With your data
A =
0.2200 0.1100
0.3300 0.1100
0.5500 0.6600
There is no element that is in the range 0.11 to 0.13 (non-inclusive), which would mean both less than 0.13 and greater than 0.11.
If you want to include the 0.11 you can use >= instead of >
indexes = find(A <= B1 & A >= B2)

Sign in to comment.

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!