# I need cost function for tuning PID controller help me

23 views (last 30 days)

Show older comments

##### 0 Comments

### Answers (1)

Sam Chak
on 23 Nov 2022

Edited: Sam Chak
on 25 Dec 2022

Hi @Yazeed Ali

Not sure what your system is, but I think you can try the one of the simplest cost function probably looks like this:

Tuning the gains is probably simpler by manual calculations (follow formulas in textbooks) or with the pidtune() command.

function J = costfun(Kp, Ki, Kd)

[t, x] = ode45(@(t, x) myode(t, y), tspan, ic, opts);

error = x - x_ref;

J = trapz(t, error.^2); % ISE

% J = trapz(t, t.*abs(error)); % ITAE

end

function dxdt = myode(t, x)

% Insert your system and the PID controller

dxdt = A.*x + B*u;

end

Edit: An example is included.

Example: Consider the system described by

.

The cost function J is given by

where

and .

A full state-feedback controller is used:

The optimal feedback gain matrix is found using fmincon().

costfun = @objfun;

nvars = 2;

A = -eye(nvars);

b = zeros(nvars, 1);

Aeq = [];

beq = [];

lb = [0 0]; % lower bound

ub = [2 2]; % upper bound

k0 = [0.5, 1.5]; % initial guess

[k, fval, exitflag, output] = fmincon(costfun, k0, A, b, Aeq, beq, lb, ub)

function J = objfun(k)

tspan = linspace(0, 30, 3001);

ic = [1 0];

[t, x] = ode45(@(t, x) myode(t, x, k), tspan, ic);

Q = eye(2);

R = 1;

ifcn = Q(1,1)*x(:,1).^2 + Q(2,2)*x(:,2).^2 + R*(- k(1)*x(:,1) - k(2)*x(:,2)).^2;

J = trapz(t, ifcn); % ISE

end

function dxdt = myode(t, x, k)

dxdt = zeros(2, 1);

% my controller

u = - k(1)*x(1) - k(2)*x(2);

% my system

dxdt(1) = x(2);

dxdt(2) = - x(2) + u;

end

##### 9 Comments

Sam Chak
on 27 Dec 2022

Edited: Sam Chak
on 27 Dec 2022

I'm familiar with Grey Wolf. Why not consider posting the GWO code and the error message in a new Question? GWO was published by Seyedali Mirjalili in 2014. Optimization experts in MATLAB would be able to advise you.

I'm not sure if the proposed Cost function is helpful or not. Most likely it is because you cannot test with the GWO. However, it works with other optimizers such GA, PSO, ABC, etc., then we can safely assure that the proposed "Cost Function template" maybe effective.

I only verified it using fmincon. It does not guarantee to work with other optimizers. Let me know it doesn't work because I may consider removing it as I don't want other users to be misguided by the 'flawed' Cost Function. Thanks!

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!