Performance Matlab:快速查找ND矩阵中每个元素的一维线性插值节点和权重
在我正在研究的一个问题中,我计算了矩阵Performance Matlab:快速查找ND矩阵中每个元素的一维线性插值节点和权重,performance,matlab,find,linear-interpolation,accelerate,Performance,Matlab,Find,Linear Interpolation,Accelerate,在我正在研究的一个问题中,我计算了矩阵x中的一些值,然后我需要为x中的每个元素找到下面单调递增向量x中最近元素的索引,以及x元素与其两侧第一个元素的相对接近度。(这本质上是线性插值,而不是实际的插值。)我每次都在做这个,所以我真的非常感兴趣,希望它能尽可能快 我编写了一个函数locate,可以用一些示例数据调用该函数: X = linspace(5, 300, 40)'; x = randi(310, 5, 6, 7); [ii, weights] = locate(x, X); 我已经编写
x
中的一些值,然后我需要为x
中的每个元素找到下面单调递增向量x
中最近元素的索引,以及x
元素与其两侧第一个元素的相对接近度。(这本质上是线性插值,而不是实际的插值。)我每次都在做这个,所以我真的非常感兴趣,希望它能尽可能快
我编写了一个函数locate
,可以用一些示例数据调用该函数:
X = linspace(5, 300, 40)';
x = randi(310, 5, 6, 7);
[ii, weights] = locate(x, X);
我已经编写了两个版本的locate
。第一个是为了说明,第二个是我加速计算的最佳尝试。对于如何进一步提高绩效,您有什么建议或替代方法吗
1。博览会
function [ii, weights] = locate(x, X)
% LOCATE Locate first node on grid below a given value.
%
% [ii, weights] = locate(x, X) returns the first node in X that is below
% each element in x and the relative proximities to the two closest nodes.
%
% X must be a monotonically increasing vector. x is a matrix (of any
% order).
% Preallocate
ii = ones(size(x)); % Indices of first node below (or 1 if no nodes below)
weights = zeros([2, size(x)]); % Relative proximity of the two closest nodes
% Find indices and compute weights
for ix = 1:numel(x)
if x(ix) <= X(1)
ii(ix) = 1;
weights(:, ix) = [1; 0];
elseif x(ix) >= X(end)
ii(ix) = length(X) - 1;
weights(:, ix) = [0; 1];
else
ii(ix) = find(X <= x(ix), 1, 'last');
weights(:, ix) = ...
[X(ii(ix) + 1) - x(ix); x(ix) - X(ii(ix))] / (X(ii(ix) + 1) - X(ii(ix)));
end
end
end
函数[ii,权重]=定位(x,x)
%将网格上的第一个节点定位到给定值以下。
%
%[ii,weights]=locate(x,x)返回x中位于下面的第一个节点
%x中的每个元素以及到最近两个节点的相对近邻。
%
%X必须是单调递增的向量。x是一个矩阵(任意
%订单)。
%预先分配
ii=个(尺寸(x));%下面第一个节点的索引(如果下面没有节点,则为1)
权重=零([2,大小(x)];%两个最近节点的相对接近度
%查找索引并计算权重
对于ix=1:numel(x)
如果x(ix)=x(结束)
ii(ix)=长度(X)-1;
权重(:,ix)=[0;1];
其他的
ii(ix)=在中查找(Xcheckout mypolylineinterp
函数
除了polylen
输入类似于X的diff之外,几乎完全可以做到这一点
一般来说,将此类操作矢量化是使用histc()
,如此行所示
function [ii, weights] = locate(x, X)
% LOCATE Locate first node on grid below a given value.
%
% [ii, weights] = locate(x, X) returns the first node in X that is below
% each element in x and the relative proximities to the two closest nodes.
%
% X must be a monotonically increasing vector. x is a matrix (of any
% order).
% Preallocate
ii = ones(size(x)); % Indices of first node below (or 1 if no nodes below)
weights = zeros([2, size(x)]); % Relative proximity of the two closest nodes
% Find indices
for iX = 1:length(X) - 1
ii(X(iX) <= x) = iX;
end
% Find weights
below = x <= X(1);
weights(1, below) = 1; % All mass on the first node
weights(2, below) = 0;
above = x >= X(end);
weights(1, above) = 0;
weights(2, above) = 1; % All mass on the last node
interior = ~below & ~above;
xInterior = x(interior)';
iiInterior = ii(interior);
XBelow = X(iiInterior)';
XAbove = X(iiInterior + 1)';
weights(:, interior) = ...
[XAbove - xInterior; xInterior - XBelow] ./ (XAbove - XBelow);
end