如何在MATLAB中进行向量插值?
例如,我有以下矩阵:
M=
1 10
2 20
3 30
4 40
M
的第一列表示自变量x
坐标,而第二列表示输出或y
坐标。我还有以下输入向量:
a =
2.3
2.1
3.5
对于每个 a
的值,我希望确定插值结果的输出。在这种情况下,给定 a
,我希望返回
23
21
35
如何在MATLAB中进行向量插值?
例如,我有以下矩阵:
M=
1 10
2 20
3 30
4 40
M
的第一列表示自变量x
坐标,而第二列表示输出或y
坐标。a =
2.3
2.1
3.5
对于每个 a
的值,我希望确定插值结果的输出。在这种情况下,给定 a
,我希望返回
23
21
35
这是编辑后的问题的答案,即“如何进行插值”
您需要使用interp1
M = [1 10;2 20;3 30;4 40];
a = [2.3;2.1;3.5;1.2];
interpolatedVector = interp1(M(:,1),M(:,2),a)
interpolatedVector =
23
21
35
12
以下是“在向量中找到两个最接近的数”的答案,即编辑前的原始问题。
x=[1,2,3,4,5]'; %'#
a =3.3;
%# sort the absolute difference
[~,idx] = sort(abs(x-a));
%# find the two closest entries
twoClosestIdx = idx(1:2);
%# turn it into a logical array
%# if linear indices aren't good enough
twoClosestIdxLogical = false(size(x));
twoClosestIdxLogical(twoClosestIdx) = true;
twoClosestIdxLogical =
0
0
1
1
0