Multiple errors with derivative calculator code
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Kwasi Baryeh
el 6 de Sept. de 2020
Editada: John D'Errico
el 6 de Sept. de 2020
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?
0 comentarios
Respuesta aceptada
John D'Errico
el 6 de Sept. de 2020
Editada: John D'Errico
el 6 de Sept. de 2020
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 comentarios
John D'Errico
el 6 de Sept. de 2020
Editada: John D'Errico
el 6 de Sept. de 2020
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
Más respuestas (0)
Ver también
Categorías
Más información sobre Formula Manipulation and Simplification en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!