0 arrays matlab linear-interpolation
我正在尝试在matlab中编写线性插值脚本.如何修复向量长度不同的问题?
我试图绕过这个问题,但似乎无法得到它.if语句是否应包含在for循环中的任何位置?
z = linspace(0,1000,21)
vel = 1500*z^0.1;
% I want to interpolate vel between the 201 elements of depths.
depths = [0:5:1000];
numel_depths = numel(depths);
for ii = 1:numel_depths %Going through all indices of depths
lower = find(z > depths(ii),1); % Finding x0 and x1.
higher = find(z < depths(ii),1,'last');
V2(ii) = vel(lower) + ((vel(higher) - vel(lower))/(z(higher)-
z(lower)))*(depths(ii)-z(lower)); % linear interpolation step
end
Run Code Online (Sandbox Code Playgroud)
现在它返回一个错误,说不同的边有不同数量的元素.有没有办法解决这个问题,以便它作为已安装在MATLAB中的interp1函数工作?
您的代码有几个问题:
您需要按照元素方式的幂运算符来定义vel,如您必须看到的错误消息所示:
vel = 1500*z.^0.1; % Use .^ rather than ^
Run Code Online (Sandbox Code Playgroud)有一个机会,lower或者upper是空的,如果没有点在你正在测试的范围.您需要使用以下测试跳过这些情况:
~isempty( lower ) && ~isempty( higher )
Run Code Online (Sandbox Code Playgroud)您尚未使用有效的行继续.在MATLAB中,您不仅可以断开一条线,还必须...在虚线的末尾添加省略号().
您正在使用严格的不平等>和<,这意味着你错过的边界点,你应该包括在插值(演示下文).
你应该在for循环之前预先分配数组,所以
v2 = NaN(size(depths)); % Define output V2 to be same size as input depths
Run Code Online (Sandbox Code Playgroud)lower 是一个内置的MATLAB函数,用于使字符串小写,避免将其用作变量名.
修复上述所有内容如下:
z = linspace(0,1000,21);
vel = 1500*z.^0.1; % Element-wise power operator
depths = 0:5:1000;
V2 = NaN(size(depths)); % Pre-allocate output array
for ii = 1:numel(depths);
% Finding x0 and x1, inclusive of boundaries (>= or <=).
% Using 'x0' and 'x1' as var names to avoid shadowing the 'lower' function
x0 = find(z >= depths(ii),1);
x1 = find(z <= depths(ii),1,'last');
% Check if any points fell in this region
if ~isempty( x0 ) && ~isempty( x1 )
% Interpolation step, note the line continuation "..."
V2(ii) = vel(x0) + ((vel(x1) - vel(x0))/(z(x1) - ...
z(x0)))*(depths(ii)-z(x0));
end
end
Run Code Online (Sandbox Code Playgroud)
我们可以针对内置插值函数对此进行验证 interp1
<和>:<=并且>=: