## Can't run an equation in a function that works in a script

### Daniel Harper (view profile)

on 18 Feb 2019
Latest activity Commented on by Star Strider

on 20 Feb 2019

### Star Strider (view profile)

Hi,
I've used the following code for an equation in MATLAB and it works perfectly well in a script (cp1 and u1 have already been defined):
syms u4
eqn3 = cp1 == (u1+u4)*(u1.^2-u4.^2)/(2*u1.^3);
U4= double(solve(eqn3,u4));
u4 = real(U4( U4 > 0 ));
However, when I've tried to implement it into a function it doesn't work.
Can anyone help me with this please?

on 18 Feb 2019
Daniel Harper

### Daniel Harper (view profile)

on 18 Feb 2019
function [y] = test(x)
c1 = 0.5176;
c2 = 116;
c3 = 0.4;
c4 = 5;
c5 = 21;
c6 = 0.0068;
% equation 1 lamdai1
z1 = 1/(x(2) + 0.08*x(1)) - 0.035/((x(1).^3) +1);
y(1)=1/z1;
%equation 2 cp1
y(2) = c1*((c2/y(1))-c3*x(1)-c4)*exp(-c5/y(1))+c6*x(2);
%equation 3 u4 (z3)
syms y(3)
eqn3 = y(2) == (u1+y(3))*(u1.^2-y(3).^2)/(2*u1.^3);
Z3 = double(solve(eqn3,y(3)));
z3 = real(Z3( Z3>0 ));
y(3)=z3
%equation 4
y(4) = 0.5*(u1+y(3));
end
I'm using a genetic algorithm for inputs x(1) and x(2). cp1 and u4 etc. have been equated to y(1) etc.

### Star Strider (view profile)

on 18 Feb 2019

Try this:
function [y] = test(x)
c1 = 0.5176;
c2 = 116;
c3 = 0.4;
c4 = 5;
c5 = 21;
c6 = 0.0068;
% equation 1 lamdai1
z1 = 1/(x(2) + 0.08*x(1)) - 0.035/((x(1).^3) +1);
y = sym('y', [1 4])
y(1)=1/z1;
%equation 2 cp1
y(2) = c1*((c2/y(1))-c3*x(1)-c4)*exp(-c5/y(1))+c6*x(2);
%equation 3 u4 (z3)
u1 = 3; % <— PROVIDE CORRECT VALUE
eqn3 = y(2) - ((u1+y(3))*(u1.^2-y(3).^2)/(2*u1.^3));
eqn3 = vpa(eqn3);
U4p = sym2poly(eqn3);
Z3 = roots(U4p);
z3 = real(Z3( Z3>0 ));
y(3)=z3;
%equation 4
y(4) = vpa(0.5*(u1+y(3)));
y = double(y);
end
It runs without error for me. You must determine if it produces the correct result.
Note that this cannot be your fitness function, since a fitness function is required to produce a scalar output.

Star Strider

### Star Strider (view profile)

on 20 Feb 2019
Maximize it with respect to what?
The ‘y’ variable is a (1 x 12) vector that is not itself a function of any other variables. What do you intend by ‘maximizing’ it? You can get the largest value (and its index) with the max (link) function.
Star Strider

on 20 Feb 2019