Using indexing for two arrays of different lengths
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I have two separate arrays, x = 1244 x 1 and y = 1244 x 1050. I want to be able to index specific values within the x array and then find the corresponding index's within the y array. So far my code reads:
x_1= find(x == 799.6585468680)
x_2 = find(x == 3995.72148499300)
x_3 = find(x == 2021.00198661820)
y_1 = find(y == x_1)
y_2 = find(y == x_2)
y_3 = find(y == x_3)
The values input here are specifically from my data. This reads out:
x_1 =
1
x_2 =
1244
x_3 =
476
y_1 =
0×1 empty double column vector
y_2 =
0×1 empty double column vector
y_3 =
0×1 empty double column vector
However this gives me a load of empty double column vectors, I know I should be looping it to make sure I get the xth index value from every column in the y array, but I am very lost as to how I achieve this. Is there an obvious function I should be using?
0 comentarios
Respuestas (1)
Guillaume
el 14 de Sept. de 2017
The first issue with what you're doing is with
x == some_non_integer_value
It will work for some values. For others, it won't, e.g:
x = 0.1 + 0.1 + 0.1 % == 0.3 right?
x == 0.3 % guess not, return false, find would return empty!
This is due to the way numbers are stored on computers. Not all decimal values can be stored exactly (e.g 0.1 can't), meaning that testing for exact decimal value is dangerous. The proper way to compare floating point values is to check that their absolute difference is smaller than a value much smaller than their magnitude:
abs(x - 0.3) <= 1e-10 %test for equality
Second issue:
y_1 = find(y == x_1)
Remember that x_1, if not empty, is an index, always integer, from 1 to 1244. That is what you're searching for in y. From your description, I don't think that's what you meant to do. The above line will also fail if the find for x_1 returned more than index (i.e. the search value is present more than once in x).
"I know I should be looping". Most likely not. It is likely that it can all be done in a few lines with no loop. E.g, all your x_i could be found in one go with
searchvalues = [799.6585468680, 3995.72148499300, 2021.00198661820];
[found, where] = ismembertol(searchvalues, x)
where would correspond to your [x_1, x_2, x_3]
A better explanation of what you're trying to do with y (provide an example with numbers) would allow me to complete this answer.
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!