Matlab中预先计算函数的缓存结果 [英] Caching result of pre-computed function in Matlab

查看:85
本文介绍了Matlab中预先计算函数的缓存结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,xy. x是函数的输入,而y是函数的值. 例如,x = [ 1 2 3 4 5 6 7 8 9 10]y = [ 3 6 2 4 1 6 7 0 1 8 ].两者的长度相同.

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.

假设我有另一个包含[ 2 3 8 9 10 3]的数组z(长度与xy不同), 是否有任何函数可以产生输出[6 2 0 1 8 2](相应索引处的返回值),而无需在数组的每个元素之间使用for循环?

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?

非常感谢您

edit1 *如果数组中的数字不是整数,怎么办?

edit1* How can I do if the numbers in the arrays are not integer?

推荐答案

如果您使用的MATLAB版本是2008b以上,则可以使用

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) 

Map类实际上创建了一个所谓的哈希图,因此您几乎可以将任何值映射到其他值(例如字符串,单元格,数组等).

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.

如果不能使用MATLAB 2008b或更高版本,则非整数域值有三种可能.

If you cannot use MATLAB 2008b or newer, there are three possibilities for non-integer domain values.

使用插值方法,例如interp1.这可能会提供错误的值(采用事先未提供的值).您可以使用ismember(z, x)检查该情况.

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).

第二,您可以发明自己的方案,从非整数到整数(例如,如果所有值都是0.5的倍数乘以2)并使用Oli显示的解决方案.

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.

另一种解决方案是使用struct模仿地图的行为.然后,您只需要将域值转换为有效的字段名(即,在MATLAB中为有效变量名的字符串,可以通过使用genvarname函数来实现).

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.

这篇关于Matlab中预先计算函数的缓存结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆