Multiple errors with derivative calculator code

1 次查看(过去 30 天)
disp('This calculates a polynomial derivative at a specific point')
x = sym ('x');
g = input('What is your polynomial function?','s');
f() = str2func(['@(x)', 'g']);
a = input('What value would you like to derive it at?');
n = limit ((f(x) - f(a))/(x-a),a);
fprintf('The derivative of %s \n', f(x))
fprintf('at point %f is %f',n)
I get an error message here:
Error: File: DerivativeCalculator.m Line: 5 Column: 2
An indexing expression on the left side of an assignment must have at least one subscript.
What are the problems with my code?

采纳的回答

John D'Errico
John D'Errico 2020-9-6
编辑:John D'Errico 2020-9-6
This is not valid syntax in MATLAB. It may be so in some other language. But not so here.
f() = str2func(['@(x)', 'g']);
As you can see,
g = 'x^2';
f() = str2func(['@(x)', 'g']);
f() = str2func(['@(x)', 'g']);
Error: An indexing expression on the left side of an assignment must have at least one subscript.
The error message tells you MATLAB did not like the f() on the left side of the assignment. The assignment operator in MATLAB is the = sign. To the left of that, MATLAB saw f(), but no index inside the ().
The answer is simple (besides learning MATLAB more completely) is to just write it as:
f = str2func(['@(x)', 'g']);
In MATLAB, f is a variable, that just happens to contain a function handle.
whos f
Name Size Bytes Class Attributes
f 1x1 32 function_handle
You assign something into a variable like you assign any other variable.
  4 个评论
Kwasi Baryeh
Kwasi Baryeh 2020-9-6
Thank you for your insight! This isn't for a homework assignment. I'm just starting out on MATHLAB with a school license and seeing what I can do with it. I'll look deeper at my code.
John D'Errico
John D'Errico 2020-9-6
编辑:John D'Errico 2020-9-6
Just think about the difference between the name of a variable and what it contains.
Anyway, here is another way you could have performed the differentiation. You used the definition of a derivative as a limit there. But you could just have used diff.
>> g
g =
'x^2'
>> gsym = str2sym(g)
gsym =
x^2
str2sym converts the string into a symbolic variable. So gsym contains essentially the same expression as g, but here it is stored in a different form. whos tells us this fact:
>> whos g gsym
Name Size Bytes Class Attributes
g 1x3 6 char
gsym 1x1 8 sym
But now we can use symbolic tools on gsym.
>> gprime = diff(gsym,x)
gprime =
2*x
And finally we can turn gprime into a function we can evaluate directly.
f = matlabFunction(gprime)
f =
function_handle with value:
@(x)x.*2.0

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Formula Manipulation and Simplification 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by