Liky
Liky

Reputation: 1247

Get value of a function created from array without using index

Let's consider the following script where I am creating a function such as y = f(x):

x = 0:0.01:2;
y = 0:0.02:4;
figure(1);clf;
plot(x, y);

Let's say I would now like to get some values of f such as f(0.5), f(1) or f(1.5). Is there any ways to get those values with a matlab function or do I have to first get the index of 0.5, 1 and 1.5 in x in order to get f(x)?

Upvotes: 0

Views: 42

Answers (1)

Wolfie
Wolfie

Reputation: 30047

If you have an actual function, you can call it like f(x)...

f = @(xi) 2.*xi;

f(0.5)    % >> ans = 1
f(0.5001) % >> ans = 1.0002
f(10)     % >> ans = 20

If you have two corresponding arrays like in your example code, you can use indexing of the x data

x = 0:0.01:2;
y = 0:0.02:4;

y(x==0.5)    % >> ans = 1
y(x==0.5001) % >> ans = []
y(x==10)     % >> ans = []

If you have the second case, but want to interpolate to avoid the y(x==0.5001)=[] result, you can set up a function like so

x = 0:0.01:2;
y = 0:0.02:4;
f = @(xi) interp1( x, y, xi );

f(0.5)    % >> ans = 1
f(0.5001) % >> ans = 1.0002
f(10)     % >> NaN

Upvotes: 5

Related Questions