find indexes of two values that between them there is specific number

3 ビュー (過去 30 日間)
Keren Grinberg
Keren Grinberg 2022 年 4 月 28 日
回答済み: David Hill 2022 年 4 月 28 日
i have vector A=[1 5 3 1 10 38 27] and value B=2 i want to find the nearest value to B by interpolate values that B is between them. like this: 2 is between 1,5 and 3,1 if 2 is closest to value from linear interpolation between 1,5 i want to chose this number if 2 is closest to value from linear interpolation between 3,1 i want to chose this number
thanks!
  2 件のコメント
David Hill
David Hill 2022 年 4 月 28 日
How is 2 between 5, 3?
Keren Grinberg
Keren Grinberg 2022 年 4 月 28 日
Oops, my mistake I edited the question

サインインしてコメントする。

回答 (2 件)

Davide Masiello
Davide Masiello 2022 年 4 月 28 日
編集済み: Davide Masiello 2022 年 4 月 28 日
clear,clc
A = [1 5 3 10 38 27];
B = 2;
% Interpolattion values
idx = 1:2:2*length(A)-1;
newA = interp1(idx,A,1:idx(end))
newA = 1×11
1.0000 3.0000 5.0000 4.0000 3.0000 6.5000 10.0000 24.0000 38.0000 32.5000 27.0000
interpA = newA(2:2:end)
interpA = 1×5
3.0000 4.0000 6.5000 24.0000 32.5000
% Find closest interpolated value
[~,k] = min(abs(interpA-B));
disp(interpA(k))
3
% Indexes of elements in A that enclose the closest interpolated value
A_idxs = [k,k+2]
A_idxs = 1×2
1 3

David Hill
David Hill 2022 年 4 月 28 日
A=[1 5 2.5 1 2.1 38 1.4 2.7 27 2.3 1.9 2.6 2.7 9 10 1.2];
B=2;
f=A-B;
F=find(f<0);
b=[];
for k=1:length(F)
try
[~,i]=min([abs(f(F(k))),abs(f(F(k)-1))]);
b=[b,A(F(k)-i+1)];
end
try
[~,i]=min([abs(f(F(k)+1)),abs(f(F(k)))]);
b=[b,A(F(k)-i+2)];
end
end
%b array will be A-values closest to B (when adjacent values of A are
%between B)

カテゴリ

Help Center および File ExchangeInterpolation についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by