4 views (last 30 days)

I have a problem understanding how symbolic functions should be handled when first manipulating them and then sending to optimisation. I have symbols in matrices which I manipulate and try to send the final result to ga optimisation function.

For example:

>> fun = @(q) q(1)^2 + q(2)^2 + q(3)^2 + q(4)^2;

>> [x,fval,exitflag,output,population,scores] = ga(fun,4,[],[],[],[],zeros(4,1),ones(4,1),[],[1:1:4]);

Works OK, but leads to errors:

>> B=q(1)^2 + q(2)^2 + q(3)^2 + q(4)^2;

>> fun = @(q) B;

>> [x,fval,exitflag,output,population,scores] = ga(fun,4,[],[],[],[],zeros(4,1),ones(4,1),[],[1:1:4]);

The errors are:

xxxxx

The following error occurred converting from sym to double:

DOUBLE cannot convert the input expression into a double array.

Error in fcnvectorizer (line 13)

y(i,:) = feval(fun,(pop(i,:)));

Error in gaminlppenaltyfcn

Error in gapenalty

Error in makeState (line 64)

Score = FitnessFcn(state.Population(initScoreProvided+1:end,:));

Error in galincon (line 17)

state = makeState(GenomeLength,FitnessFcn,Iterate,output.problemtype,options);

Error in gapenalty

Error in gaminlp

Error in ga (line 366)

[x,fval,exitFlag,output,population,scores] = gaminlp(FitnessFcn,nvars, ...

Caused by:

Failure in user-supplied fitness function evaluation. GA cannot continue.

Failure in initial user-supplied fitness function evaluation. GA cannot continue.

xxxxx

What I understood B becomes evaluated and q1, q2, q3, q4 are no longer understood as q(:).

Question: I have a matrix manipulated and having symbolic values q1...q75. How should I introduce them to ga function?

Alan Weiss
on 20 Nov 2017

You should convert your symbolic variables to a MATLAB function before trying to pass them to a solver such as ga. See Using Symbolic Mathematics with Optimization Toolbox and Symbolic Math Toolbox Calculates Gradients and Hessians for examples.

Alan Weiss

MATLAB mathematical toolbox documentation

Alan Weiss
on 20 Nov 2017

The first example:

fun = @(q) q(1)^2 + q(2)^2 + q(3)^2 + q(4)^2;

This function accepts a row vector of double-precision variables, which is what ga passes by default, and returns a double-precision scalar, which is what a solver expects.

The second example:

B = q(1)^2 + q(2)^2 + q(3)^2 + q(4)^2;

fun = @(q) B;

If q is a symbolic expression, say

syms a b c d

q = [a b c d]

then what do you think that fun([1 2 3 4]) gives?

fun([1 2 3 4])

ans =

a^2 + b^2 + c^2 + d^2

You see, you made the function incorrectly. If, instead, you make

fun2 = matlabFunction(B,'vars',{q});

fun2([1 2 3 4])

ans =

30

I hope that this helps you understand the difference.

Alan Weiss

MATLAB mathematical toolbox documentation

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

Start Hunting!
## 0 Comments

Sign in to comment.