blkpingu
blkpingu

Reputation: 1676

Elegant way to create symbolic derivatives of a function up to N-th order

How I create derivatives of level n from f(x) thus far:

f = exp(-(x/2)),f1 = diff (f), f2 = diff (f1), f3 = diff(f2), f4 = diff(f3), f5 = diff(f4)

This command is can to do the following:

What this command can't do:

How do I add the functionality I need to make this easier for me? Is there a way to do this more elegantly?

The Syntax for a script should be something equivalent to to this java snippet:

int n;
String function;

//User input function
//User input diff level n
System.out.print("f(x)= " + function);

for(i = 1; i < n; i++){
function = diff(function);
system.out.print("f"+ i + "(x): " + function);
}

I tried this in matlab, but I have no idea what I'm doing:

syms x
int n = 0;
string f;

n = str2double(input('Enter an integer: ','s'));
if isnan(n) || fix(n) ~= n
  disp('Please enter an integer')
end

disp('f(x) = ', f);

f = str2function(input('Enter a function(String): ','s'));
if isnan(f) || fix(f) ~= f
  disp('Please enter a String')
end

while n > 1
    n = n-1;
    f = diff(f);
    disp('f',n,'(x)=', f)
end

Upvotes: 1

Views: 142

Answers (1)

ViG
ViG

Reputation: 1868

A for loop can be used to fill a vector containing the different derivatives.

syms x

f = exp(-(x/2));                     % function
n = 5;                               % number of derivatives

derivatives = sym('A', [1 n]);       % allocate memory

for ii=1:n
    derivatives(ii) = diff(f,ii);
end

In matlab you don't define the type, so just

n = 0;

without the int. You fetch the input correctly, but only asks it once. When an incorrect input is given, the program continues and the user doesn't get to input a new one. I'd use a while loop to keep asking for input, till it is correct:

n = str2double(input('Enter an integer: ','s'));
while isnan(n) || fix(n) ~= n
  disp('Please enter an integer')
  n = str2double(input('Enter an integer: ','s'));
end

For f, you want sym, I thought, not a function. disp can't be used for symbolic variables, but fprintf can:

fprintf('f(x) = %s\n', char(f));

Then I would use a for loop instead of a while because you know before hand how many iterations there will be.

Total code:

syms x

n = str2double(input('Enter an integer: ','s'));
while isnan(n) || fix(n) ~= n
  disp('Please enter an integer')
  n = str2double(input('Enter an integer: ','s'));
end


f = sym(input('Enter a function(String): ','s'));

fprintf('f(x) = %s\n', char(f));

derivatives = sym('A', [1 n]);
for ii=1:n
    derivatives(ii) = diff(f,ii);
    fprintf('f^{(%i)}(x) = %s\n', ii, char(derivatives(ii)));
end

I tried to use superscript for the derivatives, but I can't seem to manage... If I find out, I'll update the answer.

Upvotes: 2

Related Questions