How to find the loaction of an element in an array

Say I have two arrays, one for outside temperature and the other for heat rate. All elements in the array line up and correspond to each other. Is there a way that I could get the location of a certain temperature (from the temperature array) and pull the heat value element (from the heat array) that corresponds to that temperature element location? For example:
T=[0 1 2 3]'; Q=[100 200 300 400]';
I'd want to choose T=2 --> which is in the (3,1) position. How can find out the corresponding Q value? I'm doing this because because the arrays are very large and some of the temperatures are the same values and I want to group the Qs for the same temperature. Thanks

 Respuesta aceptada

Matt Fig
Matt Fig el 27 de Abr. de 2011
T=[0 1 2 3]';
Q=[100 200 300 400]';
Q_T = Q(T==2) % Or, Q(find(T==2)), but not as efficient...
Be aware that if your actual values are not integers, you may need to use a tolerance instead of ==.
If you are grouping using cell arrays, consider:
T = [0 0 1 1 2 2 3 4 5 5].'; % T with some repeats.
Q = [9 6 7 8 8 9 6 6 7 8].';
[J,J,J] = unique(T)
G = accumarray(J(:),Q(:),[],@(x) {x}); % Group Q by unique T...

4 comentarios

Neev Podder
Neev Podder el 28 de Oct. de 2011
Same question I want to ask. I understand your answer but I have floating point numbers in my array. How do I use a tolerance instead of == in my if statement.
Naz
Naz el 28 de Oct. de 2011
It's better if you multiply all the values so you have integers (say be a thousand). Then, after you pull the integer just devide by 1000 to get back your float decimal value.
Naz
Naz el 28 de Oct. de 2011
Also, check out 'nearest'. That should do it.
Jan
Jan el 28 de Oct. de 2011
@Neev: Please post a new problem to a new question.
Checking existence with a tolerance has been discussed repeatedly here.
Do you want a relative or absolute tolerance?

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 27 de Abr. de 2011

Community Treasure Hunt

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

Start Hunting!

Translated by