Troubles with MATLAB genetic algorithm nonlinear constraint function

1 view (last 30 days)
Hi everyone!
I have a question regarding an error I'm recieving regarding a nonlinear constraint function I am passing into MATLAB's genetic algorithm. This is the error message I get:
Error using ga (line 393)
Unable to perform assignment because the left and right sides have a different number of elements.
Error in OSCaR_GA_v2 (line 94)
[xf,fval,exitFlag,Output] = ga(f,m,[],[],[],[],lb,ub,nonlinconst,1:m,options);
Caused by:
Failure in initial user-supplied nonlinear constraint function evaluation.
I've made sure my nonlinear constraint accepts both vectors and arrays but I still can't pinpoint why I'm getting this error. I appreciate clearification on this issue!

Answers (1)

Matt J
Matt J on 5 Mar 2021
If you re-run your code after executing,
>>dbstop if caught error
you will be able to trace the problem.
  15 Comments
Walter Roberson
Walter Roberson on 6 Mar 2021
The below is not erroring for me with 3 targets (it will still error with 1 target, so the one target is automatically the most massive and you are deleting it...)
%% Build inequality constraint vector
% Build corresponding mass vector
mass = zeros(1,size(x,2));
for i = 1:size(x,2)
mass(i) = A(x(i),7);
end
C = zeros(size(x,2)+2,1);
%leave it at 0 if all the elements are unique
if size(unique(x),2) < size(x,2)
C(1:size(x,2)) = 1; % the condition is not met, (C>0)
end
% Apply mass constraints based on tether allocation
if size(x,2) == 2 && mass(1) <= 500 && mass(2) <= 500 % a design targeting two objects with each less than 500 kg
C(size(x,2)+1,1) = max(mass) - 500; % the objects cannot exceed a mass of 500 kg
else
norm_mass = mass;
x = find(mass == max(mass));
norm_mass(x(1)) = []; % remove the most massive object in the set
C(size(x,2)+1,1) = max(mass) - 1000 + 250*(size(x,2)-1); % the largest object cannot exceed the maximum kg allowance for the number of tethers it uses
C(size(x,2)+2,1) = max(norm_mass) - 250; % all other objects cannot exceed the 250 kg limit of a single tether
end
Angeliek Devine
Angeliek Devine on 6 Mar 2021
I think maybe I was having issues with the debugger. I got it working! Thank you so much for your help! I think I will just set max mass to zero in the norm vector mass rather than deleting it so that it will still run for one object. You definitely are the mvp for matlab answers :)

Sign in to comment.

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!