0

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)?

1
  • there are several ways, you can either evaluate it for f(0.5) f(1) etc if you have the function, or you can estimate it by estimating on the plot, or you can estimate it via interpolation. depends on what you are looking for really Commented Feb 1, 2018 at 11:05

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.