Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Using partial derivatives in Matlab

Subject: Using partial derivatives in Matlab

From: Jagdish

Date: 11 Oct, 2012 16:24:08

Message: 1 of 2

Hi,

I am writing a code to implement a function with conditions that involve partial derivatives. The out put is going to be a 3*1 matrix and will involve partial derivatives with all the three parameters. Before I could implement the actual function, I was fiddling around with a simple function as described below with no success. Could you please have a look and let me know if I have made a mistake? I think I am making a rookie mistake that would be trivial to the expert eye. Thanks a lot in advance!

Code -

function resid=case2(x)

syms x1 x2

x1=x(1);
x2=x(2);

y=x1^2-5*x1*x2+3*x2^2;

resid=[diff(y,x1);diff(y,x2)];

end

Subject: Using partial derivatives in Matlab

From: Christopher Creutzig

Date: 26 Nov, 2012 15:38:46

Message: 2 of 2

On 11.10.12 18:24, Jagdish wrote:
> Hi,
>
> I am writing a code to implement a function with conditions that involve partial derivatives. The out put is going to be a 3*1 matrix and will involve partial derivatives with all the three parameters. Before I could implement the actual function, I was fiddling around with a simple function as described below with no success. Could you please have a look and let me know if I have made a mistake? I think I am making a rookie mistake that would be trivial to the expert eye. Thanks a lot in advance!
>
> Code -
>
> function resid=case2(x)
>
> syms x1 x2
>
> x1=x(1);
> x2=x(2);
>
> y=x1^2-5*x1*x2+3*x2^2;
>
> resid=[diff(y,x1);diff(y,x2)];

1. Inside a function, using syms is not really a good idea. Search for
“poofing MATLAB variables” for details. Instead, use

x1 = sym('x1');
x2 = sym('x2');


2. You first define x1 and x2 to be symbolic names, just to immediately
replace them by your input values, before computing anything. Try this
instead:


function resid=case2(x)

x1=sym('x1');
x2=sym('x2');

y=x1^2-5*x1*x2+3*x2^2;

resid=[diff(y,x1);diff(y,x2)];
resid=subs(resid,{x1,x2},x);


Now, obviously, you'll get much better performance by not computing the
(symbolic) derivatives each time you call the function. Compute them
once and take that:

% interactive level
syms x1 x2;
y=x1^2-5*x1*x2+3*x2^2;
c2=[diff(y,x1);diff(y,x2)];
matlabFunction(c2,'file','case2.m');


HTH,
Christopher

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us