How can I interpolate a vector in MATLAB?
For example, I have the following matrix:
M=
1 10
2 20
3 30
4 40
The first column of M
denotes the independent parameter of x
coordinate while the second column of M
denotes the output or y
coordinate.
I also have the following input vector:
a =
2.3
2.1
3.5
For each value of a
, I wish to determine what the output interpolated result would be. In this case, given a
, I wish to return
23
21
35
If you want simple linear interpolation between the two, you can apply a weight to each of the vectors V1 and V2 and add them together. At the top, V1 will be weighted by 1 and V2 should be weighted by 0 . Similarly at the bottom, V2 should be weighted by 1 and V1 should be weighted by 0 .
vq = interp1( x , v , xq ) returns interpolated values of a 1-D function at specific query points using linear interpolation. Vector x contains the sample points, and v contains the corresponding values, v(x). Vector xq contains the coordinates of the query points.
Here's the answer to the question after the edit, i.e. "how to interpolate"
You want to use 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
Here's the answer to the question "find the two closest entries in a vector", i.e. the original question before the edit.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With