Linear interpolation two array with target value in one array

Given two array
A=[483, 427, 306, 195]
B=[0, 0.25, 0.5, 0.75]
Given a target the value 241, which is between the values 306 and 195 in the Array A. I want to find the value in the array B which is proportional to the value 241 in A. For this case the wanted value is 0.65 because x=0.75- [(241-195)/(306-195)]*0.25
I have to do this for a lot of array. Is there a simple way to do it?

댓글 수: 3

You are multiplying with 0.25 in the end. Should not it be 0.5? As it will cause array index errors if your target lies between A(1) and A(2).
How do you define the target value 241 in your example? and explain better the derivation of x (why do you multiply by 0.25?)
SYML2nd
SYML2nd 2021년 8월 16일
편집: SYML2nd 2021년 8월 16일
It is the step of the array B, 0.25=0.75-0.5 . 241 is a given target I decide it by myself

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

 채택된 답변

Interpolate using interp1:
A=[483, 427, 306, 195];
B=[0, 0.25, 0.5, 0.75];
target = 241;
Result = interp1(A, B, 241)
Result = 0.6464
Graphically:
figure
plot(A, B, '-b')
hold on
plot(target, Result, 'p', 'MarkerSize',10, 'MarkerFaceColor','g')
plot([1 1]*target, [min(ylim) Result], '--r')
plot([min(xlim) target], [1 1]*Result, '--r')
hold off
grid
xlabel('A')
ylabel('B')
text(target, Result, sprintf(' \\leftarrow (%d, %.2f)', target, Result), 'Horiz','left', 'Vert','middle')
.

추가 답변 (2개)

Awais Saeed
Awais Saeed 2021년 8월 16일
I did not check it thoroughly but I think it will work
clc;clear all;close all
A=[483,427, 306, 195];
B=[0, 0.25, 0.5, 0.75];
target = 241;
for col = 1:1:size(A,2)
if (target < A(col) && target > A(col+1)) % if target lies between the range
result = B(col+1)-((target-A(col+1))/(A(col)-A(col+1)))*(B(col+1)-B(col)) % desired operation
break
end
end
Try this
clc, clear
A = [483, 427, 306, 195];
B = [0, 0.25, 0.5, 0.75];
% assume that these are your target values
target = arrayfun(@(x, y) mean([x, y]), A(1:end-1), A(2:end));
% force last value to be 241 to check with your example
target(end) = 241;
step = B(2)-B(1);
% save values in c
c1 = nan(size(target));
% using for loop
for nv=1:length(c1)
c1(nv) = B(nv+1) - step*(target(nv)-A(nv+1))/(A(nv)-A(nv+1));
end
% without foor
c2 = arrayfun(@(x0, x1, x2, y) y-step*(x0-x2)/(x1-x2), target, A(1:end-1), A(2:end), B(2:end));
disp(c1)
0.1250 0.3750 0.6464
disp(c2)
0.1250 0.3750 0.6464

카테고리

도움말 센터File Exchange에서 Interpolation에 대해 자세히 알아보기

제품

태그

질문:

2021년 8월 16일

답변:

2021년 8월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by