Interpolating the indexes of values in a Vector

조회 수: 4 (최근 30일)
malik abdelli
malik abdelli 2023년 9월 19일
댓글: Star Strider 2023년 9월 19일
hi
i have a Vector lets say a = [2 4 6 8 10 12 14 16]; and i have a value "b" that can change.
I want to write a code that compares the value "b" to every value in "a" starting from index 1 and going to index 8 in this example.
When the value "b" finds a value in "a" so that b >= a(:) and b < a( :+1) . The algorithm will give me the index "c" of that value wich can also be interpolated.
As an example lets say b = 6, then the algorithm will give me c = 3, because the index of 6 in "a" is 3.
but if b = 5 then the algorithm should give me c = 2.5. even tho 5 doesnt exist in "a" but we can know the index with interpolation
and if b = 4.5 then the algorithm should give me c = 2.25
if b = 14.3 then the algorithm should give me c = 7.15 etc...
How can i do this?
Thank you.

채택된 답변

Star Strider
Star Strider 2023년 9월 19일
Use interp1 for this —
a = [2 4 6 8 10 12 14 16];
k = 1:numel(a);
k = 1×8
1 2 3 4 5 6 7 8
interpc = @(b) interp1(a,k,b);
bvector = [4.5 5 6 14.3];
c = interpc(bvector);
Result = [bvector; c]
Result = 2×4
4.5000 5.0000 6.0000 14.3000 2.2500 2.5000 3.0000 7.1500
.
  댓글 수: 4
malik abdelli
malik abdelli 2023년 9월 19일
ok thank you
Star Strider
Star Strider 2023년 9월 19일
As always, my pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Konrad
Konrad 2023년 9월 19일
Hi,
a = [2 4 6 8 10 12 14 16];
b = [6, 5, 4.5, 14.3];
interp1(a,1:numel(a),b,'linear') % 'linear' is also the default
ans = 1×4
3.0000 2.5000 2.2500 7.1500
Best, Konrad

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by