【问题标题】:Matlab Use function with structure parameter to interpolateMatlab使用带有结构参数的函数进行插值
【发布时间】:2019-04-18 19:37:26
【问题描述】:

在 MATLAB 中,我想使用将参数输入作为结构体的函数对一组数据进行插值。但是,我收到一个错误。

我有一个结构:

fruit.apples = [3 4 2 3 4]
fruit.oranges = [1 0 0 0 0]
fruit.grapes = [2 3 2 2 1] 

所以我想把这个水果结构插入到samples = 20;`

这是我的代码:

function [output] = fruitbasket (fruit, samples)
sampleLength = linspace(1, numel(data), samples + numel(data));
sampleLength = sampleLength';
output = interp1(data, sampleLength);

我希望的输出是在水果篮结构中用 25 个苹果、25 个橙子和 25 个葡萄对每个数组进行插值。如果将结构替换为变量,则代码可以工作,但我需要使用结构,以便可以将多个输入传递给函数。

【问题讨论】:

    标签: matlab structure interpolation


    【解决方案1】:

    您可以使用structfun 将函数应用于结构数组的每个元素。在这种情况下,它看起来像这样:

    fruit.apples = [3 4 2 3 4];
    fruit.oranges = [1 0 0 0 0];
    fruit.grapes = [2 3 2 2 1];
    samples = 20;
    
    interp_data = @(d)interp1(d, linspace(1, numel(d), samples + numel(d)));
    output = structfun(interp_data, fruit, 'UniformOutput',false);
    

    structfun 需要一个函数句柄,它在输入结构的每个字段上调用该函数。我们创建一个匿名函数来传递给它,我们在其中填写其他参数。 OP 中的sampleLength 是在这个匿名函数中计算的,以防结构中的元素都是不同大小的。最后,我们将'UniformOutput' 设置为false 以告诉structfun 返回相同大小的结构,而不是每个输入字段一个值的普通数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多