livemyaerodream
livemyaerodream

Reputation: 920

How to compute the derivatives automatically within for-loop in Matlab?

For the purpose of generalization, I hope Matlab can automatically compute the 1st & 2nd derivatives of the associated function f(x). (in case I change f(x) = sin(6x) to f(x) = sin(8x))

I know there exists built-in commands called diff() and syms, but I cannot figure out how to deal with them with the index i in the for-loop. This is the key problem I am struggling with.

How do I make changes to the following set of codes? I am using MATLAB R2019b.

n = 10;
h = (2.0 * pi) / (n - 1);
for i = 1 : n
  x(i) = 0.0 + (i - 1) * h;
  f(i) = sin(6 * x(i));
  dfe(i) = 6 * cos(6 * x(i));   % first derivative
  ddfe(i) = -36 * sin(6 * x(i));   % second derivative 
end

Upvotes: 1

Views: 291

Answers (1)

OmG
OmG

Reputation: 18838

You can simply use subs and double to do that. For your case:

% x is given here
n = 10;
h = (2.0 * pi) / (n - 1);
syms 'y';
g = sin(6 * y);
for i = 1 : n
  x(i) = 0.0 + (i - 1) * h;
  f(i) = double(subs(g,y,x(i)));
  dfe(i) = double(subs(diff(g),y,x(i)));   % first derivative
  ddfe(i) = double(subs(diff(g,2),y,x(i)));   % second derivative 
end

By @Daivd comment, you can vectorize the loop as well:

% x is given here
n = 10;
h = (2.0 * pi) / (n - 1);
syms 'y';
g = sin(6 * y);
x = 0.0 + ((1:n) - 1) * h;
f = double(subs(g,y,x));
dfe = double(subs(diff(g),y,x));   % first derivative
ddfe = double(subs(diff(g,2),y,x));   % second derivative 

Upvotes: 2

Related Questions