Evaluating symbolic expression and handing them to optimisation problem: How should I introduce symbolic variables to ga function?

3 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?

Answers (1)

Alan Weiss
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
  4 Comments

Sign in to comment.

Categories

Find more on Symbolic Math Toolbox in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!