I would like to define a function that allows me to enter a symbolic expression in terms of x, raise that expression to the "n"th degree, then plot that expression from x=[-5,5]
1 次查看(过去 30 天)
显示 更早的评论
Essentially, I would like to create a function that is very similar to fplot(), where I can enter an expression, and a power I would like to raise it to. The range of x-values it will be plotted for will be constant at x=[-5,5]. Here is my latest attempt that has not worked:
function [ ] = nthDegree( funcDef, n )
%Plots the the input function to the "n-th" degree.
%
syms x ;
f = funcDef ;
y = matlabFunction(f)
Y = y.^n ;
fplot(Y,[-5,5])
end
Every attempt has resulted in the error message. Here is one such attempt:
nthDegree(x.^2,1)
Undefined function or variable 'x'.
Thanks for the help!
0 个评论
回答(1 个)
Giorgos Papakonstantinou
2015-3-10
编辑:Giorgos Papakonstantinou
2015-3-10
Justin you have to define outside your function what is x. This is the reason why Matlab complains about x. It does not know what x is and therefore it is undefined.
Furthermore, you should replace the
Y = y.^n ;
with
Y = @(y) y(x)^n;
in order to get the input function to the nth power.
2 个评论
Giorgos Papakonstantinou
2015-3-11
编辑:Giorgos Papakonstantinou
2015-3-11
What I am saying is that if you have your function as it is , and you issue,
syms x
nthDegree(x.^2,1)
you get an error.
Undefined function 'power' for input arguments of type 'function_handle'.
Error in nthDegree (line 7)
Y = y.^n;
Additionaly, after the statement,
y = matlabFunction(f);
y is not anymore a symbolic expression. It is a function handle. If you try to use fplot with a symbolic object, then Matlab would throw an error. fplot requires a function handle. If you want to plot a symbolic function you can use ezplot.
What do you mean with apostrophes, passing it as a string i.e. 'x.^2' in fplot? Yes it possible. I am quoting a part of the documentation:
fun must be:
- The name of a function
- A string with variable x that may be passed to eval, such as 'sin(x)', 'diric(x,10)', or '[sin(x),cos(x)]'
- A function handle
I hope these answer your question.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Number Theory 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!