how to find the nearest value?

1 回表示 (過去 30 日間)
Rabih Sokhen
Rabih Sokhen 2021 年 10 月 21 日
回答済み: Bruno Luong 2021 年 10 月 21 日
hello guys
suppose i have a vector[s]
A=[ 1 2 3 4 5 6]
B=[6.1 5.1 4.1 3.1 2.1 1.1]
and
position_A=[10 20 30 40 50 60]
i want to find the nearest value of B in A
i have tried to do the following
for i=1: length(A)
B(i)=min(abs(A-B(i)));
end
% now my vector B is [6 5 4 3 2 1]
i want to creat a vector that indicate the position of B, for example, the number 2 is the second element in A have position " position _A(2)=20",
i want to creat a vector "position_B" in a way that the number 2 in vector B have a position_B=20
thank you in advance

採用された回答

Bruno Luong
Bruno Luong 2021 年 10 月 21 日
A=[ 1 2 3 4 5 6]
A = 1×6
1 2 3 4 5 6
B=[6.1 5.1 4.1 3.1 2.1 1.1]
B = 1×6
6.1000 5.1000 4.1000 3.1000 2.1000 1.1000
position_A=[10 20 30 40 50 60]
position_A = 1×6
10 20 30 40 50 60
loc = interp1(A,1:length(A),B,'nearest','extrap');
position_B = position_A(loc)
position_B = 1×6
60 50 40 30 20 10
B = A(loc)
B = 1×6
6 5 4 3 2 1

その他の回答 (1 件)

dpb
dpb 2021 年 10 月 21 日
The builtin way in MATLAB is interp1
>> A=[1:6];
>> B=flip(A)+0.1;
>> posn=[10:10:60];
>> C=posn(interp1(B,A,A,'nearest','extrap'))
C =
60 50 40 30 20 10
>>

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by