Useing “ga” function in MATLAB to use Genetic Algorithm for nonlinear optimization

draws a line that separates the positive examples (shown as ‘+’ symbols in the plot) from
the negative examples (shown as ‘o’ symbols in the plot). The resulting line is
your trained classifier for the given input data.
% we need to Define an underlying function (line) in 2D
a=?; b=?;
hold on;
% Generate 20 random examples
N=20;
for i=1:N
x = rand(1)*5; y = rand(1)*5;
data(i,:) = [x y]; % Generate random coordinates
% Saves the coordinates
if (y > a*x + b )% If the point is above the line
label(i) = 1; plot(x,y,'r+'); % Make it a positive example
else
label(i) = -1; plot(x,y,'go'); % Otherwise, make it negative
end
end
Hints:
1. You can use “ga” function in MATLAB to use Genetic Algorithm for
nonlinear optimization (
https://www.mathworks.com/help/gads/ga.html)

5 Comments

This sounds like a homework assignment. If it is, show us the code you've written to try to solve the problem and ask a specific question about where you're having difficulty and we may be able to provide some guidance.
If you aren't sure where to start because you're not familiar with how to write MATLAB code, I suggest you start with the MATLAB Onramp tutorial (https://www.mathworks.com/support/learn-with-matlab-tutorials.html) to quickly learn the essentials of MATLAB.
If you aren't sure where to start because you're not familiar with the mathematics you'll need to solve the problem, I recommend asking your professor and/or teaching assistant for help.
myRand:
function[label, x ,y] = myRand(opt)
% Define an underlying function (line) in 2D
a=opt(1);
b=opt(2);
% Generate 20 random examples
for i = 1:20
x = rand(1)*5; y = rand(1)*5; % Generate random coordinates
if (y > a*x + b )% If the point is above the line
label(i) = 1; % Make it a positive example
else
label(i) = -1; % Otherwise, make it negative
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
code:
hold on
A = [1 1];
b = [1];
Aeq = [];
beq = [];
lb = 0;
ub = 5;
myRand(x)
options = optimoptions('ga','PlotFcn', @gaplotbestf);
rng default % For reproducibility
fun = @(x) myRand(x)
x = ga(fun,2,A,b,[],[],[],lb,ub,options)
Thank you for showing your code. Now what is the specific question you have about this code or issue that you're experiencing when you try to use this code to solve the problem?
this code needs one input for @gaplotbestf and myRand is giving out 20*2 output. I dont know how to colve it.
hi, do you want to help or ask question. becuase I have my dealine around the corner.

Sign in to comment.

Answers (0)

Asked:

on 10 Sep 2021

Commented:

on 10 Sep 2021

Community Treasure Hunt

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

Start Hunting!