在 Matlab 中对不同时间的矩阵进行插值
Interpolate matrices for different times in Matlab
我已经为特定时间向量计算了存储在矩阵中的变量。
现在我想在这些整个矩阵之间插值一个新的时间向量以获得所需的新时间向量的矩阵。
我想出了以下解决方案,但它看起来笨拙且计算量大:
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]
有什么想法吗?
我真的没有发现基于循环的方法有什么问题,但是如果您正在寻找一种无循环的方法,您可以执行以下操作。
[rows, cols, ~] = size(a);
aReshape = reshape(a, rows*cols, []).';
tabInterp = reshape(interp1(t1, aReshape, t2).', rows, cols, []);
查看 interp1
的源代码,似乎正在使用 for
循环,所以我怀疑这是否会带来任何性能提升。
您可以一次手动进行线性插值...
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
包含超过 2 个元素,您可以使用 interp1
创建缩放向量 m
。这是相对有效的,因为您只使用 interp1
作为时间向量,而不是矩阵:
m = interp1( t1, (t1-min(t1))/(max(t1)-min(t1)), t2, 'linear', 'extrap' );
这对 .*
操作使用隐式扩展,这需要 R2016b 或更新版本。如果您有较旧的 MATLAB 版本,请使用 bsxfun
实现相同的功能。
我已经为特定时间向量计算了存储在矩阵中的变量。 现在我想在这些整个矩阵之间插值一个新的时间向量以获得所需的新时间向量的矩阵。
我想出了以下解决方案,但它看起来笨拙且计算量大:
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]
有什么想法吗?
我真的没有发现基于循环的方法有什么问题,但是如果您正在寻找一种无循环的方法,您可以执行以下操作。
[rows, cols, ~] = size(a);
aReshape = reshape(a, rows*cols, []).';
tabInterp = reshape(interp1(t1, aReshape, t2).', rows, cols, []);
查看 interp1
的源代码,似乎正在使用 for
循环,所以我怀疑这是否会带来任何性能提升。
您可以一次手动进行线性插值...
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
包含超过 2 个元素,您可以使用 interp1
创建缩放向量 m
。这是相对有效的,因为您只使用 interp1
作为时间向量,而不是矩阵:
m = interp1( t1, (t1-min(t1))/(max(t1)-min(t1)), t2, 'linear', 'extrap' );
这对 .*
操作使用隐式扩展,这需要 R2016b 或更新版本。如果您有较旧的 MATLAB 版本,请使用 bsxfun
实现相同的功能。