Reputation: 379
I have defined a vector [0.11,1,3,4.5,7]
. I also has a function f
which have the values [f(0.11),f(1),f(3),f(4.5),f(7)]
. At the same time, I have another vector which may not have fixed length. Its value and length are determined by user. For simplicity, let assume the vector to [4,4.5,5,6]
. I would like to do as follow in programming:
Obtain approximated values f(4), f(4.5), f(5) and f(6)
from the given data input using linear approximation.
I understand that I can use for-loop to solve the problem; but I wonder if for-loop is necessary. Could someone think of a method without using for-loop?
Upvotes: 0
Views: 81
Reputation: 11238
We can do it this way:
We can do it avoiding for-loop (and any other loops too :) ):
x = [0.11 1 3 4.5 7]'
f_values = [1 5 3 15 0]'
xnew = [4 4.5 5 6]'
fnew = interp1q(x,f_values,xnew)
But there is second interesting way: to fit your data. Matlab has strong fitting tool.
For example this one. If you fit it you take function like this:
myf = @(x) here+some+formula
. So you can get any value of f
for any x
in anytime without any additional calculation.
If you know real value of f
just create an anonymous function:
f = @(x) x.^2
And now you can just put your [4,4.5,5,6]
values and get result:
xnew = [4 4.4 5 6]
result = f(xnew)
Upvotes: 5