Evaluate f(x) for multiple evenly spaced values

How do I evaluate a function f(x) for multiple, evenly spaced values of x between two variables. ie x = exactly 10 evenly spaced numbers between 5 and 20
I'm thinking define an anonymous function so I can evaluate it over a range of values but how to set those values is where I'm lost

 Akzeptierte Antwort

Shashank Prasanna
Shashank Prasanna am 16 Feb. 2013

1 Stimme

x = linspace(5,20,10); % Generate 10 evenly spaced points between 5 and 20
y = f(x); % Call your function, assuming you have defined it already
%If f can't take in a vector you will have to call it in a loop.

3 Kommentare

Josh
Josh am 16 Feb. 2013
Bearbeitet: Josh am 16 Feb. 2013
how exactly do I do this? The function is a polynomial and I keep getting errors
??? Undefined function or variable 'y'.
Error in ==> at 21 f(x)=y
OR
??? Error using ==> mpower Inputs must be a scalar and a square matrix.
Error in ==> @(x)x^3-2*x^2-3*x+1
Error in ==> at 21 y=feval(f,x) >>
Josh, to use mpower in your example, you must use elementwise :
f=@(x) x.^3-2*x.^2-3*x+1
x=linspace(5,20,10);
y=feval(f,x)
Image Analyst
Image Analyst am 16 Feb. 2013
Bearbeitet: Image Analyst am 16 Feb. 2013
Josh, you have to do y=f(x), not f(x)=y. The "target" variable is on the left, and the expression on the right is evaluated and stuffed into the variable on the left. This is how every programming language that I've used does it.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Youssef  Khmou
Youssef Khmou am 16 Feb. 2013

0 Stimmen

hi,
You can set the values using 'linspace' :
x=linspace(5,20,10);
f=@(x) sin(x)
y=feval(f,x);

1 Kommentar

Youssef  Khmou
Youssef Khmou am 16 Feb. 2013
linspace(a,b,n) generates a vector of n points linearly spaced between and including a and b .

Melden Sie sich an, um zu kommentieren.

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by