Error: File: Untitled11.m Line: 1 Column: 10 Invalid expression. Check for missing multiplication operator, missing or unbalanced delimiters, or other syntax error. To construct matrices, use brackets instead of parentheses.

f = x^3+2x^2-x+3;
%actual derivative of function
fprime = 3x^2+4x-1;
%step size:
h=0.1;
%forward difference
dfdx_forward = f(1+h)-f(1)/h
Error_forward = fprime(1)-dfdx_forward %error
%backward difference
dfdx_backward = (f(1)-f(1-h))/h
Error_backward = fprime(1)-dfdx_backward %error
%central difference
dfdx_central = (f(1+h)-f(1-h))/(2*h)
Error_central = fprime(1)-dfdx_central %error

 Accepted Answer

f = x^3+2*x^2-x+3;
% ^---missing
fprime = 3*x^2+4*x-1;
% ^---missing

7 Comments

now it started to give such an error. Array indices must be positive integers or logical values.
Error in Untitled11 (line 9)
dfdx_forward = (f(x+h)-f(x))/h;
why ? I'm so confused.
I suggest you to do https://matlabacademy.mathworks.com to learn the basics:
x=1:10; % example
x(1) % no error
x(0) % error
x(.5) % error
f and fprime should be a function handle:
f = @(x)x^3+2*x^2-x+3;
%actual derivative of function
fprime = @(x)3*x^2+4*x-1;
Your f is an array, not a function. You would have had to define an x value before that point, and for the syntax you used to work, your x would have had to have either been symbolic or else a numeric scalar.
You have two choices:
  1. f = @(x) x.^3 + 2*x.^2 - x + 3;
  2. syms x; f(x) = x^3 + 2*x^2 - x + 3

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!