Matlab使用带结构参数的函数进行插值

问题描述 投票:0回答:1

在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个回答
1
投票

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

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返回相同大小的结构,而不是每个输入字段有一个值的普通数组。

© www.soinside.com 2019 - 2024. All rights reserved.