I have two arrays, x
and y
. x
is the input of the function and y
is the function values.
For example, x = [ 1 2 3 4 5 6 7 8 9 10]
, y = [ 3 6 2 4 1 6 7 0 1 8 ]
. Both are the same length.
Suppose I have an another array z
containing [ 2 3 8 9 10 3]
(not the same length as x
and y
),
Is there any functions that produce the output [6 2 0 1 8 2]
(return value at corresponding indices) without using for-loop through each element of array?
Thank you so much
edit1* How can I do if the numbers in the arrays are not integer?
That's all you need......
If you are using a MATLAB version newer than 2008b, you can use the containers.Map class to do what you want, even with non-integer, non-consecutive or non-numeric values:
The Map class actually creates a so-called hashmap, so you can map almost any value to other values (e.g. strings, cells, array, ...).
When the item is not present, it will return an error.
If you cannot use MATLAB 2008b or newer, there are three possibilities for non-integer domain values.
Use an interpolation method such as
interp1
. That might give false values (at values that weren't provided beforehand). You can check for that case by usingismember(z, x)
.Secondly, you could invent your own scheme from non-integers to integers (e.g. if all your values are multiples of 0.5, multiply by 2) and use the solution Oli has shown.
The other solution is to use
struct
s to mimic the behavior of a map. Then you only need a conversion from your domain values to valid field names (i.e. strings that are valid variable names in MATLAB, that may be possible by using thegenvarname
function).These last two solutions are somewhat dirty and prone to errors if you don't take rounding into consideration. So I see them only as a last resort.
I think that you just want:
This will return the z'th elements of the y vector. You may want
Which will return the same result in your example, since
x
is just the value 1 through 10.With both of these
z
can contain only positive integers, and in the second casex
must also contain only positive integers.