【问题标题】:Interpolate matrices for different times in Matlab在 Matlab 中插入不同时间的矩阵
【发布时间】:2018-08-09 16:31:21
【问题描述】:

我已经为特定时间向量计算了存储在矩阵中的变量。 现在我想在这些整个矩阵之间插入一个新的时间向量,以获得所需的新时间向量的矩阵。

我想出了以下解决方案,但它似乎笨重且计算要求高:

clear all;

a(:,:,1) = [1 1 1;2 2 2;3 3 3]; % Matrix 1
a(:,:,2) = [4 4 4;6 6 6;8 8 8]; % Matrix 2

t1 = [1 2]; % Old time vector

t2 = [1 1.5 2]; % New time vector

% Interpolation for each matrix element
for r = 1:1:size(a,2)
for c = 1:1:size(a,1)
tab(:) = a(r,c,:);
tabInterp(r,c,:) = interp1(t1,tab(:),t2);
end
end

结果是并且应该是:

[2.5000    2.5000    2.5000
    4.0000    4.0000    4.0000
    5.5000    5.5000    5.5000]

有什么想法吗?

【问题讨论】:

    标签: matlab grid interpolation


    【解决方案1】:

    您可以手动进行线性插值,并且一次完成...

    m = ( t2 - t1(1) ) / ( t1(2) - t1(1) );  
    % Linear interpolation using the standard 'y = m*x + c' linear structure
    tabInterp = reshape(m,1,1,[]) .* (a(:,:,2)-a(:,:,1)) + a(:,:,1);
    

    这适用于任何大小的 t2,只要 t1 有 2 个元素。

    如果t1 有两个以上的元素,则可以使用interp1 创建缩放向量m。这是相对有效的,因为您只使用interp1 作为时间向量,而不是矩阵:

    m = interp1( t1, (t1-min(t1))/(max(t1)-min(t1)), t2, 'linear', 'extrap' );
    

    这使用 .* 操作的隐式扩展,这需要 R2016b 或更高版本。如果您的 MATLAB 版本较旧,请使用 bsxfun 来获得相同的功能。

    【讨论】:

    • @jodag 我已经更新了我的答案并解决了这个问题,现在可以用多个值 t1 一次性完成。
    • 感谢您的宝贵意见。它完美无瑕。我也尝试过使用 interp3。你觉得哪个更快?清除所有; a(:,:,1) = [1 1 1;2 2 2;3 3 3]; % 矩阵 1 a(:,:,2) = [4 4 4;6 6 6;8 8 8]; % 矩阵 2 t1 = [1 2]; % 旧时向量 t2 = [1 1.5 2]; % 新时间向量 % 每个矩阵元素的插值 [X, Y, Z] = meshgrid(1:size(a,1), 1:size(a,2), t1); [X2, Y2, Z2] = meshgrid(1:size(a,1), 1:size(a,2), t2); tabInterp = interp3(X,Y,Z,a,X2,Y2,Z2);
    • 你为什么不timeit 看看?如果你想问一个相关但不同的性能问题,作为一个新问题而不是在 cmets 中这样做更容易:)
    【解决方案2】:

    我真的不认为基于循环的方法有问题,但如果您正在寻找一种无循环的方法,您可以执行以下操作。

    [rows, cols, ~] = size(a);
    aReshape = reshape(a, rows*cols, []).';
    tabInterp = reshape(interp1(t1, aReshape, t2).', rows, cols, []);
    

    查看interp1 的源代码,它似乎正在使用for 循环,所以我怀疑这会带来任何性能提升。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-08
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      • 1970-01-01
      相关资源
      最近更新 更多