Caching result of pre-computed function in Matlab

2020-03-28 02:23发布

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?

3条回答
戒情不戒烟
2楼-- · 2020-03-28 02:39
y(z)

That's all you need......

查看更多
forever°为你锁心
3楼-- · 2020-03-28 02:55

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:

 x  = [ 1 2 3 4 5 6 7 8 9 10];
 y  = [ 3 6 2 4 1 6 7 0 1 8 ];
 z  = [ 2 3 8 9 10 3];
 F  = containers.Map(x,y);
 % for a single element:
 Fz1 = F(z(1))
 % for multiple elements at the same time, you need to use arrayfun
 Fz = arrayfun(@(x)(F(x)),z) 

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 using ismember(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 structs 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 the genvarname 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.

查看更多
戒情不戒烟
4楼-- · 2020-03-28 03:04

I think that you just want:

y(z);  

This will return the z'th elements of the y vector. You may want

y(x(z));

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 case x must also contain only positive integers.

查看更多
登录 后发表回答