├── .gitattributes ├── PID ├── Acontrol.m ├── Anglemodel.m ├── Init.m ├── Pcontrol.m ├── Positionmodel.m ├── TD1.m ├── TD2.m ├── slidemodel.mdl └── slidemodel_plot.m ├── README.md ├── demo ├── Untitled3.m └── demo1.mdl ├── 模糊滑模控制 ├── Acontrol.m ├── Anglemodel.m ├── Init.m ├── Pcontrol.m ├── Positionmodel.m ├── TD1.m ├── TD2.m ├── createfuzz.m ├── fuzz.asv ├── fuzz_1.fis ├── fuzz_rule.m ├── slidemodel.mdl └── slidemodel_plot.m ├── 滑模控制 ├── Acontrol.m ├── Anglemodel.m ├── Init.m ├── Pcontrol.m ├── Positionmodel.m ├── TD1.m ├── TD2.m ├── slidemodel.mdl └── slidemodel_plot.m └── 遗传算法优化 ├── Acontrol.m ├── Anglemodel.m ├── GAcode.m ├── Init.m ├── Pcontrol.m ├── Positionmodel.m ├── TD1.m ├── TD2.m ├── fitness.m ├── fuzz_1.fis ├── fuzz_rule.m ├── gaot ├── Contents.m ├── EER.m ├── README ├── adjswapMutation.m ├── arithXover.m ├── b2f.m ├── binaryExample.m ├── binaryMutation.m ├── boundaryMutation.m ├── calcbits.m ├── coranaEval.m ├── coranaFeval.m ├── coranaMin.m ├── cyclicXover.m ├── delta.m ├── dists.m ├── enhancederXover.m ├── erXover.m ├── f2b.m ├── floatExample.m ├── floatGradExample.m ├── ga.m ├── gaMichEval.m ├── gaZBGrad.m ├── gaZBGradEval.m ├── gademo.m ├── gademo1.m ├── gademo1eval1.m ├── gademo2.m ├── gademo3.m ├── gaotv5.ps ├── heuristicXover.m ├── idprefs.mat ├── initializega.m ├── initializeoga.m ├── inversionMutation.m ├── linerorderXover.m ├── maxGenTerm.m ├── multiNonUnifMutation.m ├── nonUnifMutation.m ├── normGeomSelect.m ├── optMaxGenTerm.m ├── orderBasedExample.m ├── orderbasedXover.m ├── parse.m ├── partmapXover.m ├── plotCorana.m ├── roulette.m ├── shiftMutation.m ├── simpleXover.m ├── singleptXover.m ├── startup.m ├── swapMutation.m ├── threeswapMutation.m ├── tournSelect.m ├── tspEval.m ├── unifMutation.m └── uniformXover.m ├── optimal.m ├── slidemodel.mdl └── slidemodel_plot.m /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /PID/Acontrol.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/PID/Acontrol.m -------------------------------------------------------------------------------- /PID/Anglemodel.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts]=Amodel(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2, 4, 9 } 10 | sys = []; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 6; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 6; 19 | sizes.NumInputs = 3; 20 | sizes.DirFeedthrough = 0; 21 | sizes.NumSampleTimes = 1; 22 | sys=simsizes(sizes); 23 | x0=[0 0 0 0 0 0]; 24 | str=[]; 25 | ts=[-1 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | u2=u(1);u3=u(2);u4=u(3); 28 | 29 | Init; 30 | 31 | theta=x(1);dtheta=x(2); 32 | psi=x(3);dpsi=x(4); 33 | phi=x(5);dphi=x(6); 34 | 35 | d4=0.10*sin(t); 36 | d5=0.10*sin(t); 37 | d6=0.10*sin(t); 38 | 39 | ddtheta=u2+d4; 40 | ddpsi=u3+d5; 41 | ddphi=u4+d6; 42 | 43 | sys(1)=x(2); 44 | sys(2)=ddtheta; 45 | sys(3)=x(4); 46 | sys(4)=ddpsi; 47 | sys(5)=x(6); 48 | sys(6)=ddphi; 49 | function sys=mdlOutputs(t,x,u) 50 | theta=x(1);dtheta=x(2); 51 | psi=x(3);dpsi=x(4); 52 | phi=x(5);dphi=x(6); 53 | 54 | sys(1)=theta; 55 | sys(2)=dtheta; 56 | sys(3)=psi; 57 | sys(4)=dpsi; 58 | sys(5)=phi; 59 | sys(6)=dphi; -------------------------------------------------------------------------------- /PID/Init.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/PID/Init.m -------------------------------------------------------------------------------- /PID/Pcontrol.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/PID/Pcontrol.m -------------------------------------------------------------------------------- /PID/Positionmodel.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts]=Model(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2, 4, 9 } 10 | sys = []; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 6; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 6; 19 | sizes.NumInputs = 7; 20 | sizes.DirFeedthrough = 0; 21 | sizes.NumSampleTimes = 1; 22 | sys=simsizes(sizes); 23 | x0=[2 0 1 0 0 0]; 24 | str=[]; 25 | ts=[-1 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | u1=u(1); 28 | theta=u(2); 29 | psi=u(4); 30 | phi=u(6); 31 | 32 | Init; 33 | 34 | x1=x(1);dx1=x(2); 35 | y=x(3);dy=x(4); 36 | z=x(5);dz=x(6); 37 | 38 | ddx=u1*(cos(phi)*sin(theta)*cos(psi)+sin(phi)*sin(psi)); 39 | ddy=u1*(sin(phi)*sin(theta)*cos(psi)-cos(phi)*sin(psi)); 40 | ddz=u1*(cos(phi)*cos(psi))-g; 41 | 42 | sys(1)=x(2); 43 | sys(2)=ddx; 44 | sys(3)=x(4); 45 | sys(4)=ddy; 46 | sys(5)=x(6); 47 | sys(6)=ddz; 48 | function sys=mdlOutputs(t,x,u) 49 | x1=x(1);dx1=x(2); 50 | y=x(3);dy=x(4); 51 | z=x(5);dz=x(6); 52 | 53 | sys(1)=x1; 54 | sys(2)=dx1; 55 | sys(3)=y; 56 | sys(4)=dy; 57 | sys(5)=z; 58 | sys(6)=dz; -------------------------------------------------------------------------------- /PID/TD1.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts] = spacemodel(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2,4,9} 10 | sys=[]; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 3; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 3; 19 | sizes.NumInputs = 1; 20 | sizes.DirFeedthrough = 1; 21 | sizes.NumSampleTimes = 1; 22 | sys = simsizes(sizes); 23 | x0 = [0 0 0]; 24 | str = []; 25 | ts = [0 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | ebs=0.10; 28 | vt=u(1); 29 | temp1=(abs(ebs*x(2))^(9/7))*sign(ebs*x(2)); 30 | temp2=x(1)-vt+temp1; 31 | temp2=abs(temp2)^(1/3)*sign(temp2); 32 | temp3=abs(ebs^2*x(3))^(3/5)*sign(ebs^2*x(3)); 33 | sys(1)=x(2); 34 | sys(2)=x(3); 35 | sys(3)=(-2^(3/5)*4*temp2-4*temp3)*1/ebs^3; 36 | function sys=mdlOutputs(t,x,u) 37 | v=u(1); 38 | sys(1)=v; 39 | sys(2)=x(2); 40 | sys(3)=x(3); -------------------------------------------------------------------------------- /PID/TD2.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts] = spacemodel(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2,4,9} 10 | sys=[]; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 3; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 3; 19 | sizes.NumInputs = 1; 20 | sizes.DirFeedthrough = 1; 21 | sizes.NumSampleTimes = 1; 22 | sys = simsizes(sizes); 23 | x0 = [0 0 0]; 24 | str = []; 25 | ts = [0 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | ebs=0.04; 28 | vt=u(1); 29 | temp1=(abs(ebs*x(2))^(9/7))*sign(ebs*x(2)); 30 | temp2=x(1)-vt+temp1; 31 | temp2=abs(temp2)^(1/3)*sign(temp2); 32 | temp3=abs(ebs^2*x(3))^(3/5)*sign(ebs^2*x(3)); 33 | sys(1)=x(2); 34 | sys(2)=x(3); 35 | sys(3)=(-2^(3/5)*4*temp2-4*temp3)*1/ebs^3; 36 | function sys=mdlOutputs(t,x,u) 37 | v=u(1); 38 | sys(1)=v; 39 | sys(2)=x(2); 40 | sys(3)=x(3); -------------------------------------------------------------------------------- /PID/slidemodel.mdl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/PID/slidemodel.mdl -------------------------------------------------------------------------------- /PID/slidemodel_plot.m: -------------------------------------------------------------------------------- 1 | close all; 2 | figure(1); 3 | subplot(311); 4 | plot(t,x(:,1),'b','linewidth',2); 5 | xlabel('Time(s)');ylabel('x'); 6 | legend('x'); 7 | subplot(312); 8 | plot(t,x(:,3),'b','linewidth',2); 9 | xlabel('Time(s)');ylabel('y'); 10 | legend('y'); 11 | subplot(313); 12 | zd=3*t./t; 13 | plot(t,zd,'r--',t,x(:,5),'b','linewidth',2); 14 | xlabel('Time(s)');ylabel('z'); 15 | legend('zd','z'); 16 | 17 | figure(2); 18 | subplot(311); 19 | plot(t,Angle(:,1)/pi*180,'r',t,x(:,7)/pi*180,'k','linewidth',2); 20 | legend('\phid(degree)','\phi (degree)'); 21 | subplot(312); 22 | plot(t,Angle(:,2)/pi*180,'r',t,x(:,9)/pi*180,'k','linewidth',2); 23 | legend('\theta_d (degree)','\theta (degree)'); 24 | subplot(313); 25 | plot(t,60*t./t,'r--',t,x(:,11)/pi*180,'b','linewidth',2); 26 | legend('\psi_d (degree)','\psi (degree)'); 27 | figure(3); 28 | subplot(411); 29 | plot(t,ut(:,1),'k','linewidth',2); 30 | legend('u1'); 31 | subplot(412); 32 | plot(t,ut(:,2),'k','linewidth',2); 33 | legend('u2'); 34 | subplot(413); 35 | plot(t,ut(:,3),'k','linewidth',2); 36 | legend('u3'); 37 | subplot(414); 38 | plot(t,ut(:,4),'k','linewidth',2); 39 | legend('u4'); -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Matlab-GA 2 | -------------------------------------------------------------------------------- /demo/Untitled3.m: -------------------------------------------------------------------------------- 1 | clear all; 2 | close all; 3 | ts = 1e-4; 4 | In = 5; 5 | Kp = 60; 6 | Ki = 1; 7 | Kd = 3; 8 | simOut = sim('demo1'); 9 | for k = 1:1:length(out) 10 | time(k) = k * ts; 11 | end 12 | figure(1);plot(time,out);grid on; -------------------------------------------------------------------------------- /demo/demo1.mdl: -------------------------------------------------------------------------------- 1 | Model { 2 | Name "demo1" 3 | Version 8.5 4 | MdlSubVersion 0 5 | SavedCharacterEncoding "GBK" 6 | GraphicalInterface { 7 | NumRootInports 0 8 | NumRootOutports 0 9 | ParameterArgumentNames "" 10 | ComputedModelVersion "1.8" 11 | NumModelReferences 0 12 | NumTestPointedSignals 0 13 | } 14 | ScopeRefreshTime 0.035000 15 | OverrideScopeRefreshTime on 16 | DisableAllScopes on 17 | DataTypeOverride "UseLocalSettings" 18 | DataTypeOverrideAppliesTo "AllNumericTypes" 19 | MinMaxOverflowLogging "UseLocalSettings" 20 | MinMaxOverflowArchiveMode "Overwrite" 21 | FPTRunName "Run 1" 22 | MaxMDLFileLineLength 120 23 | Object { 24 | $PropName "BdWindowsInfo" 25 | $ObjectID 1 26 | $ClassName "Simulink.BDWindowsInfo" 27 | Object { 28 | $PropName "WindowsInfo" 29 | $ObjectID 2 30 | $ClassName "Simulink.WindowInfo" 31 | IsActive [1] 32 | Location [-7.0, 0.0, 974.0, 1057.0] 33 | Object { 34 | $PropName "ModelBrowserInfo" 35 | $ObjectID 3 36 | $ClassName "Simulink.ModelBrowserInfo" 37 | Visible [0] 38 | DockPosition "Left" 39 | Width [50] 40 | Height [50] 41 | Filter [9] 42 | } 43 | Object { 44 | $PropName "ExplorerBarInfo" 45 | $ObjectID 4 46 | $ClassName "Simulink.ExplorerBarInfo" 47 | Visible [1] 48 | } 49 | Object { 50 | $PropName "EditorsInfo" 51 | $ObjectID 5 52 | $ClassName "Simulink.EditorInfo" 53 | IsActive [1] 54 | ViewObjType "SimulinkTopLevel" 55 | LoadSaveID "0" 56 | Extents [924.0, 879.0] 57 | ZoomFactor [1.0] 58 | Offset [0.0, 0.0] 59 | } 60 | } 61 | } 62 | Created "Fri Apr 13 09:57:45 2018" 63 | Creator "18813" 64 | UpdateHistory "UpdateHistoryNever" 65 | ModifiedByFormat "%" 66 | LastModifiedBy "18813" 67 | ModifiedDateFormat "%" 68 | LastModifiedDate "Fri May 11 20:41:37 2018" 69 | RTWModifiedTimeStamp 447972051 70 | ModelVersionFormat "1.%" 71 | ConfigurationManager "none" 72 | SampleTimeColors off 73 | SampleTimeAnnotations off 74 | LibraryLinkDisplay "disabled" 75 | WideLines off 76 | ShowLineDimensions off 77 | ShowPortDataTypes off 78 | ShowDesignRanges off 79 | ShowLoopsOnError on 80 | IgnoreBidirectionalLines off 81 | ShowStorageClass off 82 | ShowTestPointIcons on 83 | ShowSignalResolutionIcons on 84 | ShowViewerIcons on 85 | SortedOrder off 86 | ExecutionContextIcon off 87 | ShowLinearizationAnnotations on 88 | ShowMarkup on 89 | BlockNameDataTip off 90 | BlockParametersDataTip off 91 | BlockDescriptionStringDataTip off 92 | ToolBar on 93 | StatusBar on 94 | BrowserShowLibraryLinks off 95 | BrowserLookUnderMasks off 96 | SimulationMode "normal" 97 | PauseTimes "5" 98 | NumberOfSteps 1 99 | SnapshotBufferSize 10 100 | SnapshotInterval 10 101 | NumberOfLastSnapshots 0 102 | LinearizationMsg "none" 103 | Profile off 104 | ParamWorkspaceSource "MATLABWorkspace" 105 | AccelSystemTargetFile "accel.tlc" 106 | AccelTemplateMakefile "accel_default_tmf" 107 | AccelMakeCommand "make_rtw" 108 | TryForcingSFcnDF off 109 | Object { 110 | $PropName "DataLoggingOverride" 111 | $ObjectID 6 112 | $ClassName "Simulink.SimulationData.ModelLoggingInfo" 113 | model_ "demo1" 114 | overrideMode_ [0.0] 115 | Array { 116 | Type "Cell" 117 | Dimension 1 118 | Cell "demo1" 119 | PropName "logAsSpecifiedByModels_" 120 | } 121 | Array { 122 | Type "Cell" 123 | Dimension 1 124 | Cell [] 125 | PropName "logAsSpecifiedByModelsSSIDs_" 126 | } 127 | } 128 | RecordCoverage off 129 | CovPath "/" 130 | CovSaveName "covdata" 131 | CovMetricSettings "dw" 132 | CovNameIncrementing off 133 | CovHtmlReporting on 134 | CovForceBlockReductionOff on 135 | CovEnableCumulative on 136 | covSaveCumulativeToWorkspaceVar on 137 | CovSaveSingleToWorkspaceVar on 138 | CovCumulativeVarName "covCumulativeData" 139 | CovCumulativeReport off 140 | CovReportOnPause on 141 | CovModelRefEnable "Off" 142 | CovExternalEMLEnable off 143 | CovSFcnEnable on 144 | CovBoundaryAbsTol 0.000010 145 | CovBoundaryRelTol 0.010000 146 | CovUseTimeInterval off 147 | CovStartTime 0 148 | CovStopTime 0 149 | ExtModeBatchMode off 150 | ExtModeEnableFloating on 151 | ExtModeTrigType "manual" 152 | ExtModeTrigMode "normal" 153 | ExtModeTrigPort "1" 154 | ExtModeTrigElement "any" 155 | ExtModeTrigDuration 1000 156 | ExtModeTrigDurationFloating "auto" 157 | ExtModeTrigHoldOff 0 158 | ExtModeTrigDelay 0 159 | ExtModeTrigDirection "rising" 160 | ExtModeTrigLevel 0 161 | ExtModeArchiveMode "off" 162 | ExtModeAutoIncOneShot off 163 | ExtModeIncDirWhenArm off 164 | ExtModeAddSuffixToVar off 165 | ExtModeWriteAllDataToWs off 166 | ExtModeArmWhenConnect on 167 | ExtModeSkipDownloadWhenConnect off 168 | ExtModeLogAll on 169 | ExtModeAutoUpdateStatusClock on 170 | ShowModelReferenceBlockVersion off 171 | ShowModelReferenceBlockIO off 172 | Array { 173 | Type "Handle" 174 | Dimension 1 175 | Simulink.ConfigSet { 176 | $ObjectID 7 177 | Version "1.15.0" 178 | Array { 179 | Type "Handle" 180 | Dimension 9 181 | Simulink.SolverCC { 182 | $ObjectID 8 183 | Version "1.15.0" 184 | StartTime "0.0" 185 | StopTime "10.0" 186 | AbsTol "auto" 187 | FixedStep "auto" 188 | InitialStep "auto" 189 | MaxNumMinSteps "-1" 190 | MaxOrder 5 191 | ZcThreshold "auto" 192 | ConsecutiveZCsStepRelTol "10*128*eps" 193 | MaxConsecutiveZCs "1000" 194 | ExtrapolationOrder 4 195 | NumberNewtonIterations 1 196 | MaxStep "auto" 197 | MinStep "auto" 198 | MaxConsecutiveMinStep "1" 199 | RelTol "1e-3" 200 | SolverMode "Auto" 201 | EnableConcurrentExecution off 202 | ConcurrentTasks off 203 | Solver "ode45" 204 | SolverName "ode45" 205 | SolverJacobianMethodControl "auto" 206 | ShapePreserveControl "DisableAll" 207 | ZeroCrossControl "UseLocalSettings" 208 | ZeroCrossAlgorithm "Nonadaptive" 209 | AlgebraicLoopSolver "TrustRegion" 210 | SolverResetMethod "Fast" 211 | PositivePriorityOrder off 212 | AutoInsertRateTranBlk off 213 | SampleTimeConstraint "Unconstrained" 214 | InsertRTBMode "Whenever possible" 215 | } 216 | Simulink.DataIOCC { 217 | $ObjectID 9 218 | Version "1.15.0" 219 | Decimation "1" 220 | ExternalInput "[t, u]" 221 | FinalStateName "xFinal" 222 | InitialState "xInitial" 223 | LimitDataPoints on 224 | MaxDataPoints "1000" 225 | LoadExternalInput off 226 | LoadInitialState off 227 | SaveFinalState off 228 | SaveCompleteFinalSimState off 229 | SaveFormat "Array" 230 | SignalLoggingSaveFormat "Dataset" 231 | SaveOutput on 232 | SaveState off 233 | SignalLogging on 234 | DSMLogging on 235 | InspectSignalLogs off 236 | VisualizeSimOutput on 237 | SaveTime on 238 | ReturnWorkspaceOutputs off 239 | StateSaveName "xout" 240 | TimeSaveName "tout" 241 | OutputSaveName "yout" 242 | SignalLoggingName "logsout" 243 | DSMLoggingName "dsmout" 244 | OutputOption "RefineOutputTimes" 245 | OutputTimes "[]" 246 | ReturnWorkspaceOutputsName "out" 247 | Refine "1" 248 | } 249 | Simulink.OptimizationCC { 250 | $ObjectID 10 251 | Version "1.15.0" 252 | Array { 253 | Type "Cell" 254 | Dimension 8 255 | Cell "BooleansAsBitfields" 256 | Cell "PassReuseOutputArgsAs" 257 | Cell "PassReuseOutputArgsThreshold" 258 | Cell "ZeroExternalMemoryAtStartup" 259 | Cell "ZeroInternalMemoryAtStartup" 260 | Cell "OptimizeModelRefInitCode" 261 | Cell "NoFixptDivByZeroProtection" 262 | Cell "UseSpecifiedMinMax" 263 | PropName "DisabledProps" 264 | } 265 | BlockReduction on 266 | BooleanDataType on 267 | ConditionallyExecuteInputs on 268 | InlineParams off 269 | UseDivisionForNetSlopeComputation "off" 270 | UseFloatMulNetSlope off 271 | DefaultUnderspecifiedDataType "double" 272 | UseSpecifiedMinMax off 273 | InlineInvariantSignals off 274 | OptimizeBlockIOStorage on 275 | BufferReuse on 276 | EnhancedBackFolding off 277 | CachingGlobalReferences off 278 | GlobalBufferReuse on 279 | StrengthReduction off 280 | ExpressionFolding on 281 | BooleansAsBitfields off 282 | BitfieldContainerType "uint_T" 283 | EnableMemcpy on 284 | MemcpyThreshold 64 285 | PassReuseOutputArgsAs "Structure reference" 286 | PassReuseOutputArgsThreshold 12 287 | ExpressionDepthLimit 128 288 | LocalBlockOutputs on 289 | RollThreshold 5 290 | StateBitsets off 291 | DataBitsets off 292 | ActiveStateOutputEnumStorageType "Native Integer" 293 | ZeroExternalMemoryAtStartup on 294 | ZeroInternalMemoryAtStartup on 295 | InitFltsAndDblsToZero off 296 | NoFixptDivByZeroProtection off 297 | EfficientFloat2IntCast off 298 | EfficientMapNaN2IntZero on 299 | OptimizeModelRefInitCode off 300 | LifeSpan "inf" 301 | MaxStackSize "Inherit from target" 302 | BufferReusableBoundary on 303 | SimCompilerOptimization "off" 304 | AccelVerboseBuild off 305 | } 306 | Simulink.DebuggingCC { 307 | $ObjectID 11 308 | Version "1.15.0" 309 | RTPrefix "error" 310 | ConsistencyChecking "none" 311 | ArrayBoundsChecking "none" 312 | SignalInfNanChecking "none" 313 | SignalRangeChecking "none" 314 | ReadBeforeWriteMsg "UseLocalSettings" 315 | WriteAfterWriteMsg "UseLocalSettings" 316 | WriteAfterReadMsg "UseLocalSettings" 317 | AlgebraicLoopMsg "warning" 318 | ArtificialAlgebraicLoopMsg "warning" 319 | SaveWithDisabledLinksMsg "warning" 320 | SaveWithParameterizedLinksMsg "warning" 321 | CheckSSInitialOutputMsg on 322 | UnderspecifiedInitializationDetection "Simplified" 323 | MergeDetectMultiDrivingBlocksExec "error" 324 | CheckExecutionContextPreStartOutputMsg off 325 | CheckExecutionContextRuntimeOutputMsg off 326 | SignalResolutionControl "UseLocalSettings" 327 | BlockPriorityViolationMsg "warning" 328 | MinStepSizeMsg "warning" 329 | TimeAdjustmentMsg "none" 330 | MaxConsecutiveZCsMsg "error" 331 | MaskedZcDiagnostic "warning" 332 | IgnoredZcDiagnostic "warning" 333 | SolverPrmCheckMsg "none" 334 | InheritedTsInSrcMsg "warning" 335 | DiscreteInheritContinuousMsg "warning" 336 | MultiTaskDSMMsg "error" 337 | MultiTaskCondExecSysMsg "error" 338 | MultiTaskRateTransMsg "error" 339 | SingleTaskRateTransMsg "none" 340 | TasksWithSamePriorityMsg "warning" 341 | SigSpecEnsureSampleTimeMsg "warning" 342 | CheckMatrixSingularityMsg "none" 343 | IntegerOverflowMsg "warning" 344 | Int32ToFloatConvMsg "warning" 345 | ParameterDowncastMsg "error" 346 | ParameterOverflowMsg "error" 347 | ParameterUnderflowMsg "none" 348 | ParameterPrecisionLossMsg "warning" 349 | ParameterTunabilityLossMsg "warning" 350 | FixptConstUnderflowMsg "none" 351 | FixptConstOverflowMsg "none" 352 | FixptConstPrecisionLossMsg "none" 353 | UnderSpecifiedDataTypeMsg "none" 354 | UnnecessaryDatatypeConvMsg "none" 355 | VectorMatrixConversionMsg "none" 356 | InvalidFcnCallConnMsg "error" 357 | FcnCallInpInsideContextMsg "EnableAllAsError" 358 | SignalLabelMismatchMsg "none" 359 | UnconnectedInputMsg "warning" 360 | UnconnectedOutputMsg "warning" 361 | UnconnectedLineMsg "warning" 362 | SFcnCompatibilityMsg "none" 363 | FrameProcessingCompatibilityMsg "error" 364 | UniqueDataStoreMsg "none" 365 | BusObjectLabelMismatch "warning" 366 | RootOutportRequireBusObject "warning" 367 | AssertControl "UseLocalSettings" 368 | ModelReferenceIOMsg "none" 369 | ModelReferenceMultiInstanceNormalModeStructChecksumCheck "error" 370 | ModelReferenceVersionMismatchMessage "none" 371 | ModelReferenceIOMismatchMessage "none" 372 | UnknownTsInhSupMsg "warning" 373 | ModelReferenceDataLoggingMessage "warning" 374 | ModelReferenceSymbolNameMessage "warning" 375 | ModelReferenceExtraNoncontSigs "error" 376 | StateNameClashWarn "none" 377 | SimStateInterfaceChecksumMismatchMsg "warning" 378 | SimStateOlderReleaseMsg "error" 379 | InitInArrayFormatMsg "warning" 380 | StrictBusMsg "ErrorLevel1" 381 | BusNameAdapt "WarnAndRepair" 382 | NonBusSignalsTreatedAsBus "none" 383 | BlockIODiagnostic "none" 384 | SFUnusedDataAndEventsDiag "warning" 385 | SFUnexpectedBacktrackingDiag "warning" 386 | SFInvalidInputDataAccessInChartInitDiag "warning" 387 | SFNoUnconditionalDefaultTransitionDiag "warning" 388 | SFTransitionOutsideNaturalParentDiag "warning" 389 | SFUnconditionalTransitionShadowingDiag "warning" 390 | SFUndirectedBroadcastEventsDiag "warning" 391 | SFTransitionActionBeforeConditionDiag "warning" 392 | SFOutputUsedAsStateInMooreChartDiag "error" 393 | IntegerSaturationMsg "warning" 394 | } 395 | Simulink.HardwareCC { 396 | $ObjectID 12 397 | Version "1.15.0" 398 | ProdBitPerChar 8 399 | ProdBitPerShort 16 400 | ProdBitPerInt 32 401 | ProdBitPerLong 32 402 | ProdBitPerLongLong 64 403 | ProdBitPerFloat 32 404 | ProdBitPerDouble 64 405 | ProdBitPerPointer 32 406 | ProdLargestAtomicInteger "Char" 407 | ProdLargestAtomicFloat "None" 408 | ProdIntDivRoundTo "Undefined" 409 | ProdEndianess "Unspecified" 410 | ProdWordSize 32 411 | ProdShiftRightIntArith on 412 | ProdLongLongMode off 413 | ProdHWDeviceType "32-bit Generic" 414 | TargetBitPerChar 8 415 | TargetBitPerShort 16 416 | TargetBitPerInt 32 417 | TargetBitPerLong 32 418 | TargetBitPerLongLong 64 419 | TargetBitPerFloat 32 420 | TargetBitPerDouble 64 421 | TargetBitPerPointer 32 422 | TargetLargestAtomicInteger "Char" 423 | TargetLargestAtomicFloat "None" 424 | TargetShiftRightIntArith on 425 | TargetLongLongMode off 426 | TargetIntDivRoundTo "Undefined" 427 | TargetEndianess "Unspecified" 428 | TargetWordSize 32 429 | TargetPreprocMaxBitsSint 32 430 | TargetPreprocMaxBitsUint 32 431 | TargetHWDeviceType "Specified" 432 | TargetUnknown off 433 | ProdEqTarget on 434 | } 435 | Simulink.ModelReferenceCC { 436 | $ObjectID 13 437 | Version "1.15.0" 438 | UpdateModelReferenceTargets "IfOutOfDateOrStructuralChange" 439 | CheckModelReferenceTargetMessage "error" 440 | EnableParallelModelReferenceBuilds off 441 | ParallelModelReferenceErrorOnInvalidPool on 442 | ParallelModelReferenceMATLABWorkerInit "None" 443 | ModelReferenceNumInstancesAllowed "Multi" 444 | PropagateVarSize "Infer from blocks in model" 445 | ModelReferencePassRootInputsByReference on 446 | ModelReferenceMinAlgLoopOccurrences off 447 | PropagateSignalLabelsOutOfModel off 448 | SupportModelReferenceSimTargetCustomCode off 449 | } 450 | Simulink.SFSimCC { 451 | $ObjectID 14 452 | Version "1.15.0" 453 | SFSimOverflowDetection on 454 | SFSimEcho on 455 | SimCtrlC on 456 | SimIntegrity on 457 | SimUseLocalCustomCode off 458 | SimParseCustomCode on 459 | SimBuildMode "sf_incremental_build" 460 | SimGenImportedTypeDefs off 461 | } 462 | Simulink.RTWCC { 463 | $BackupClass "Simulink.RTWCC" 464 | $ObjectID 15 465 | Version "1.15.0" 466 | Array { 467 | Type "Cell" 468 | Dimension 16 469 | Cell "IncludeHyperlinkInReport" 470 | Cell "GenerateTraceInfo" 471 | Cell "GenerateTraceReport" 472 | Cell "GenerateTraceReportSl" 473 | Cell "GenerateTraceReportSf" 474 | Cell "GenerateTraceReportEml" 475 | Cell "PortableWordSizes" 476 | Cell "GenerateWebview" 477 | Cell "GenerateCodeMetricsReport" 478 | Cell "GenerateCodeReplacementReport" 479 | Cell "GenerateMissedCodeReplacementReport" 480 | Cell "GenerateErtSFunction" 481 | Cell "CreateSILPILBlock" 482 | Cell "CodeExecutionProfiling" 483 | Cell "CodeProfilingSaveOptions" 484 | Cell "CodeProfilingInstrumentation" 485 | PropName "DisabledProps" 486 | } 487 | SystemTargetFile "grt.tlc" 488 | TLCOptions "" 489 | GenCodeOnly off 490 | MakeCommand "make_rtw" 491 | GenerateMakefile on 492 | PackageGeneratedCodeAndArtifacts off 493 | PackageName "" 494 | TemplateMakefile "grt_default_tmf" 495 | PostCodeGenCommand "" 496 | Description "" 497 | GenerateReport off 498 | SaveLog off 499 | RTWVerbose on 500 | RetainRTWFile off 501 | ProfileTLC off 502 | TLCDebug off 503 | TLCCoverage off 504 | TLCAssert off 505 | RTWUseLocalCustomCode off 506 | RTWUseSimCustomCode off 507 | CustomSourceCode "" 508 | CustomHeaderCode "" 509 | CustomInclude "" 510 | CustomSource "" 511 | CustomLibrary "" 512 | CustomInitializer "" 513 | CustomTerminator "" 514 | Toolchain "Automatically locate an installed toolchain" 515 | BuildConfiguration "Faster Builds" 516 | IncludeHyperlinkInReport off 517 | LaunchReport off 518 | PortableWordSizes off 519 | CreateSILPILBlock "None" 520 | CodeExecutionProfiling off 521 | CodeExecutionProfileVariable "executionProfile" 522 | CodeProfilingSaveOptions "SummaryOnly" 523 | CodeProfilingInstrumentation off 524 | SILDebugging off 525 | TargetLang "C" 526 | IncludeBusHierarchyInRTWFileBlockHierarchyMap off 527 | GenerateTraceInfo off 528 | GenerateTraceReport off 529 | GenerateTraceReportSl off 530 | GenerateTraceReportSf off 531 | GenerateTraceReportEml off 532 | GenerateWebview off 533 | GenerateCodeMetricsReport off 534 | GenerateCodeReplacementReport off 535 | GenerateMissedCodeReplacementReport off 536 | RTWCompilerOptimization "off" 537 | RTWCustomCompilerOptimizations "" 538 | CheckMdlBeforeBuild "Off" 539 | SharedConstantsCachingThreshold 1024 540 | Array { 541 | Type "Handle" 542 | Dimension 2 543 | Simulink.CodeAppCC { 544 | $ObjectID 16 545 | Version "1.15.0" 546 | Array { 547 | Type "Cell" 548 | Dimension 24 549 | Cell "IgnoreCustomStorageClasses" 550 | Cell "ParameterTuningSideEffectCode" 551 | Cell "IgnoreTestpoints" 552 | Cell "InsertBlockDesc" 553 | Cell "InsertPolySpaceComments" 554 | Cell "SFDataObjDesc" 555 | Cell "MATLABFcnDesc" 556 | Cell "SimulinkDataObjDesc" 557 | Cell "DefineNamingRule" 558 | Cell "SignalNamingRule" 559 | Cell "ParamNamingRule" 560 | Cell "InternalIdentifier" 561 | Cell "InlinedPrmAccess" 562 | Cell "CustomSymbolStr" 563 | Cell "CustomSymbolStrGlobalVar" 564 | Cell "CustomSymbolStrType" 565 | Cell "CustomSymbolStrField" 566 | Cell "CustomSymbolStrFcn" 567 | Cell "CustomSymbolStrFcnArg" 568 | Cell "CustomSymbolStrBlkIO" 569 | Cell "CustomSymbolStrTmpVar" 570 | Cell "CustomSymbolStrMacro" 571 | Cell "CustomSymbolStrUtil" 572 | Cell "ReqsInCode" 573 | PropName "DisabledProps" 574 | } 575 | ForceParamTrailComments off 576 | GenerateComments on 577 | CommentStyle "Auto" 578 | IgnoreCustomStorageClasses on 579 | IgnoreTestpoints off 580 | IncHierarchyInIds off 581 | MaxIdLength 31 582 | PreserveName off 583 | PreserveNameWithParent off 584 | ShowEliminatedStatement off 585 | OperatorAnnotations off 586 | IncAutoGenComments off 587 | SimulinkDataObjDesc off 588 | SFDataObjDesc off 589 | MATLABFcnDesc off 590 | IncDataTypeInIds off 591 | MangleLength 1 592 | CustomSymbolStrGlobalVar "$R$N$M" 593 | CustomSymbolStrType "$N$R$M_T" 594 | CustomSymbolStrField "$N$M" 595 | CustomSymbolStrFcn "$R$N$M$F" 596 | CustomSymbolStrFcnArg "rt$I$N$M" 597 | CustomSymbolStrBlkIO "rtb_$N$M" 598 | CustomSymbolStrTmpVar "$N$M" 599 | CustomSymbolStrMacro "$R$N$M" 600 | CustomSymbolStrUtil "$N$C" 601 | DefineNamingRule "None" 602 | ParamNamingRule "None" 603 | SignalNamingRule "None" 604 | InsertBlockDesc off 605 | InsertPolySpaceComments off 606 | SimulinkBlockComments on 607 | MATLABSourceComments off 608 | EnableCustomComments off 609 | InternalIdentifier "Shortened" 610 | InlinedPrmAccess "Literals" 611 | ReqsInCode off 612 | UseSimReservedNames off 613 | } 614 | Simulink.GRTTargetCC { 615 | $BackupClass "Simulink.TargetCC" 616 | $ObjectID 17 617 | Version "1.15.0" 618 | Array { 619 | Type "Cell" 620 | Dimension 13 621 | Cell "GeneratePreprocessorConditionals" 622 | Cell "IncludeMdlTerminateFcn" 623 | Cell "SuppressErrorStatus" 624 | Cell "ERTCustomFileBanners" 625 | Cell "GenerateSampleERTMain" 626 | Cell "GenerateTestInterfaces" 627 | Cell "ModelStepFunctionPrototypeControlCompliant" 628 | Cell "GenerateAllocFcn" 629 | Cell "PurelyIntegerCode" 630 | Cell "SupportComplex" 631 | Cell "SupportAbsoluteTime" 632 | Cell "SupportContinuousTime" 633 | Cell "SupportNonInlinedSFcns" 634 | PropName "DisabledProps" 635 | } 636 | TargetFcnLib "ansi_tfl_table_tmw.mat" 637 | TargetLibSuffix "" 638 | TargetPreCompLibLocation "" 639 | GenFloatMathFcnCalls "NOT IN USE" 640 | TargetLangStandard "C89/C90 (ANSI)" 641 | CodeReplacementLibrary "None" 642 | UtilityFuncGeneration "Auto" 643 | ERTMultiwordTypeDef "System defined" 644 | ERTMultiwordLength 256 645 | MultiwordLength 2048 646 | GenerateFullHeader on 647 | InferredTypesCompatibility off 648 | GenerateSampleERTMain off 649 | GenerateTestInterfaces off 650 | ModelReferenceCompliant on 651 | ParMdlRefBuildCompliant on 652 | CompOptLevelCompliant on 653 | ConcurrentExecutionCompliant on 654 | IncludeMdlTerminateFcn on 655 | GeneratePreprocessorConditionals "Disable all" 656 | CombineOutputUpdateFcns on 657 | CombineSignalStateStructs off 658 | SuppressErrorStatus off 659 | ERTFirstTimeCompliant off 660 | IncludeFileDelimiter "Auto" 661 | ERTCustomFileBanners off 662 | SupportAbsoluteTime on 663 | LogVarNameModifier "rt_" 664 | MatFileLogging on 665 | MultiInstanceERTCode off 666 | CodeInterfacePackaging "Nonreusable function" 667 | SupportNonFinite on 668 | SupportComplex on 669 | PurelyIntegerCode off 670 | SupportContinuousTime on 671 | SupportNonInlinedSFcns on 672 | SupportVariableSizeSignals off 673 | ParenthesesLevel "Nominal" 674 | CastingMode "Nominal" 675 | MATLABClassNameForMDSCustomization "Simulink.SoftwareTarget.GRTCustomization" 676 | ModelStepFunctionPrototypeControlCompliant off 677 | CPPClassGenCompliant on 678 | AutosarCompliant off 679 | GRTInterface off 680 | GenerateAllocFcn off 681 | GenerateSharedConstants on 682 | UseMalloc off 683 | ExtMode off 684 | ExtModeStaticAlloc off 685 | ExtModeTesting off 686 | ExtModeStaticAllocSize 1000000 687 | ExtModeTransport 0 688 | ExtModeMexFile "ext_comm" 689 | ExtModeIntrfLevel "Level1" 690 | RTWCAPISignals off 691 | RTWCAPIParams off 692 | RTWCAPIStates off 693 | RTWCAPIRootIO off 694 | GenerateASAP2 off 695 | MultiInstanceErrorCode "Error" 696 | } 697 | PropName "Components" 698 | } 699 | } 700 | hdlcoderui.hdlcc { 701 | $ObjectID 18 702 | Version "1.15.0" 703 | Description "HDL Coder custom configuration component" 704 | Name "HDL Coder" 705 | Array { 706 | Type "Cell" 707 | Dimension 1 708 | Cell " " 709 | PropName "HDLConfigFile" 710 | } 711 | HDLCActiveTab "0" 712 | } 713 | PropName "Components" 714 | } 715 | Name "Configuration" 716 | CurrentDlgPage "Solver" 717 | ConfigPrmDlgPosition [ 420, 220, 1500, 860 ] 718 | } 719 | PropName "ConfigurationSets" 720 | } 721 | Simulink.ConfigSet { 722 | $PropName "ActiveConfigurationSet" 723 | $ObjectID 7 724 | } 725 | Object { 726 | $PropName "DataTransfer" 727 | $ObjectID 19 728 | $ClassName "Simulink.GlobalDataTransfer" 729 | DefaultTransitionBetweenSyncTasks "Ensure deterministic transfer (maximum delay)" 730 | DefaultTransitionBetweenAsyncTasks "Ensure data integrity only" 731 | DefaultTransitionBetweenContTasks "Ensure deterministic transfer (minimum delay)" 732 | DefaultExtrapolationMethodBetweenContTasks "None" 733 | AutoInsertRateTranBlk [0] 734 | } 735 | ExplicitPartitioning off 736 | BlockDefaults { 737 | ForegroundColor "black" 738 | BackgroundColor "white" 739 | DropShadow off 740 | NamePlacement "normal" 741 | FontName "Helvetica" 742 | FontSize 10 743 | FontWeight "normal" 744 | FontAngle "normal" 745 | ShowName on 746 | BlockRotation 0 747 | BlockMirror off 748 | } 749 | AnnotationDefaults { 750 | HorizontalAlignment "center" 751 | VerticalAlignment "middle" 752 | ForegroundColor "black" 753 | BackgroundColor "white" 754 | DropShadow off 755 | FontName "Helvetica" 756 | FontSize 10 757 | FontWeight "normal" 758 | FontAngle "normal" 759 | UseDisplayTextAsClickCallback off 760 | } 761 | LineDefaults { 762 | FontName "Helvetica" 763 | FontSize 9 764 | FontWeight "normal" 765 | FontAngle "normal" 766 | } 767 | MaskDefaults { 768 | SelfModifiable "off" 769 | IconFrame "on" 770 | IconOpaque "on" 771 | RunInitForIconRedraw "off" 772 | IconRotate "none" 773 | PortRotate "default" 774 | IconUnits "autoscale" 775 | } 776 | MaskParameterDefaults { 777 | Evaluate "on" 778 | Tunable "on" 779 | NeverSave "off" 780 | Internal "off" 781 | ReadOnly "off" 782 | Enabled "on" 783 | Visible "on" 784 | ToolTip "on" 785 | } 786 | BlockParameterDefaults { 787 | Block { 788 | BlockType Constant 789 | Value "1" 790 | VectorParams1D on 791 | SamplingMode "Sample based" 792 | OutMin "[]" 793 | OutMax "[]" 794 | OutDataTypeStr "Inherit: Inherit from 'Constant value'" 795 | LockScale off 796 | SampleTime "inf" 797 | FramePeriod "inf" 798 | PreserveConstantTs off 799 | } 800 | Block { 801 | BlockType Mux 802 | Inputs "4" 803 | DisplayOption "none" 804 | UseBusObject off 805 | BusObject "BusObject" 806 | NonVirtualBus off 807 | } 808 | Block { 809 | BlockType Scope 810 | ModelBased off 811 | TickLabels "OneTimeTick" 812 | ZoomMode "on" 813 | Grid "on" 814 | ShowLegends off 815 | TimeRange "auto" 816 | YMin "-5" 817 | YMax "5" 818 | SaveToWorkspace off 819 | SaveName "ScopeData" 820 | DataFormat "Array" 821 | LimitDataPoints on 822 | MaxDataPoints "5000" 823 | Decimation "1" 824 | SampleInput off 825 | SampleTime "-1" 826 | ScrollMode off 827 | } 828 | Block { 829 | BlockType Sum 830 | IconShape "rectangular" 831 | Inputs "++" 832 | CollapseMode "All dimensions" 833 | CollapseDim "1" 834 | InputSameDT on 835 | AccumDataTypeStr "Inherit: Inherit via internal rule" 836 | OutMin "[]" 837 | OutMax "[]" 838 | OutDataTypeStr "Inherit: Same as first input" 839 | LockScale off 840 | RndMeth "Floor" 841 | SaturateOnIntegerOverflow on 842 | SampleTime "-1" 843 | } 844 | Block { 845 | BlockType ToWorkspace 846 | VariableName "simulink_output" 847 | MaxDataPoints "1000" 848 | Decimation "1" 849 | SaveFormat "Array" 850 | Save2DSignal "Inherit from input (this choice will be removed - see release notes)" 851 | FixptAsFi off 852 | NumInputs "1" 853 | SampleTime "0" 854 | } 855 | Block { 856 | BlockType TransferFcn 857 | Numerator "[1]" 858 | Denominator "[1 2 1]" 859 | AbsoluteTolerance "auto" 860 | ContinuousStateAttributes "''" 861 | Realization "auto" 862 | } 863 | } 864 | System { 865 | Name "demo1" 866 | Location [-7, 0, 967, 1057] 867 | Open on 868 | ModelBrowserVisibility off 869 | ModelBrowserWidth 200 870 | ScreenColor "white" 871 | PaperOrientation "landscape" 872 | PaperPositionMode "auto" 873 | PaperType "usletter" 874 | PaperUnits "inches" 875 | TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] 876 | TiledPageScale 1 877 | ShowPageBoundaries off 878 | ZoomFactor "100" 879 | ReportName "simulink-default.rpt" 880 | SIDHighWatermark "19" 881 | Block { 882 | BlockType Constant 883 | Name "Constant" 884 | SID "14" 885 | Position [205, 280, 235, 310] 886 | ZOrder 3 887 | Value "5" 888 | } 889 | Block { 890 | BlockType Mux 891 | Name "Mux" 892 | SID "17" 893 | Ports [2, 1] 894 | Position [690, 258, 720, 322] 895 | ZOrder 6 896 | ShowName off 897 | Inputs "2" 898 | DisplayOption "bar" 899 | } 900 | Block { 901 | BlockType Reference 902 | Name "PID Controller" 903 | SID "12" 904 | Ports [1, 1] 905 | Position [370, 279, 430, 331] 906 | ZOrder 1 907 | LibraryVersion "1.356" 908 | SourceBlock "simulink/Continuous/PID Controller" 909 | SourceType "PID 1dof" 910 | ContentPreviewEnabled off 911 | Controller "PID" 912 | TimeDomain "Continuous-time" 913 | SampleTime "-1" 914 | IntegratorMethod "Forward Euler" 915 | FilterMethod "Forward Euler" 916 | Form "Parallel" 917 | UseFilter on 918 | ControllerParametersSource "internal" 919 | P "Kp" 920 | I "Ki" 921 | D "Kd" 922 | N "100" 923 | InitialConditionSource "internal" 924 | InitialConditionForIntegrator "0" 925 | InitialConditionForFilter "0" 926 | ExternalReset "none" 927 | IgnoreLimit off 928 | ZeroCross on 929 | LimitOutput off 930 | UpperSaturationLimit "inf" 931 | LowerSaturationLimit "-inf" 932 | LinearizeAsGain on 933 | AntiWindupMode "none" 934 | Kb "1" 935 | TrackingMode off 936 | Kt "1" 937 | RndMeth "Floor" 938 | SaturateOnIntegerOverflow off 939 | LockScale off 940 | PParamMin "[]" 941 | PParamMax "[]" 942 | PParamDataTypeStr "Inherit: Inherit via internal rule" 943 | IParamMin "[]" 944 | IParamMax "[]" 945 | IParamDataTypeStr "Inherit: Inherit via internal rule" 946 | DParamMin "[]" 947 | DParamMax "[]" 948 | DParamDataTypeStr "Inherit: Inherit via internal rule" 949 | NParamMin "[]" 950 | NParamMax "[]" 951 | NParamDataTypeStr "Inherit: Inherit via internal rule" 952 | KbParamMin "[]" 953 | KbParamMax "[]" 954 | KbParamDataTypeStr "Inherit: Inherit via internal rule" 955 | KtParamMin "[]" 956 | KtParamMax "[]" 957 | KtParamDataTypeStr "Inherit: Inherit via internal rule" 958 | POutMin "[]" 959 | POutMax "[]" 960 | POutDataTypeStr "Inherit: Inherit via internal rule" 961 | PGainOutDataTypeStr "Inherit: Inherit via internal rule" 962 | PProdOutDataTypeStr "Inherit: Inherit via internal rule" 963 | IOutMin "[]" 964 | IOutMax "[]" 965 | IOutDataTypeStr "Inherit: Inherit via internal rule" 966 | IGainOutDataTypeStr "Inherit: Inherit via internal rule" 967 | IProdOutDataTypeStr "Inherit: Inherit via internal rule" 968 | DOutMin "[]" 969 | DOutMax "[]" 970 | DOutDataTypeStr "Inherit: Inherit via internal rule" 971 | DGainOutDataTypeStr "Inherit: Inherit via internal rule" 972 | DProdOutDataTypeStr "Inherit: Inherit via internal rule" 973 | NOutMin "[]" 974 | NOutMax "[]" 975 | NOutDataTypeStr "Inherit: Inherit via internal rule" 976 | NGainOutDataTypeStr "Inherit: Inherit via internal rule" 977 | NProdOutDataTypeStr "Inherit: Inherit via internal rule" 978 | KbOutMin "[]" 979 | KbOutMax "[]" 980 | KbOutDataTypeStr "Inherit: Inherit via internal rule" 981 | KtOutMin "[]" 982 | KtOutMax "[]" 983 | KtOutDataTypeStr "Inherit: Inherit via internal rule" 984 | IntegratorOutMin "[]" 985 | IntegratorOutMax "[]" 986 | IntegratorOutDataTypeStr "Inherit: Inherit via internal rule" 987 | FilterOutMin "[]" 988 | FilterOutMax "[]" 989 | FilterOutDataTypeStr "Inherit: Inherit via internal rule" 990 | SumOutMin "[]" 991 | SumOutMax "[]" 992 | SumOutDataTypeStr "Inherit: Inherit via internal rule" 993 | SumI1OutMin "[]" 994 | SumI1OutMax "[]" 995 | SumI1OutDataTypeStr "Inherit: Inherit via internal rule" 996 | SumI2OutMin "[]" 997 | SumI2OutMax "[]" 998 | SumI2OutDataTypeStr "Inherit: Inherit via internal rule" 999 | SumI3OutMin "[]" 1000 | SumI3OutMax "[]" 1001 | SumI3OutDataTypeStr "Inherit: Inherit via internal rule" 1002 | SumDOutMin "[]" 1003 | SumDOutMax "[]" 1004 | SumDOutDataTypeStr "Inherit: Inherit via internal rule" 1005 | SumAccumDataTypeStr "Inherit: Inherit via internal rule" 1006 | SumI1AccumDataTypeStr "Inherit: Inherit via internal rule" 1007 | SumI2AccumDataTypeStr "Inherit: Inherit via internal rule" 1008 | SumI3AccumDataTypeStr "Inherit: Inherit via internal rule" 1009 | SumDAccumDataTypeStr "Inherit: Inherit via internal rule" 1010 | SaturationOutMin "[]" 1011 | SaturationOutMax "[]" 1012 | SaturationOutDataTypeStr "Inherit: Same as input" 1013 | IntegratorContinuousStateAttributes "''" 1014 | IntegratorStateMustResolveToSignalObject off 1015 | IntegratorRTWStateStorageClass "Auto" 1016 | FilterContinuousStateAttributes "''" 1017 | FilterStateMustResolveToSignalObject off 1018 | FilterRTWStateStorageClass "Auto" 1019 | DifferentiatorICPrevScaledInput "0" 1020 | DifferentiatorOutMin "[]" 1021 | DifferentiatorOutMax "[]" 1022 | DifferentiatorOutDataTypeStr "Inherit: Inherit via internal rule" 1023 | } 1024 | Block { 1025 | BlockType Scope 1026 | Name "Scope" 1027 | SID "18" 1028 | Ports [1] 1029 | Position [790, 274, 820, 306] 1030 | ZOrder 7 1031 | Floating off 1032 | Location [1, 49, 1921, 1049] 1033 | Open off 1034 | NumInputPorts "1" 1035 | List { 1036 | ListType AxesTitles 1037 | axes1 "%" 1038 | } 1039 | List { 1040 | ListType ScopeGraphics 1041 | FigureColor "[0.5 0.5 0.5]" 1042 | AxesColor "[0 0 0]" 1043 | AxesTickColor "[1 1 1]" 1044 | LineColors "[1 1 0;1 0 1;0 1 1;1 0 0;0 1 0;0 0 1]" 1045 | LineStyles "-|-|-|-|-|-" 1046 | LineWidths "[0.5 0.5 0.5 0.5 0.5 0.5]" 1047 | MarkerStyles "none|none|none|none|none|none" 1048 | } 1049 | } 1050 | Block { 1051 | BlockType Sum 1052 | Name "Subtract" 1053 | SID "16" 1054 | Ports [2, 1] 1055 | Position [305, 287, 335, 318] 1056 | ZOrder 5 1057 | Inputs "+-" 1058 | InputSameDT off 1059 | OutDataTypeStr "Inherit: Inherit via internal rule" 1060 | SaturateOnIntegerOverflow off 1061 | } 1062 | Block { 1063 | BlockType ToWorkspace 1064 | Name "To Workspace" 1065 | SID "19" 1066 | Ports [1] 1067 | Position [690, 395, 750, 425] 1068 | ZOrder 8 1069 | VariableName "out" 1070 | MaxDataPoints "inf" 1071 | Save2DSignal "3-D array (concatenate along third dimension)" 1072 | FixptAsFi on 1073 | SampleTime "-1" 1074 | } 1075 | Block { 1076 | BlockType TransferFcn 1077 | Name "Transfer Fcn" 1078 | SID "13" 1079 | Position [505, 279, 580, 331] 1080 | ZOrder 2 1081 | Numerator "[133]" 1082 | Denominator "[1 25 0]" 1083 | } 1084 | Line { 1085 | ZOrder 1 1086 | SrcBlock "PID Controller" 1087 | SrcPort 1 1088 | DstBlock "Transfer Fcn" 1089 | DstPort 1 1090 | } 1091 | Line { 1092 | ZOrder 3 1093 | SrcBlock "Subtract" 1094 | SrcPort 1 1095 | DstBlock "PID Controller" 1096 | DstPort 1 1097 | } 1098 | Line { 1099 | ZOrder 4 1100 | SrcBlock "Constant" 1101 | SrcPort 1 1102 | Points [38, 0] 1103 | Branch { 1104 | ZOrder 9 1105 | Points [0, -74; 335, 0; 0, 54] 1106 | DstBlock "Mux" 1107 | DstPort 1 1108 | } 1109 | Branch { 1110 | ZOrder 8 1111 | DstBlock "Subtract" 1112 | DstPort 1 1113 | } 1114 | } 1115 | Line { 1116 | ZOrder 5 1117 | SrcBlock "Transfer Fcn" 1118 | SrcPort 1 1119 | Points [27, 0] 1120 | Branch { 1121 | ZOrder 7 1122 | Points [0, 106; -322, 0] 1123 | DstBlock "Subtract" 1124 | DstPort 2 1125 | } 1126 | Branch { 1127 | ZOrder 6 1128 | Points [35, 0] 1129 | Branch { 1130 | ZOrder 13 1131 | Points [0, 105] 1132 | DstBlock "To Workspace" 1133 | DstPort 1 1134 | } 1135 | Branch { 1136 | ZOrder 12 1137 | DstBlock "Mux" 1138 | DstPort 2 1139 | } 1140 | } 1141 | } 1142 | Line { 1143 | ZOrder 11 1144 | SrcBlock "Mux" 1145 | SrcPort 1 1146 | DstBlock "Scope" 1147 | DstPort 1 1148 | } 1149 | } 1150 | } 1151 | -------------------------------------------------------------------------------- /模糊滑模控制/Acontrol.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/模糊滑模控制/Acontrol.m -------------------------------------------------------------------------------- /模糊滑模控制/Anglemodel.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts]=chap14_5plant(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2, 4, 9 } 10 | sys = []; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 6; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 6; 19 | sizes.NumInputs = 3; 20 | sizes.DirFeedthrough = 0; 21 | sizes.NumSampleTimes = 1; 22 | sys=simsizes(sizes); 23 | x0=[0 0 0 0 0 0]; 24 | str=[]; 25 | ts=[-1 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | u2=u(1);u3=u(2);u4=u(3); 28 | 29 | Init; 30 | 31 | theta=x(1);dtheta=x(2); 32 | psi=x(3);dpsi=x(4); 33 | phi=x(5);dphi=x(6); 34 | 35 | d4=0.10*sin(t); 36 | d5=0.10*sin(t); 37 | d6=0.10*sin(t); 38 | 39 | ddtheta=u2+d4; 40 | ddpsi=u3+d5; 41 | ddphi=u4+d6; 42 | 43 | sys(1)=x(2); 44 | sys(2)=ddtheta; 45 | sys(3)=x(4); 46 | sys(4)=ddpsi; 47 | sys(5)=x(6); 48 | sys(6)=ddphi; 49 | function sys=mdlOutputs(t,x,u) 50 | theta=x(1);dtheta=x(2); 51 | psi=x(3);dpsi=x(4); 52 | phi=x(5);dphi=x(6); 53 | 54 | sys(1)=theta; 55 | sys(2)=dtheta; 56 | sys(3)=psi; 57 | sys(4)=dpsi; 58 | sys(5)=phi; 59 | sys(6)=dphi; -------------------------------------------------------------------------------- /模糊滑模控制/Init.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/模糊滑模控制/Init.m -------------------------------------------------------------------------------- /模糊滑模控制/Pcontrol.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/模糊滑模控制/Pcontrol.m -------------------------------------------------------------------------------- /模糊滑模控制/Positionmodel.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts]=Model(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2, 4, 9 } 10 | sys = []; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 6; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 6; 19 | sizes.NumInputs = 7; 20 | sizes.DirFeedthrough = 0; 21 | sizes.NumSampleTimes = 1; 22 | sys=simsizes(sizes); 23 | x0=[2 0 1 0 0 0]; 24 | str=[]; 25 | ts=[-1 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | u1=u(1); 28 | theta=u(2); 29 | psi=u(4); 30 | phi=u(6); 31 | 32 | Init; 33 | 34 | d1=0.10*sin(t); 35 | d2=0.10*sin(t); 36 | d3=0.10*sin(t); 37 | 38 | 39 | x1=x(1);dx1=x(2); 40 | y=x(3);dy=x(4); 41 | z=x(5);dz=x(6); 42 | 43 | ddx=u1*(cos(phi)*sin(theta)*cos(psi)+sin(phi)*sin(psi))/m ; 44 | ddy=u1*(sin(phi)*sin(theta)*cos(psi)-cos(phi)*sin(psi))/m ; 45 | ddz=u1*(cos(phi)*cos(psi))/m-g ; 46 | 47 | sys(1)=x(2); 48 | sys(2)=ddx; 49 | sys(3)=x(4); 50 | sys(4)=ddy; 51 | sys(5)=x(6); 52 | sys(6)=ddz; 53 | function sys=mdlOutputs(t,x,u) 54 | x1=x(1);dx1=x(2); 55 | y=x(3);dy=x(4); 56 | z=x(5);dz=x(6); 57 | 58 | sys(1)=x1; 59 | sys(2)=dx1; 60 | sys(3)=y; 61 | sys(4)=dy; 62 | sys(5)=z; 63 | sys(6)=dz; -------------------------------------------------------------------------------- /模糊滑模控制/TD1.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts] = spacemodel(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2,4,9} 10 | sys=[]; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 3; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 3; 19 | sizes.NumInputs = 1; 20 | sizes.DirFeedthrough = 1; 21 | sizes.NumSampleTimes = 1; 22 | sys = simsizes(sizes); 23 | x0 = [0 0 0]; 24 | str = []; 25 | ts = [0 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | ebs=0.10; 28 | vt=u(1); 29 | temp1=(abs(ebs*x(2))^(9/7))*sign(ebs*x(2)); 30 | temp2=x(1)-vt+temp1; 31 | temp2=abs(temp2)^(1/3)*sign(temp2); 32 | temp3=abs(ebs^2*x(3))^(3/5)*sign(ebs^2*x(3)); 33 | sys(1)=x(2); 34 | sys(2)=x(3); 35 | sys(3)=(-2^(3/5)*4*temp2-4*temp3)*1/ebs^3; 36 | function sys=mdlOutputs(t,x,u) 37 | v=u(1); 38 | sys(1)=v; 39 | sys(2)=x(2); 40 | sys(3)=x(3); -------------------------------------------------------------------------------- /模糊滑模控制/TD2.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts] = spacemodel(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2,4,9} 10 | sys=[]; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 3; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 3; 19 | sizes.NumInputs = 1; 20 | sizes.DirFeedthrough = 1; 21 | sizes.NumSampleTimes = 1; 22 | sys = simsizes(sizes); 23 | x0 = [0 0 0]; 24 | str = []; 25 | ts = [0 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | ebs=0.04; 28 | vt=u(1); 29 | temp1=(abs(ebs*x(2))^(9/7))*sign(ebs*x(2)); 30 | temp2=x(1)-vt+temp1; 31 | temp2=abs(temp2)^(1/3)*sign(temp2); 32 | temp3=abs(ebs^2*x(3))^(3/5)*sign(ebs^2*x(3)); 33 | sys(1)=x(2); 34 | sys(2)=x(3); 35 | sys(3)=(-2^(3/5)*4*temp2-4*temp3)*1/ebs^3; 36 | function sys=mdlOutputs(t,x,u) 37 | v=u(1); 38 | sys(1)=v; 39 | sys(2)=x(2); 40 | sys(3)=x(3); -------------------------------------------------------------------------------- /模糊滑模控制/createfuzz.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/模糊滑模控制/createfuzz.m -------------------------------------------------------------------------------- /模糊滑模控制/fuzz.asv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/模糊滑模控制/fuzz.asv -------------------------------------------------------------------------------- /模糊滑模控制/fuzz_1.fis: -------------------------------------------------------------------------------- 1 | [System] 2 | Name='fuzz_1' 3 | Type='mamdani' 4 | Version=2.0 5 | NumInputs=2 6 | NumOutputs=1 7 | NumRules=49 8 | AndMethod='min' 9 | OrMethod='max' 10 | ImpMethod='min' 11 | AggMethod='max' 12 | DefuzzMethod='centroid' 13 | 14 | [Input1] 15 | Name='s' 16 | Range=[-25 25] 17 | NumMFs=7 18 | MF1='NB':'zmf',[-25 -15] 19 | MF2='NM':'trimf',[-20 -15 -10] 20 | MF3='NS':'trimf',[-15 -10 -5] 21 | MF4='ZE':'trimf',[-10 0 10] 22 | MF5='PS':'trimf',[5 10 15] 23 | MF6='PM':'trimf',[10 15 20] 24 | MF7='PB':'smf',[15 25] 25 | 26 | [Input2] 27 | Name='ds' 28 | Range=[-25 25] 29 | NumMFs=7 30 | MF1='NB':'zmf',[-25 -15] 31 | MF2='NM':'trimf',[-20 -15 -10] 32 | MF3='NS':'trimf',[-15 -10 -5] 33 | MF4='ZE':'trimf',[-10 0 10] 34 | MF5='PS':'trimf',[5 10 15] 35 | MF6='PM':'trimf',[10 15 20] 36 | MF7='PB':'smf',[15 25] 37 | 38 | [Output1] 39 | Name='k' 40 | Range=[-2.5 2.5] 41 | NumMFs=7 42 | MF1='NB':'zmf',[-2.5 -1.5] 43 | MF2='NM':'trimf',[-2 -1.5 -1] 44 | MF3='NS':'trimf',[-1.5 -1 -0.5] 45 | MF4='ZE':'trimf',[-1 0 1] 46 | MF5='PS':'trimf',[0.5 1 1.5] 47 | MF6='PM':'trimf',[1 1.5 2] 48 | MF7='PB':'smf',[1.5 2.5] 49 | 50 | [Rules] 51 | 1 1, 7 (1) : 1 52 | 1 2, 7 (1) : 1 53 | 1 3, 7 (1) : 1 54 | 1 4, 7 (1) : 1 55 | 1 5, 7 (1) : 1 56 | 1 6, 4 (1) : 1 57 | 1 7, 4 (1) : 1 58 | 2 1, 7 (1) : 1 59 | 2 2, 7 (1) : 1 60 | 2 3, 7 (1) : 1 61 | 2 4, 7 (1) : 1 62 | 2 5, 6 (1) : 1 63 | 2 6, 4 (1) : 1 64 | 2 7, 4 (1) : 1 65 | 3 1, 6 (1) : 1 66 | 3 2, 6 (1) : 1 67 | 3 3, 6 (1) : 1 68 | 3 4, 6 (1) : 1 69 | 3 5, 4 (1) : 1 70 | 3 6, 3 (1) : 1 71 | 3 7, 3 (1) : 1 72 | 4 1, 6 (1) : 1 73 | 4 2, 6 (1) : 1 74 | 4 3, 5 (1) : 1 75 | 4 4, 4 (1) : 1 76 | 4 5, 3 (1) : 1 77 | 4 6, 2 (1) : 1 78 | 4 7, 2 (1) : 1 79 | 5 1, 5 (1) : 1 80 | 5 2, 5 (1) : 1 81 | 5 3, 4 (1) : 1 82 | 5 4, 3 (1) : 1 83 | 5 5, 2 (1) : 1 84 | 5 6, 2 (1) : 1 85 | 5 7, 2 (1) : 1 86 | 6 1, 4 (1) : 1 87 | 6 2, 4 (1) : 1 88 | 6 3, 2 (1) : 1 89 | 6 4, 1 (1) : 1 90 | 6 5, 1 (1) : 1 91 | 6 6, 1 (1) : 1 92 | 6 7, 1 (1) : 1 93 | 7 1, 4 (1) : 1 94 | 7 2, 4 (1) : 1 95 | 7 3, 2 (1) : 1 96 | 7 4, 1 (1) : 1 97 | 7 5, 1 (1) : 1 98 | 7 6, 1 (1) : 1 99 | 7 7, 1 (1) : 1 100 | -------------------------------------------------------------------------------- /模糊滑模控制/fuzz_rule.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/模糊滑模控制/fuzz_rule.m -------------------------------------------------------------------------------- /模糊滑模控制/slidemodel.mdl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/模糊滑模控制/slidemodel.mdl -------------------------------------------------------------------------------- /模糊滑模控制/slidemodel_plot.m: -------------------------------------------------------------------------------- 1 | angle1 = 0*t./t; 2 | figure(1); 3 | plot(t,angle1, 'r--',t,x(:,7)/pi*180,'k','linewidth',2); 4 | legend('\phi_d (degree)','\phi (degree)'); 5 | xlabel('time(s)') 6 | figure(2); 7 | plot(t,angle1, 'r--',t,x(:,9)/pi*180,'k','linewidth',2); 8 | legend('\theta_d (degree)','\theta (degree)'); 9 | xlabel('time(s)') 10 | figure(3); 11 | plot(t,60 * t./t, 'r--',t,x(:,11)/pi*180,'k','linewidth',2); 12 | legend('\psi_d (degree)','\psi (degree)'); 13 | xlabel('time(s)') -------------------------------------------------------------------------------- /滑模控制/Acontrol.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts] = spacemodel(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2,4,9} 10 | sys=[]; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 0; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 3; 19 | sizes.NumInputs = 14; 20 | sizes.DirFeedthrough = 1; 21 | sizes.NumSampleTimes = 1; 22 | sys = simsizes(sizes); 23 | x0 = []; 24 | str = []; 25 | ts = [0 0]; 26 | function sys=mdlOutputs(t,x,u) 27 | Init; 28 | 29 | dphid=0;ddphid=0; 30 | thetad=u(1); 31 | psid=u(2); 32 | dthetad=u(4); 33 | ddthetad=u(5); 34 | dpsid=u(7); 35 | ddpsid=u(8); 36 | 37 | theta=u(9);dtheta=u(10); 38 | psi=u(11);dpsi=u(12); 39 | phi=u(13);dphi=u(14); 40 | 41 | thetae=theta-thetad;dthetae=dtheta-dthetad; 42 | s4=c4*thetae+dthetae; 43 | 44 | psie=psi-psid;dpsie=dpsi-dpsid; 45 | s5=c5*psie+dpsie; 46 | 47 | phie=phi-phid;dphie=dphi-dphid; 48 | s6=c6*phie+dphie; 49 | 50 | delta=0.10; 51 | if abs(s4)>delta 52 | sat_s4=sign(s4); 53 | else 54 | sat_s4=1/delta*s4; 55 | end 56 | if abs(s5)>delta 57 | sat_s5=sign(s5); 58 | else 59 | sat_s5=1/delta*s6; 60 | end 61 | if abs(s6)>delta 62 | sat_s6=sign(s6); 63 | else 64 | sat_s6=1/delta*s6; 65 | end 66 | 67 | u2=-c4*dthetae+ddthetad-eta4*sign(s4); 68 | u3=-c5*dpsie+ddpsid-eta5*sign(s5); 69 | u4=-c6*dphie+ddphid-eta6*sign(s6); 70 | 71 | sys(1)=u2; 72 | sys(2)=u3; 73 | sys(3)=u4; -------------------------------------------------------------------------------- /滑模控制/Anglemodel.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts]=chap14_5plant(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2, 4, 9 } 10 | sys = []; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 6; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 6; 19 | sizes.NumInputs = 3; 20 | sizes.DirFeedthrough = 0; 21 | sizes.NumSampleTimes = 1; 22 | sys=simsizes(sizes); 23 | x0=[0 0 0 0 0 0]; 24 | str=[]; 25 | ts=[-1 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | u2=u(1);u3=u(2);u4=u(3); 28 | 29 | Init; 30 | 31 | theta=x(1);dtheta=x(2); 32 | psi=x(3);dpsi=x(4); 33 | phi=x(5);dphi=x(6); 34 | 35 | d4=0.1 * sin(t); 36 | d5=0.1 * sin(t); 37 | d6=0.1 * sin(t); 38 | 39 | ddtheta=u2 + d4; 40 | ddpsi=u3 + d5; 41 | ddphi=u4 + d6; 42 | 43 | sys(1)=x(2); 44 | sys(2)=ddtheta; 45 | sys(3)=x(4); 46 | sys(4)=ddpsi; 47 | sys(5)=x(6); 48 | sys(6)=ddphi; 49 | function sys=mdlOutputs(t,x,u) 50 | theta=x(1);dtheta=x(2); 51 | psi=x(3);dpsi=x(4); 52 | phi=x(5);dphi=x(6); 53 | 54 | sys(1)=theta; 55 | sys(2)=dtheta; 56 | sys(3)=psi; 57 | sys(4)=dpsi; 58 | sys(5)=phi; 59 | sys(6)=dphi; -------------------------------------------------------------------------------- /滑模控制/Init.m: -------------------------------------------------------------------------------- 1 | %Parameters Value 2 | m=2;l=0.2;g=9.8; 3 | %K1=0.01;K2=0.01;K3=0.01;K4=0.012;K5=0.012;K6=0.012; 4 | I1=1.25;I2=1.25;I3=2.5; 5 | 6 | c1=5;c2=5;c3=5; 7 | c4=30;c5=30;c6=30; 8 | 9 | %k1=5;k2=5;k3=5; 10 | %k4=50;k5=50;k6=50; 11 | 12 | eta1=1.5;eta2=1.5;eta3=1.5; 13 | eta4=15;eta5=15;eta6=15; 14 | 15 | zd=3.0; 16 | phid=pi/3; 17 | angled = 0; -------------------------------------------------------------------------------- /滑模控制/Pcontrol.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/滑模控制/Pcontrol.m -------------------------------------------------------------------------------- /滑模控制/Positionmodel.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts]=Model(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2, 4, 9 } 10 | sys = []; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 6; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 6; 19 | sizes.NumInputs = 7; 20 | sizes.DirFeedthrough = 0; 21 | sizes.NumSampleTimes = 1; 22 | sys=simsizes(sizes); 23 | x0=[2 0 1 0 0 0]; 24 | str=[]; 25 | ts=[-1 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | u1=u(1); 28 | theta=u(2); 29 | psi=u(4); 30 | phi=u(6); 31 | 32 | Init; 33 | d1=0.1 * sin(t); 34 | d2=0.1 * sin(t); 35 | d3=0.1 * sin(t); 36 | 37 | x1=x(1);dx1=x(2); 38 | y=x(3);dy=x(4); 39 | z=x(5);dz=x(6); 40 | 41 | ddx=u1*(cos(phi)*sin(theta)*cos(psi)+sin(phi)*sin(psi))/m; 42 | ddy=u1*(sin(phi)*sin(theta)*cos(psi)-cos(phi)*sin(psi))/m; 43 | ddz=u1*(cos(phi)*cos(psi))/m-g; 44 | 45 | sys(1)=x(2); 46 | sys(2)=ddx; 47 | sys(3)=x(4); 48 | sys(4)=ddy; 49 | sys(5)=x(6); 50 | sys(6)=ddz; 51 | function sys=mdlOutputs(t,x,u) 52 | x1=x(1);dx1=x(2); 53 | y=x(3);dy=x(4); 54 | z=x(5);dz=x(6); 55 | 56 | sys(1)=x1; 57 | sys(2)=dx1; 58 | sys(3)=y; 59 | sys(4)=dy; 60 | sys(5)=z; 61 | sys(6)=dz; -------------------------------------------------------------------------------- /滑模控制/TD1.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts] = spacemodel(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2,4,9} 10 | sys=[]; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 3; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 3; 19 | sizes.NumInputs = 1; 20 | sizes.DirFeedthrough = 1; 21 | sizes.NumSampleTimes = 1; 22 | sys = simsizes(sizes); 23 | x0 = [0 0 0]; 24 | str = []; 25 | ts = [0 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | ebs=0.10; 28 | vt=u(1); 29 | temp1=(abs(ebs*x(2))^(9/7))*sign(ebs*x(2)); 30 | temp2=x(1)-vt+temp1; 31 | temp2=abs(temp2)^(1/3)*sign(temp2); 32 | temp3=abs(ebs^2*x(3))^(3/5)*sign(ebs^2*x(3)); 33 | sys(1)=x(2); 34 | sys(2)=x(3); 35 | sys(3)=(-2^(3/5)*4*temp2-4*temp3)*1/ebs^3; 36 | function sys=mdlOutputs(t,x,u) 37 | v=u(1); 38 | sys(1)=v; 39 | sys(2)=x(2); 40 | sys(3)=x(3); -------------------------------------------------------------------------------- /滑模控制/TD2.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts] = spacemodel(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2,4,9} 10 | sys=[]; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 3; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 3; 19 | sizes.NumInputs = 1; 20 | sizes.DirFeedthrough = 1; 21 | sizes.NumSampleTimes = 1; 22 | sys = simsizes(sizes); 23 | x0 = [0 0 0]; 24 | str = []; 25 | ts = [0 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | ebs=0.04; 28 | vt=u(1); 29 | temp1=(abs(ebs*x(2))^(9/7))*sign(ebs*x(2)); 30 | temp2=x(1)-vt+temp1; 31 | temp2=abs(temp2)^(1/3)*sign(temp2); 32 | temp3=abs(ebs^2*x(3))^(3/5)*sign(ebs^2*x(3)); 33 | sys(1)=x(2); 34 | sys(2)=x(3); 35 | sys(3)=(-2^(3/5)*4*temp2-4*temp3)*1/ebs^3; 36 | function sys=mdlOutputs(t,x,u) 37 | v=u(1); 38 | sys(1)=v; 39 | sys(2)=x(2); 40 | sys(3)=x(3); -------------------------------------------------------------------------------- /滑模控制/slidemodel.mdl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/滑模控制/slidemodel.mdl -------------------------------------------------------------------------------- /滑模控制/slidemodel_plot.m: -------------------------------------------------------------------------------- 1 | close all; 2 | figure(1); 3 | subplot(311); 4 | plot(t,x(:,1),'b','linewidth',2); 5 | xlabel('Time(s)');ylabel('x(m)'); 6 | legend('x'); 7 | subplot(312); 8 | plot(t,x(:,3),'b','linewidth',2); 9 | xlabel('Time(s)');ylabel('y(m)'); 10 | legend('y'); 11 | subplot(313); 12 | zd=3*t./t; 13 | plot(t,zd,'r--',t,x(:,5),'b','linewidth',2); 14 | xlabel('Time(s)');ylabel('z(m)'); 15 | legend('zd','z'); 16 | 17 | 18 | angle1 = 0*t./t; 19 | figure(2); 20 | plot(t,angle1, 'r--',t,x(:,7)/pi*180,'k','linewidth',2); 21 | legend('\phi_d (degree)','\phi (degree)'); 22 | xlabel('time(s)') 23 | figure(3); 24 | plot(t,angle1, 'r--',t,x(:,9)/pi*180,'k','linewidth',2); 25 | legend('\theta_d (degree)','\theta (degree)'); 26 | xlabel('time(s)') 27 | figure(4); 28 | plot(t,60 * t./t, 'r--',t,x(:,11)/pi*180,'k','linewidth',2); 29 | legend('\psi_d (degree)','\psi (degree)'); 30 | xlabel('time(s)') -------------------------------------------------------------------------------- /遗传算法优化/Acontrol.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/遗传算法优化/Acontrol.m -------------------------------------------------------------------------------- /遗传算法优化/Anglemodel.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts]=chap14_5plant(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2, 4, 9 } 10 | sys = []; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 6; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 6; 19 | sizes.NumInputs = 3; 20 | sizes.DirFeedthrough = 0; 21 | sizes.NumSampleTimes = 1; 22 | sys=simsizes(sizes); 23 | x0=[0 0 0 0 0 0]; 24 | str=[]; 25 | ts=[-1 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | u2=u(1);u3=u(2);u4=u(3); 28 | 29 | Init; 30 | 31 | theta=x(1);dtheta=x(2); 32 | psi=x(3);dpsi=x(4); 33 | phi=x(5);dphi=x(6); 34 | 35 | d4=0.10*sin(t); 36 | d5=0.10*sin(t); 37 | d6=0.10*sin(t); 38 | 39 | ddtheta=u2+d4; 40 | ddpsi=u3+d5; 41 | ddphi=u4+d6; 42 | 43 | sys(1)=x(2); 44 | sys(2)=ddtheta; 45 | sys(3)=x(4); 46 | sys(4)=ddpsi; 47 | sys(5)=x(6); 48 | sys(6)=ddphi; 49 | function sys=mdlOutputs(t,x,u) 50 | theta=x(1);dtheta=x(2); 51 | psi=x(3);dpsi=x(4); 52 | phi=x(5);dphi=x(6); 53 | 54 | sys(1)=theta; 55 | sys(2)=dtheta; 56 | sys(3)=psi; 57 | sys(4)=dpsi; 58 | sys(5)=phi; 59 | sys(6)=dphi; -------------------------------------------------------------------------------- /遗传算法优化/GAcode.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/遗传算法优化/GAcode.m -------------------------------------------------------------------------------- /遗传算法优化/Init.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/遗传算法优化/Init.m -------------------------------------------------------------------------------- /遗传算法优化/Pcontrol.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/遗传算法优化/Pcontrol.m -------------------------------------------------------------------------------- /遗传算法优化/Positionmodel.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts]=Model(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2, 4, 9 } 10 | sys = []; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 6; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 6; 19 | sizes.NumInputs = 7; 20 | sizes.DirFeedthrough = 0; 21 | sizes.NumSampleTimes = 1; 22 | sys=simsizes(sizes); 23 | x0=[2 0 1 0 0 0]; 24 | str=[]; 25 | ts=[-1 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | u1=u(1); 28 | theta=u(2); 29 | psi=u(4); 30 | phi=u(6); 31 | 32 | Init; 33 | 34 | x1=x(1);dx1=x(2); 35 | y=x(3);dy=x(4); 36 | z=x(5);dz=x(6); 37 | 38 | ddx=u1*(cos(phi)*sin(theta)*cos(psi)+sin(phi)*sin(psi))/m; 39 | ddy=u1*(sin(phi)*sin(theta)*cos(psi)-cos(phi)*sin(psi))/m; 40 | ddz=u1*(cos(phi)*cos(psi))/m-g; 41 | 42 | sys(1)=x(2); 43 | sys(2)=ddx; 44 | sys(3)=x(4); 45 | sys(4)=ddy; 46 | sys(5)=x(6); 47 | sys(6)=ddz; 48 | function sys=mdlOutputs(t,x,u) 49 | x1=x(1);dx1=x(2); 50 | y=x(3);dy=x(4); 51 | z=x(5);dz=x(6); 52 | 53 | sys(1)=x1; 54 | sys(2)=dx1; 55 | sys(3)=y; 56 | sys(4)=dy; 57 | sys(5)=z; 58 | sys(6)=dz; -------------------------------------------------------------------------------- /遗传算法优化/TD1.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts] = spacemodel(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2,4,9} 10 | sys=[]; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 3; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 3; 19 | sizes.NumInputs = 1; 20 | sizes.DirFeedthrough = 1; 21 | sizes.NumSampleTimes = 1; 22 | sys = simsizes(sizes); 23 | x0 = [0 0 0]; 24 | str = []; 25 | ts = [0 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | ebs=0.10; 28 | vt=u(1); 29 | temp1=(abs(ebs*x(2))^(9/7))*sign(ebs*x(2)); 30 | temp2=x(1)-vt+temp1; 31 | temp2=abs(temp2)^(1/3)*sign(temp2); 32 | temp3=abs(ebs^2*x(3))^(3/5)*sign(ebs^2*x(3)); 33 | sys(1)=x(2); 34 | sys(2)=x(3); 35 | sys(3)=(-2^(3/5)*4*temp2-4*temp3)*1/ebs^3; 36 | function sys=mdlOutputs(t,x,u) 37 | v=u(1); 38 | sys(1)=v; 39 | sys(2)=x(2); 40 | sys(3)=x(3); -------------------------------------------------------------------------------- /遗传算法优化/TD2.m: -------------------------------------------------------------------------------- 1 | function [sys,x0,str,ts] = spacemodel(t,x,u,flag) 2 | switch flag, 3 | case 0, 4 | [sys,x0,str,ts]=mdlInitializeSizes; 5 | case 1, 6 | sys=mdlDerivatives(t,x,u); 7 | case 3, 8 | sys=mdlOutputs(t,x,u); 9 | case {2,4,9} 10 | sys=[]; 11 | otherwise 12 | error(['Unhandled flag = ',num2str(flag)]); 13 | end 14 | function [sys,x0,str,ts]=mdlInitializeSizes 15 | sizes = simsizes; 16 | sizes.NumContStates = 3; 17 | sizes.NumDiscStates = 0; 18 | sizes.NumOutputs = 3; 19 | sizes.NumInputs = 1; 20 | sizes.DirFeedthrough = 1; 21 | sizes.NumSampleTimes = 1; 22 | sys = simsizes(sizes); 23 | x0 = [0 0 0]; 24 | str = []; 25 | ts = [0 0]; 26 | function sys=mdlDerivatives(t,x,u) 27 | ebs=0.04; 28 | vt=u(1); 29 | temp1=(abs(ebs*x(2))^(9/7))*sign(ebs*x(2)); 30 | temp2=x(1)-vt+temp1; 31 | temp2=abs(temp2)^(1/3)*sign(temp2); 32 | temp3=abs(ebs^2*x(3))^(3/5)*sign(ebs^2*x(3)); 33 | sys(1)=x(2); 34 | sys(2)=x(3); 35 | sys(3)=(-2^(3/5)*4*temp2-4*temp3)*1/ebs^3; 36 | function sys=mdlOutputs(t,x,u) 37 | v=u(1); 38 | sys(1)=v; 39 | sys(2)=x(2); 40 | sys(3)=x(3); -------------------------------------------------------------------------------- /遗传算法优化/fitness.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/遗传算法优化/fitness.m -------------------------------------------------------------------------------- /遗传算法优化/fuzz_1.fis: -------------------------------------------------------------------------------- 1 | [System] 2 | Name='fuzz_1' 3 | Type='mamdani' 4 | Version=2.0 5 | NumInputs=2 6 | NumOutputs=1 7 | NumRules=49 8 | AndMethod='min' 9 | OrMethod='max' 10 | ImpMethod='min' 11 | AggMethod='max' 12 | DefuzzMethod='centroid' 13 | 14 | [Input1] 15 | Name='s' 16 | Range=[-25 25] 17 | NumMFs=7 18 | MF1='NB':'zmf',[-25 -15] 19 | MF2='NM':'trimf',[-20 -15 -10] 20 | MF3='NS':'trimf',[-15 -10 -5] 21 | MF4='ZE':'trimf',[-10 0 10] 22 | MF5='PS':'trimf',[5 10 15] 23 | MF6='PM':'trimf',[10 15 20] 24 | MF7='PB':'smf',[15 25] 25 | 26 | [Input2] 27 | Name='ds' 28 | Range=[-25 25] 29 | NumMFs=7 30 | MF1='NB':'zmf',[-25 -15] 31 | MF2='NM':'trimf',[-20 -15 -10] 32 | MF3='NS':'trimf',[-15 -10 -5] 33 | MF4='ZE':'trimf',[-10 0 10] 34 | MF5='PS':'trimf',[5 10 15] 35 | MF6='PM':'trimf',[10 15 20] 36 | MF7='PB':'smf',[15 25] 37 | 38 | [Output1] 39 | Name='k' 40 | Range=[-2.5 2.5] 41 | NumMFs=7 42 | MF1='NB':'zmf',[-2.5 -1.5] 43 | MF2='NM':'trimf',[-2 -1.5 -1] 44 | MF3='NS':'trimf',[-1.5 -1 -0.5] 45 | MF4='ZE':'trimf',[-1 0 1] 46 | MF5='PS':'trimf',[0.5 1 1.5] 47 | MF6='PM':'trimf',[1 1.5 2] 48 | MF7='PB':'smf',[1.5 2.5] 49 | 50 | [Rules] 51 | 1 1, 4 (1) : 1 52 | 1 2, 4 (1) : 1 53 | 1 3, 2 (1) : 1 54 | 1 4, 3 (1) : 1 55 | 1 5, 6 (1) : 1 56 | 1 6, 7 (1) : 1 57 | 1 7, 4 (1) : 1 58 | 2 1, 4 (1) : 1 59 | 2 2, 5 (1) : 1 60 | 2 3, 5 (1) : 1 61 | 2 4, 4 (1) : 1 62 | 2 5, 4 (1) : 1 63 | 2 6, 5 (1) : 1 64 | 2 7, 5 (1) : 1 65 | 3 1, 3 (1) : 1 66 | 3 2, 2 (1) : 1 67 | 3 3, 6 (1) : 1 68 | 3 4, 7 (1) : 1 69 | 3 5, 3 (1) : 1 70 | 3 6, 5 (1) : 1 71 | 3 7, 4 (1) : 1 72 | 4 1, 4 (1) : 1 73 | 4 2, 4 (1) : 1 74 | 4 3, 5 (1) : 1 75 | 4 4, 5 (1) : 1 76 | 4 5, 2 (1) : 1 77 | 4 6, 1 (1) : 1 78 | 4 7, 3 (1) : 1 79 | 5 1, 6 (1) : 1 80 | 5 2, 4 (1) : 1 81 | 5 3, 5 (1) : 1 82 | 5 4, 3 (1) : 1 83 | 5 5, 6 (1) : 1 84 | 5 6, 3 (1) : 1 85 | 5 7, 3 (1) : 1 86 | 6 1, 7 (1) : 1 87 | 6 2, 2 (1) : 1 88 | 6 3, 2 (1) : 1 89 | 6 4, 5 (1) : 1 90 | 6 5, 1 (1) : 1 91 | 6 6, 2 (1) : 1 92 | 6 7, 4 (1) : 1 93 | 7 1, 6 (1) : 1 94 | 7 2, 4 (1) : 1 95 | 7 3, 4 (1) : 1 96 | 7 4, 2 (1) : 1 97 | 7 5, 2 (1) : 1 98 | 7 6, 5 (1) : 1 99 | 7 7, 2 (1) : 1 100 | -------------------------------------------------------------------------------- /遗传算法优化/fuzz_rule.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/遗传算法优化/fuzz_rule.m -------------------------------------------------------------------------------- /遗传算法优化/gaot/Contents.m: -------------------------------------------------------------------------------- 1 | % Genetic Optimization Toolbox 2 | % 3 | % Main interface 4 | % ga.m The Genetic Algorithm 5 | % initializega.m Initialization function for float and binary 6 | % representation Used by ga.m 7 | % initializeoga.m Initialization function for order-based 8 | % representation 9 | % 10 | % Operators used during simulated evolution 11 | % 12 | % Crossover Operators 13 | % 14 | % Float and Binary Representation 15 | % simpleXover.m Operator for the Algorithm Used by ga.m 16 | % 17 | % Float Representation 18 | % heuristicXover.m Operator for the Algorithm Used by ga.m 19 | % arithXover.m Operator for the Algorithm Used by ga.m 20 | % 21 | % Order-based Representation 22 | % cyclicXover.m Operator for the Algorithm Used by ga.m 23 | % erXover.m Operator for the Algorithm Used by ga.m 24 | % enhancederXover.m Operator for the Algorithm Used by ga.m 25 | % linerorderXover.m Operator for the Algorithm Used by ga.m 26 | % orderbasedXover.m Operator for the Algorithm Used by ga.m 27 | % partmapXover.m Operator for the Algorithm Used by ga.m 28 | % singleptXover.m Operator for the Algorithm Used by ga.m 29 | % uniformXover.m Operator for the Algorithm Used by ga.m 30 | % 31 | % Mutation Operators 32 | % 33 | % Binary Representation 34 | % binaryMutation.m Operator for the Algorithm Used by ga.m 35 | % 36 | % Float Representation 37 | % boundaryMutation.m Operator for the Algorithm Used by ga.m 38 | % multiNonUnifMutation.m Operator for the Algorithm Used by ga.m 39 | % nonUnifMutation.m Operator for the Algorithm Used by ga.m 40 | % unifMutation.m Operator for the Algorithm Used by ga.m 41 | % 42 | % Binary and Order-Based Representation 43 | % inversionMutation.m Operator for the Algorithm Used by ga.m 44 | % 45 | % Order-Based Representation 46 | % adjswapMutation.m Operator for the Algorithm Used by ga.m 47 | % shiftMutation.m Operator for the Algorithm Used by ga.m 48 | % swapMutation.m Operator for the Algorithm Used by ga.m 49 | % threeswapMutation.m Operator for the Algorithm Used by ga.m 50 | % 51 | % Selection Functions 52 | % normGeomSelect.m Selection function Used by ga.m 53 | % roulette.m Selection function Used by ga.m 54 | % tournSelect.m Selection function Used by ga.m 55 | % 56 | % Termination Functions 57 | % maxGenTerm.m Termination function Used by ga.m 58 | % optMaxGenTerm.m Termination function Used by ga.m 59 | % 60 | % Functions used for binary representation 61 | % calcbits.m Binary precision function used by ga.m 62 | % f2b.m Float to Binary conversion used by ga.m 63 | % b2f.m Binary to Float conversion used by ga.m 64 | % 65 | % Utility functions 66 | % parse.m Parse blank separated names used by ga.m 67 | % delta.m Used by nonUnifMutation.m and mult...m 68 | % 69 | % Demonstrations 70 | % gademo1.m Introductory demo of GAOT 71 | % gademo2.m Multi-dimensional demo of GAOT 72 | % gademo3.m Reference for GAOT 73 | % floatExample.m Example using float representation 74 | % floatGradExample.m Example exploring learning(Lamarckian and Baldwinian) 75 | % binaryExample.m Example using binary representation 76 | % orderBasedExample.m Example using order-based representation 77 | % 78 | % Functions used in Demonstrations 79 | % gademo1eval1.m Example eval function used by gademo1.m 80 | % coranaEval.m Calculate Corana functions used by gademo2.m 81 | % coranaMin.m Calculate negative of Corana used by gademo2.m 82 | % gaEval.m Calculation of Corana used for testing 83 | % gaMichEval.m Michalewicz 2-variable problem evaluation 84 | % gaZBGradEval.m Michalewicz Evaluation Used for Learning example 85 | % gaZBGrad.m Gradient used for SQP during learning 86 | % tspEval.m Function used in orderBasedExample 87 | 88 | % Binary and Real-Valued Simulation Evolution for Matlab 89 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 90 | % 91 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 92 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 93 | % Software, Submitted 1996. 94 | % 95 | % This program is free software; you can redistribute it and/or modify 96 | % it under the terms of the GNU General Public License as published by 97 | % the Free Software Foundation; either version 1, or (at your option) 98 | % any later version. 99 | % 100 | % This program is distributed in the hope that it will be useful, 101 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 102 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 103 | % GNU General Public License for more details. A copy of the GNU 104 | % General Public License can be obtained from the 105 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -------------------------------------------------------------------------------- /遗传算法优化/gaot/EER.m: -------------------------------------------------------------------------------- 1 | function [c1,c2]=er(p1,p2,bounds,genInfo,ops) 2 | sz=size(p1,2); 3 | %fprintf(1,'======EER======\n'); 4 | %fprintf(1,'%d ',p1(1:sz-1)); fprintf(1,'\n'); 5 | %fprintf(1,'%d ',p2(1:sz-1)); fprintf(1,'\n'); 6 | 7 | right=[2:sz-1 1]; 8 | left =[sz-1 1:(sz-2)]; 9 | p1i(p1(1:sz-1))=1:sz-1; %Generate index 10 | p2i(p2(1:sz-1))=1:sz-1; %Generate index 11 | 12 | adj=sort([-1:-1:-sz+1;p1(right(p1i));p1(left(p1i));p2(right(p2i));p2(left(p2i))])'; %' 13 | repeats=find(diff(adj(:,2:5)')'==0); 14 | adj(repeats+sz-1)=zeros(size(repeats)); %Zero repeat 15 | adj(repeats+2*(sz-1))=-1*adj(repeats+2*(sz-1)); %Leftover is negative 16 | adj=[adj sum(abs(sign(adj(:,2:5)))')']; 17 | 18 | curr_site = round(rand*(sz-1) + 0.5); %Pick random start site 19 | %curr_site=5; 20 | %curr_site=8; 21 | for site=1:(sz-2) 22 | c1(site)=curr_site; 23 | adj_cities=adj(curr_site,1+find(adj(curr_site,2:5))); %Cities adjacent 24 | i=find(adj_cities<0); 25 | adj_cities=abs(adj_cities); 26 | %Zero out this site in adj table 27 | [cai caj]=find(abs(adj(adj_cities,2:5))==curr_site); 28 | adj(abs(adj(adj_cities(cai),1))+(sz-1)*caj)=zeros(size(cai,1),1); 29 | adj(curr_site,1:6)=[0 0 0 0 0 0]; 30 | %Update nonzero count 31 | adj(adj_cities,6)=adj(adj_cities,6)-ones(size(cai,1),1); 32 | %Pick the destination city 33 | if(i==[]) %No negative city 34 | [v i]=min(adj(adj_cities,6)); 35 | if (v==[]) %No cities left ERROR 36 | i=find(adj(:,1)<0); adj_cities=abs(adj(i,1)); i=1; 37 | %adj_cities=abs(adj(i,1)); 38 | %i=1; 39 | end %No Cities left Error 40 | end %If no negative cities 41 | curr_site=abs(adj_cities(i(1))); 42 | end 43 | c1(sz-1:sz)=[curr_site p1(sz)]; %Tag on fittness 44 | c2=p1; %Create other child 45 | %fprintf(1,'%d ',c1(1:sz-1)); fprintf(1,'\n'); -------------------------------------------------------------------------------- /遗传算法优化/gaot/README: -------------------------------------------------------------------------------- 1 | This directory contains the Genetic Algorithm Optimization Toolbox for 2 | Matlab 5. 3 | 4 | To use this, if you are local to NCSU and have AFS access to this 5 | directory, simply extend the matlab path using the following command. 6 | You can also place this command in a file called startup.m. Everytime 7 | you start Matlab in the directory containing this file, the path will 8 | always be extended. 9 | 10 | >>path(path,'/afs/eos/service/ie/research/kay_res/GAToolBox/gaot'); 11 | 12 | Otherwise, install the .m files into a directory named gaot and extend 13 | the matlab path to that directory. The compressed tar archive and the 14 | zip file should automatically create the gaot directory for you. 15 | 16 | The companion paper describing this toolbox is included here as 17 | gaotv5.ps. The paper, the three demo files, gademo1.m gademo2.m 18 | gademo3.m, and four example scripts, binaryExample, floatExample, 19 | floatGradExample, and orderbasedExample, should be sufficient 20 | explanation of this toolbox. For any questions, comments, suggestions 21 | send mail to jjoine@eos.ncsu.edu. 22 | 23 | For a list of the files in the tool box get help on gaot. 24 | 25 | Thanks for trying the toolbox. 26 | 27 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/adjswapMutation.m: -------------------------------------------------------------------------------- 1 | function [child] = adjswapmutation(par,bounds,genInfo,Ops) 2 | % Adjswap mutation performs a swap of two adjacent 3 | % genes in a permutation 4 | % 5 | % function [newSol] = adjswapmutation(parent,bounds,Ops) 6 | % parent - the first parent ( [solution string function value] ) 7 | % bounds - the bounds matrix for the solution space 8 | % Ops - Options for binaryMutation [gen prob_of_mutation] 9 | 10 | % Binary and Real-Valued Simulation Evolution for Matlab 11 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 12 | % 13 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 14 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 15 | % Software, Submitted 1996. 16 | % 17 | % This program is free software; you can redistribute it and/or modify 18 | % it under the terms of the GNU General Public License as published by 19 | % the Free Software Foundation; either version 1, or (at your option) 20 | % any later version. 21 | % 22 | % This program is distributed in the hope that it will be useful, 23 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 24 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 25 | % GNU General Public License for more details. A copy of the GNU 26 | % General Public License can be obtained from the 27 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 28 | sz = size(par,2)-1; 29 | pos = round(rand*(sz-1) + 0.5); %Generate U(1,n-1) 30 | child = par; 31 | child(pos:pos+1)=[par(pos+1) par(pos)]; 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/arithXover.m: -------------------------------------------------------------------------------- 1 | function [c1,c2] = arithXover(p1,p2,bounds,Ops) 2 | % Arith crossover takes two parents P1,P2 and performs an interpolation 3 | % along the line formed by the two parents. 4 | % 5 | % function [c1,c2] = arithXover(p1,p2,bounds,Ops) 6 | % p1 - the first parent ( [solution string function value] ) 7 | % p2 - the second parent ( [solution string function value] ) 8 | % bounds - the bounds matrix for the solution space 9 | % Ops - Options matrix for arith crossover [gen #ArithXovers] 10 | 11 | % Binary and Real-Valued Simulation Evolution for Matlab 12 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 13 | % 14 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 15 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 16 | % Software, Submitted 1996. 17 | % 18 | % This program is free software; you can redistribute it and/or modify 19 | % it under the terms of the GNU General Public License as published by 20 | % the Free Software Foundation; either version 1, or (at your option) 21 | % any later version. 22 | % 23 | % This program is distributed in the hope that it will be useful, 24 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 25 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 26 | % GNU General Public License for more details. A copy of the GNU 27 | % General Public License can be obtained from the 28 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 29 | 30 | % Pick a random mix amount 31 | a = rand; 32 | 33 | % Create the children 34 | c1 = p1*a + p2*(1-a); 35 | c2 = p1*(1-a) + p2*a; 36 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/b2f.m: -------------------------------------------------------------------------------- 1 | function [fval] = b2f(bval,bounds,bits) 2 | % function [fval] = b2f(bval,bounds,bits) 3 | % 4 | % Return the float number corresponing to the binary representation of bval. 5 | % 6 | % fval - the float representation of the number 7 | % bval - the binary representation of the number 8 | % bounds - the bounds on the variables 9 | % bits - the number of bits to represent each variable 10 | 11 | % Binary and Real-Valued Simulation Evolution for Matlab 12 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 13 | % 14 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 15 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 16 | % Software, Submitted 1996. 17 | % 18 | % This program is free software; you can redistribute it and/or modify 19 | % it under the terms of the GNU General Public License as published by 20 | % the Free Software Foundation; either version 1, or (at your option) 21 | % any later version. 22 | % 23 | % This program is distributed in the hope that it will be useful, 24 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 25 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 26 | % GNU General Public License for more details. A copy of the GNU 27 | % General Public License can be obtained from the 28 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 29 | 30 | scale=(bounds(:,2)-bounds(:,1))'./(2.^bits-1); %The range of the variables 31 | numV=size(bounds,1); 32 | cs=[0 cumsum(bits)]; 33 | for i=1:numV 34 | a=bval((cs(i)+1):cs(i+1)); 35 | fval(i)=sum(2.^(size(a,2)-1:-1:0).*a)*scale(i)+bounds(i,1); 36 | end -------------------------------------------------------------------------------- /遗传算法优化/gaot/binaryExample.m: -------------------------------------------------------------------------------- 1 | echo on 2 | % This script shows how to use the ga using a float representation. 3 | % You should see the demos for 4 | % more information as well. gademo1, gademo2, gademo3 5 | global bounds 6 | 7 | % Setting the seed back to the beginning for comparison sake 8 | rand('seed',0) 9 | 10 | % Crossover Operators 11 | xFns = 'simpleXover'; 12 | xOpts = [.4]; 13 | 14 | % Mutation Operators 15 | mFns = 'binaryMutation'; 16 | 17 | mOpts = [0.005]; 18 | 19 | % Termination Operators 20 | termFns = 'maxGenTerm'; 21 | termOps = [200]; % 200 Generations 22 | 23 | % Selection Function 24 | selectFn = 'roulette' 25 | selectOps = []; 26 | 27 | % Evaluation Function 28 | evalFn = 'gaMichEval'; 29 | evalOps = []; 30 | 31 | type gaMichEval 32 | 33 | % Bounds on the variables 34 | bounds = [-3 12.1; 4.1 5.8]; 35 | 36 | % GA Options [epsilon float/binar display] 37 | gaOpts=[1e-6 0 1]; 38 | 39 | % Generate an intialize population of size 20 40 | startPop = initializega(20,bounds,'gaMichEval',[],[1e-6 0]); 41 | 42 | % Lets run the GA 43 | % Hit a return to continue 44 | pause 45 | 46 | [x endPop bestPop trace]=ga(bounds,evalFn,evalOps,startPop,gaOpts,... 47 | termFns,termOps,selectFn,selectOps,xFns,xOpts,mFns,mOpts); 48 | 49 | % x is the best solution found 50 | x 51 | % Hit a return to continue 52 | pause 53 | 54 | % endPop is the ending population 55 | endPop 56 | % Hit a return to continue 57 | pause 58 | 59 | % trace is a trace of the best value and average value of generations 60 | trace 61 | % Hit a return to continue 62 | pause 63 | 64 | % Plot the best over time 65 | clf 66 | plot(trace(:,1),trace(:,2)); 67 | % Hit a return to continue 68 | pause 69 | 70 | % Add the average to the graph 71 | hold on 72 | plot(trace(:,1),trace(:,3)); 73 | % Hit a return to continue 74 | pause 75 | 76 | % Lets increase the population size by running the defaults 77 | % 78 | rand('seed',0) 79 | termOps=[100]; 80 | [x endPop bestPop trace]=ga(bounds,evalFn,evalOps,[],gaOpts,termFns,termOps,... 81 | selectFn,selectOps); 82 | 83 | % x is the best solution found 84 | x 85 | % Hit a return to continue 86 | pause 87 | 88 | % endPop is the ending population 89 | endPop 90 | % Hit a return to continue 91 | pause 92 | 93 | % trace is a trace of the best value and average value of generations 94 | trace 95 | % Hit a return to continue 96 | pause 97 | 98 | % Plot the best over time 99 | clf 100 | plot(trace(:,1),trace(:,2)); 101 | % Hit a return to continue 102 | pause 103 | 104 | % Add the average to the graph 105 | hold on 106 | plot(trace(:,1),trace(:,3)); 107 | 108 | echo off -------------------------------------------------------------------------------- /遗传算法优化/gaot/binaryMutation.m: -------------------------------------------------------------------------------- 1 | function [parent] = binaryMutate(parent,bounds,Ops) 2 | % Binary mutation changes each of the bits of the parent 3 | % based on the probability of mutation 4 | % 5 | % function [newSol] = binaryMutate(parent,bounds,Ops) 6 | % parent - the first parent ( [solution string function value] ) 7 | % bounds - the bounds matrix for the solution space 8 | % Ops - Options for binaryMutation [gen prob_of_mutation] 9 | 10 | % Binary and Real-Valued Simulation Evolution for Matlab 11 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 12 | % 13 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 14 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 15 | % Software, Submitted 1996. 16 | % 17 | % This program is free software; you can redistribute it and/or modify 18 | % it under the terms of the GNU General Public License as published by 19 | % the Free Software Foundation; either version 1, or (at your option) 20 | % any later version. 21 | % 22 | % This program is distributed in the hope that it will be useful, 23 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 24 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 25 | % GNU General Public License for more details. A copy of the GNU 26 | % General Public License can be obtained from the 27 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 28 | 29 | pm=Ops(2); 30 | numVar = size(parent,2)-1; % Get the number of variables 31 | % Pick a variable to mutate randomly from 1-number of vars 32 | rN=rand(1,numVar)1) 33 | r=.99; 34 | % disp(sprintf('max gen %d < current gen %d setting ratio = 1',mt,ct)); 35 | end 36 | change = y*(rand*(1-r))^b; 37 | 38 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/dists.m: -------------------------------------------------------------------------------- 1 | function D = dists(X1,X2,p,e) 2 | %DISTS Calculates distances between vectors of points. 3 | % D = dists(X1,X2,p,e) 4 | % X1 = n x d matrix of n d-dimensional points 5 | % X2 = m x d matrix of m d-dimensional points 6 | % D = n x m matrix of distances 7 | % = (n-1) x 1 vector of distances between X1 points, if X2 = [] 8 | % p = 2, Euclidean (default): D(i,j) = sqrt(sum((X1(i,:) - X2(j,:))^2)) 9 | % = 1, rectilinear: D(i,j) = sum(abs(X1(i,:) - X2(j,:)) 10 | % = Inf, Chebychev dist: D(i,j) = max(abs(X1(i,:) - X2(j,:)) 11 | % = (1 Inf), lp norm: D(i,j) = sum(abs(X1(i,:) - X2(j,:))^p)^(1/p) 12 | % = 'rad', great circle distance in radians of a sphere 13 | % (where X1 and X2 are decimal degree latitudes and longitudes) 14 | % = 'mi' or 'sm', great circle distance in statute miles on the earth 15 | % = 'km', great circle distance in kilometers on the earth 16 | % e = epsilon for hyperboloid approximation gradient estimation 17 | % = 0 (default); no error checking if any non-empty 'e' input 18 | % ~= 0 => general lp used for rect., Cheb., and p outside [1,2] 19 | % 20 | % Great circle distances are calculated using the Haversine Formula (from R.W. 21 | % Sinnott, "Virtues of the Haversine", Sky and Telescope, vol. 68, no. 2, 1984 22 | % p. 159, as reported in "http://www.census.gov/cgi-bin/geo/gisfaq?Q5.1") 23 | 24 | % Copyright (c) 1998 by Michael G. Kay 25 | % Matlog Version 1.0 Apr-3-98 26 | 27 | % Input Error Checking ******************************************************* 28 | if nargin == 4 & ~isempty(e) % No error checking is 'e' input 29 | [n,d] = size(X1); 30 | m = size(X2,1); 31 | else % Do error checking 32 | error(nargchk(1,4,nargin)); 33 | e = 0; % 'e' default 34 | [n,d] = size(X1); 35 | if n == 0 | ~isreal(X1) 36 | error('X1 must be non-empty real matrix'); 37 | end 38 | if nargin < 2 | isempty(X2) % Calc intra-seq dist b/w X1 points 39 | m = 0; % X2 default 40 | if n < 2 41 | error('X1 must have more than 1 point'); 42 | end 43 | else % Calc dist b/w X1 and X2 points 44 | [m,dX2] = size(X2); 45 | if m == 0 | ~isreal(X2) 46 | error('X2 must be non-empty real matrix'); 47 | end 48 | if d ~= dX2 49 | error('Rows of X1 and X2 must have same dimensions'); 50 | end 51 | end 52 | if nargin < 3 | isempty(p) 53 | p = 2; % 'p' default 54 | elseif ~ischar(p) % lp distances 55 | if length(p(:)) ~= 1 | ~isreal(p) 56 | error('''p'' must be a real scalar number'); 57 | end 58 | elseif ischar(p) % Great circle distances 59 | p = lower(p); 60 | if d ~= 2 61 | error('Points must be 2-dimensional for great-circle distances'); 62 | end 63 | if ~any(strcmp(p,{'rad','mi','sm','km'})) 64 | error('''p'' must be either ''rad,'' ''mi,'' ''sm,'' or ''km'''); 65 | end 66 | else 67 | error('''p'' not valid value'); 68 | end 69 | end 70 | % End (Input Error Checking) *********************************************** 71 | 72 | % Interchange if X2 is the only 1 point 73 | intrchg = 0; 74 | if n > 1 & m == 1 75 | tmp = X2; X2 = X1; X1 = tmp; 76 | m = n;n = 1; 77 | intrchg = 1; 78 | end 79 | 80 | % 1-dimensional points 81 | if d == 1 82 | if e == 0 83 | if m ~= 0 84 | D = abs(X1(:,ones(1,m)) - X2(:,ones(1,n))'); 85 | else 86 | D = abs(X1(1:n-1) - X1(2:n))'; % X1 intra-seq. dist. 87 | end 88 | else 89 | if m ~= 0 90 | D = sqrt((X1(:,ones(1,m)) - X2(:,ones(1,n))').^2 + e); 91 | else 92 | D = sqrt((X1(1:n-1) - X1(2:n)).^2 + e)'; 93 | end 94 | end 95 | 96 | % X1 only 1 point or intra-seq dist 97 | elseif n == 1 | m == 0 98 | if n == 1 % Expand X1 to match X2 99 | X1 = X1(ones(1,m),:); 100 | n = m; 101 | else % X1 intra-seq. dist. 102 | X2 = X1(2:n,:); % X2 = ending points 103 | n = n - 1; 104 | X1 = X1(1:n,:); % X1 = beginning points 105 | end 106 | if p == 2 % Euclidean distance 107 | D = sqrt(sum(((X1 - X2).^2 + e)')); 108 | elseif ischar(p) % Great-circle distance 109 | X1 = pi*X1/180;X2 = pi*X2/180; 110 | D = 2*asin(min(1,sqrt(sin((X1(:,1) - X2(:,1))/2).^2 + ... 111 | cos(X1(:,1)).*cos(X2(:,1)).* ... 112 | sin((X1(:,2) - X2(:,2))/2).^2)))'; 113 | elseif p == 1 & e == 0 % Rectilinear distance 114 | D = sum(abs(X1 - X2)'); 115 | elseif (p >= 1 & p <= 2) | (e ~= 0 & p > 0) % General lp distance 116 | D = sum((((X1 - X2).^2 + e).^(p/2))').^(1/p); 117 | elseif p == Inf & e == 0 % Chebychev distance 118 | D = max(abs(X1 - X2)'); 119 | else % Otherwise 120 | D = zeros(1,n); 121 | for j = 1:n 122 | D(j) = norm(X1(j,:) - X2(j,:),p); 123 | end 124 | end 125 | 126 | % X1 and X2 are 2-dimensional points 127 | elseif d == 2 128 | if p == 2 % Euclidean distance 129 | D = sqrt((X1(:, ones(1,m)) - X2(:, ones(1,n))').^2 + e + ... 130 | (X1(:,2*ones(1,m)) - X2(:,2*ones(1,n))').^2 + e); 131 | elseif ischar(p) % Great-circle distance 132 | X1 = pi*X1/180;X2 = pi*X2/180; 133 | cosX1lat = cos(X1(:,1));cosX2lat = cos(X2(:,1)); 134 | D = 2*asin(min(1,sqrt(... 135 | sin((X1(:,ones(1,m)) - X2(:,ones(1,n))')/2).^2 + ... 136 | cosX1lat(:,ones(1,m),1).*cosX2lat(:,ones(1,n))'.* ... 137 | sin((X1(:,2*ones(1,m)) - X2(:,2*ones(1,n))')/2).^2))); 138 | elseif p == 1 & e == 0 % Rectilinear distance 139 | D = abs(X1(:,ones(1,m)) - X2(:,ones(1,n))') + ... 140 | abs(X1(:,2*ones(1,m)) - X2(:,2*ones(1,n))'); 141 | elseif (p >= 1 & p <= 2) | (e ~= 0 & p > 0) % General lp distance 142 | D = (((X1(:, ones(1,m)) - X2(:, ones(1,n))').^2 + e).^(p/2) + ... 143 | ((X1(:,2*ones(1,m)) - X2(:,2*ones(1,n))').^2 + e).^(p/2)).^(1/p); 144 | elseif p == Inf & e == 0 % Chebychev distance 145 | D = max(abs(X1(:,ones(1,m)) - X2(:,ones(1,n))'),... 146 | abs(X1(:,2*ones(1,m)) - X2(:,2*ones(1,n))')); 147 | else % Otherwise 148 | D = zeros(n,m); 149 | for i = 1:n 150 | for j = 1:m 151 | D(i,j) = norm(X1(i,:) - X2(j,:),p); 152 | end 153 | end 154 | end 155 | 156 | % X1 and X2 are 3 or more dim. point 157 | else 158 | if p == 2 % Euclidean distance 159 | D = sqrt(sum((repmat(reshape(X1,[n 1 k]),1,m) - ... 160 | repmat(reshape(X2,[1 m k]),n,1)).^2 + e,3)); 161 | elseif p == 1 & e == 0 % Rectilinear distance 162 | D = sum(abs(repmat(reshape(X1,[n 1 k]),1,m) - ... 163 | repmat(reshape(X2,[1 m k]),n,1)),3); 164 | elseif (p >= 1 & p <= 2) | (e ~= 0 & p > 0) % General lp distance 165 | D = sum(((repmat(reshape(X1,[n 1 k]),1,m) - ... 166 | repmat(reshape(X2,[1 m k]),n,1)).^2 + e).^(p/2),3).^(1/p); 167 | elseif p == Inf & e == 0 % Chebychev distance 168 | D = max(abs(repmat(reshape(X1,[n 1 k]),1,m) - ... 169 | repmat(reshape(X2,[1 m k]),n,1)),[],3); 170 | else % Otherwise 171 | D = zeros(n,m); 172 | for i = 1:n 173 | for j = 1:m 174 | D(i,j) = norm(X1(i,:) - X2(j,:),p); 175 | end 176 | end 177 | end 178 | end 179 | 180 | % Transpose D if X2 was interchanged or X1 intra-seq distances 181 | if intrchg == 1 | m == 0 182 | D = D.'; 183 | end 184 | 185 | % Convert 'rad' to 'km' or 'mi' (or 'sm') 186 | if ischar(p) & ~strcmp(p,'rad') 187 | if strcmp(p,'km') 188 | D = (6378.388 - 21.476*abs(sin(mean([X1(:,1);X2(:,1)]))))*D; 189 | else % 'mi' or 'sm' 190 | D = (3963.34 - 13.35*abs(sin(mean([X1(:,1);X2(:,1)]))))*D; 191 | end 192 | end 193 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/enhancederXover.m: -------------------------------------------------------------------------------- 1 | function [c1,c2]=enhancederXover(p1,p2,bounds,ops) 2 | % EnhancederXover crossover takes two parents P1,P2 and performs 3 | % enhanced edge recombination crossover on permutation strings. 4 | % 5 | % function [c1,c2] = enhancederXover(p1,p2,bounds,Ops) 6 | % p1 - the first parent ( [solution string function value] ) 7 | % p2 - the second parent ( [solution string function value] ) 8 | % bounds - the bounds matrix for the solution space 9 | % Ops - Options matrix for simple crossover [gen #SimpXovers]. 10 | 11 | % Binary and Real-Valued Simulation Evolution for Matlab 12 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 13 | % 14 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 15 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 16 | % Software, Submitted 1996. 17 | % 18 | % This program is free software; you can redistribute it and/or modify 19 | % it under the terms of the GNU General Public License as published by 20 | % the Free Software Foundation; either version 1, or (at your option) 21 | % any later version. 22 | % 23 | % This program is distributed in the hope that it will be useful, 24 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 25 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 26 | % GNU General Public License for more details. A copy of the GNU 27 | % General Public License can be obtained from the 28 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 29 | sz=size(p1,2); 30 | right=[2:sz 1]; 31 | left =[sz 1:(sz-1)]; 32 | p1i(p1)=1:10; %Generate index 33 | p2i(p2)=1:10; %Generate index 34 | adj=sort([-1:-1:-sz;p1(right(p1i));p1(left(p1i));p2(right(p2i));p2(left(p2i))])'; 35 | repeats=find(diff(adj(:,2:5)')'==0); 36 | adj(repeats+sz)=zeros(size(repeats)); %Zero repeat 37 | adj(repeats+2*sz)=-1*adj(repeats+2*sz); %Leftover is negative 38 | 39 | curr_site = round(rand*sz + 0.5); %Pick random start site 40 | for site=1:(sz-1) 41 | c1(site)=curr_site; 42 | inAdj=find(abs(adj(:,2:5))==curr_site); %Find this site in adjacency table 43 | adj(inAdj+sz)=zeros(size(inAdj)); %Take this out of the adjacency table 44 | %Find the element with fewest remaining links 45 | lz=colperm(adj'); 46 | lzi(lz)=1:size(lz,2); %create index 47 | adj_cities=adj(curr_site,1+(find(adj(curr_site,2:5)))); 48 | if(prod(sign(adj_cities))==-1) %One negative city 49 | i=find(adj_cities<0); 50 | else 51 | [v i]=min(lzi(abs(adj_cities))); 52 | end 53 | curr_site=abs(adj_cities(i)); 54 | end 55 | c1(sz)=curr_site; 56 | c2=p1; -------------------------------------------------------------------------------- /遗传算法优化/gaot/erXover.m: -------------------------------------------------------------------------------- 1 | function [c1,c2]=er(p1,p2,bounds,ops) 2 | % Er crossover takes two parents P1,P2 and performs edge recombination 3 | % crossover on permutation strings. 4 | % 5 | % function [c1,c2] = er(p1,p2,bounds,Ops) 6 | % p1 - the first parent ( [solution string function value] ) 7 | % p2 - the second parent ( [solution string function value] ) 8 | % bounds - the bounds matrix for the solution space 9 | % Ops - Options matrix for simple crossover [gen #SimpXovers]. 10 | 11 | % Binary and Real-Valued Simulation Evolution for Matlab 12 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 13 | % 14 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 15 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 16 | % Software, Submitted 1996. 17 | % 18 | % This program is free software; you can redistribute it and/or modify 19 | % it under the terms of the GNU General Public License as published by 20 | % the Free Software Foundation; either version 1, or (at your option) 21 | % any later version. 22 | % 23 | % This program is distributed in the hope that it will be useful, 24 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 25 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 26 | % GNU General Public License for more details. A copy of the GNU 27 | % General Public License can be obtained from the 28 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 29 | sz=size(p1,2)-1; 30 | right=[2:sz 1]; 31 | left =[sz 1:(sz-1)]; 32 | p1i(p1)=1:sz; %Generate index 33 | p2i(p2)=1:sz; %Generate index 34 | adj=sort([-1:-1:-sz;p1(right(p1i));p1(left(p1i));p2(right(p2i));p2(left(p2i))])'; 35 | repeats=find(diff(adj(:,2:5)')'==0); 36 | adj(repeats+sz)=zeros(size(repeats)); 37 | 38 | curr_site = round(rand*sz + 0.5); %Pick random start site 39 | for site=1:(sz-1) 40 | c1(site)=curr_site; 41 | inAdj=find(adj(:,2:5)==curr_site); %Find this site in adjacency table 42 | adj(inAdj+sz)=zeros(size(inAdj)); %Take this out of the adjacency table 43 | %Find the element with fewest remaining links 44 | lz=colperm(adj'); 45 | lzi(lz)=1:size(lz,2); %create index 46 | adj_cities=adj(curr_site,1+(find(adj(curr_site,2:5)))); 47 | [v i]=min(lzi(adj_cities)); 48 | curr_site=adj_cities(i); 49 | end 50 | c1(sz)=curr_site; 51 | c2=p1; -------------------------------------------------------------------------------- /遗传算法优化/gaot/f2b.m: -------------------------------------------------------------------------------- 1 | function [bval] = f2b(fval,bounds,bits) 2 | % function [bval] = f2b(fval,bounds,bits) 3 | % 4 | % Return the binary representation of the float number fval. 5 | % 6 | % fval - the float representation of the number 7 | % bval - the binary representation of the number 8 | % bounds - the bounds on the variables 9 | % bits - the number of bits to represent each variable 10 | 11 | % Binary and Real-Valued Simulation Evolution for Matlab 12 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 13 | % 14 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 15 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 16 | % Software, Submitted 1996. 17 | % 18 | % This program is free software; you can redistribute it and/or modify 19 | % it under the terms of the GNU General Public License as published by 20 | % the Free Software Foundation; either version 1, or (at your option) 21 | % any later version. 22 | % 23 | % This program is distributed in the hope that it will be useful, 24 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 25 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 26 | % GNU General Public License for more details. A copy of the GNU 27 | % General Public License can be obtained from the 28 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 29 | 30 | scale=(2.^bits-1)./ (bounds(:,2)-bounds(:,1))'; %The range of the variables 31 | numV=size(bounds,1); 32 | cs=[0 cumsum(bits)]; 33 | bval=[]; 34 | for i=1:numV 35 | fval(i)=(fval(i)-bounds(i,1)) * scale(i); 36 | bval=[bval rem(floor(fval(i)*pow2(1-bits(i):0)),2)]; 37 | end -------------------------------------------------------------------------------- /遗传算法优化/gaot/floatExample.m: -------------------------------------------------------------------------------- 1 | echo on 2 | % This script shows how to use the ga using a float representation. 3 | % You should see the demos for 4 | % more information as well. gademo1, gademo2, gademo3 5 | global bounds 6 | 7 | % Setting the seed to the same for binary 8 | rand('seed',156789) 9 | 10 | % Crossover Operators 11 | xFns = 'arithXover heuristicXover simpleXover'; 12 | xOpts = [1 0; 1 3; 1 0]; 13 | 14 | % Mutation Operators 15 | mFns = 'boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation'; 16 | 17 | mOpts = [2 0 0;3 200 3;2 200 3;2 0 0]; 18 | 19 | % Termination Operators 20 | termFns = 'maxGenTerm'; 21 | termOps = [200]; % 200 Generations 22 | 23 | % Selection Function 24 | selectFn = 'normGeomSelect'; 25 | selectOps = [0.08]; 26 | 27 | % Evaluation Function 28 | evalFn = 'gaMichEval'; 29 | evalOps = []; 30 | 31 | type gaMichEval 32 | 33 | % Bounds on the variables 34 | bounds = [-3 12.1; 4.1 5.8]; 35 | 36 | % GA Options [epsilon float/binar display] 37 | gaOpts=[1e-6 1 1]; 38 | 39 | % Generate an intialize population of size 20 40 | startPop = initializega(20,bounds,'gaMichEval',[1e-6 1]) 41 | 42 | % Lets run the GA 43 | % Hit a return to continue 44 | pause 45 | 46 | 47 | [x endPop bestPop trace]=ga(bounds,evalFn,evalOps,startPop,gaOpts,... 48 | termFns,termOps,selectFn,selectOps,xFns,xOpts,mFns,mOpts); 49 | 50 | 51 | % x is the best solution found 52 | x 53 | % Hit a return to continue 54 | pause 55 | 56 | 57 | % endPop is the ending population 58 | endPop 59 | % Hit a return to continue 60 | pause 61 | 62 | 63 | % bestPop is the best solution tracked over generations 64 | bestPop 65 | % Hit a return to continue 66 | pause 67 | 68 | 69 | % trace is a trace of the best value and average value of generations 70 | trace 71 | % Hit a return to continue 72 | pause 73 | 74 | 75 | % Plot the best over time 76 | clf 77 | plot(trace(:,1),trace(:,2)); 78 | % Hit a return to continue 79 | pause 80 | 81 | 82 | % Add the average to the graph 83 | hold on 84 | plot(trace(:,1),trace(:,3)); 85 | % Hit a return to continue 86 | pause 87 | 88 | 89 | % Lets increase the population size by running the defaults 90 | % 91 | 92 | [x endPop bestPop trace]=ga(bounds,evalFn,evalOps,[],gaOpts); 93 | 94 | % x is the best solution found 95 | x 96 | % Hit a return to continue 97 | pause 98 | 99 | 100 | % endPop is the ending population 101 | endPop 102 | % Hit a return to continue 103 | pause 104 | 105 | 106 | % bestPop is the best solution tracked over generations 107 | bestPop 108 | % Hit a return to continue 109 | pause 110 | 111 | 112 | % trace is a trace of the best value and average value of generations 113 | trace 114 | % Hit a return to continue 115 | pause 116 | 117 | 118 | % Plot the best over time 119 | clf 120 | plot(trace(:,1),trace(:,2)); 121 | % Hit a return to continue 122 | pause 123 | 124 | 125 | % Add the average to the graph 126 | hold on 127 | plot(trace(:,1),trace(:,3)); 128 | 129 | 130 | echo off -------------------------------------------------------------------------------- /遗传算法优化/gaot/floatGradExample.m: -------------------------------------------------------------------------------- 1 | echo off 2 | %load seed.mat 3 | rand('seed',0); 4 | echo on 5 | % This script shows how to use the ga. You should see the demos for 6 | % more information as well. gademo1, gademo2, gademo3 7 | global bounds 8 | 9 | % Crossover Operators 10 | xFns = 'arithXover heuristicXover simpleXover'; 11 | xOpts = [2 0; 2 3; 2 0]; 12 | 13 | % Mutation Operators 14 | mFns = 'boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation'; 15 | mOpts = [4 0 0;6 10 3;4 10 3;4 0 0]; 16 | 17 | % Termination Operators 18 | termFns = 'maxGenTerm'; 19 | termOps = [10]; 20 | 21 | % Selection Function 22 | selectFn = 'normGeomSelect'; 23 | selectOps = [0.06]; 24 | 25 | % Evaluation Function takes two options 26 | % prob to use gradient, prob to perform Lamarkian evolution 27 | evalFn = 'gaZBGradEval'; 28 | evalOps = [1.00 1.00]; 29 | 30 | % Bounds on the variables 31 | bounds = [-3 12.1; 4.1 5.8]; 32 | 33 | % GA Options [epsilon float/binar display] 34 | gaOpts=[1e-6 1 1]; 35 | 36 | % Generate an intialize population of size 80 37 | startPop = initializega(80,bounds,evalFn,evalOps,[1e-6 1]); 38 | evalOps = [1.00 0.00]; % 1 - Peform learning 0-Do not update 39 | 40 | % Lets run the GA using Baldwinian Evolution 41 | 42 | [x endPop bestPop trace]=ga(bounds,evalFn,evalOps,startPop,gaOpts,... 43 | termFns,termOps,selectFn,selectOps,xFns,xOpts,mFns,mOpts); 44 | 45 | % x is the best solution found 46 | x 47 | pause 48 | 49 | % endPop is the ending population 50 | endPop 51 | pause 52 | 53 | % bestPop is the best solution tracked over generations 54 | bestPop 55 | pause 56 | 57 | % trace is a trace of the best value and average value of generations 58 | trace 59 | pause 60 | 61 | % Plot the best over time 62 | clf 63 | plot(trace(:,1),trace(:,2)); 64 | pause 65 | 66 | % Add the average to the graph 67 | hold on 68 | plot(trace(:,1),trace(:,3)); 69 | pause 70 | 71 | % Lets run the GA using Lamarkian Evolution 72 | evalOps = [1.00 1.00]; 73 | 74 | [x endPop bestPop trace]=ga(bounds,evalFn,evalOps,startPop,gaOpts,... 75 | termFns,termOps,selectFn,selectOps,xFns,xOpts,mFns,mOpts); 76 | 77 | % x is the best solution found 78 | x 79 | pause 80 | 81 | % endPop is the ending population 82 | endPop 83 | pause 84 | 85 | % bestPop is the best solution tracked over generations 86 | bestPop 87 | pause 88 | 89 | % trace is a trace of the best value and average value of generations 90 | trace 91 | pause 92 | 93 | % Plot the best over time 94 | clf 95 | plot(trace(:,1),trace(:,2)); 96 | pause 97 | 98 | % Add the average to the graph 99 | hold on 100 | plot(trace(:,1),trace(:,3)); 101 | pause 102 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/ga.m: -------------------------------------------------------------------------------- 1 | function [x,endPop,bPop,traceInfo] = ga(bounds,evalFN,evalOps,startPop,opts,... 2 | termFN,termOps,selectFN,selectOps,xOverFNs,xOverOps,mutFNs,mutOps) 3 | % GA run a genetic algorithm 4 | % function [x,endPop,bPop,traceInfo]=ga(bounds,evalFN,evalOps,startPop,opts, 5 | % termFN,termOps,selectFN,selectOps, 6 | % xOverFNs,xOverOps,mutFNs,mutOps) 7 | % 8 | % Output Arguments: 9 | % x - the best solution found during the course of the run 10 | % endPop - the final population 11 | % bPop - a trace of the best population 12 | % traceInfo - a matrix of best and means of the ga for each generation 13 | % 14 | % Input Arguments: 15 | % bounds - a matrix of upper and lower bounds on the variables 16 | % evalFN - the name of the evaluation .m function 17 | % evalOps - options to pass to the evaluation function ([NULL]) 18 | % startPop - a matrix of solutions that can be initialized 19 | % from initialize.m 20 | % opts - [epsilon prob_ops display] change required to consider two 21 | % solutions different, prob_ops 0 if you want to apply the 22 | % genetic operators probabilisticly to each solution, 1 if 23 | % you are supplying a deterministic number of operator 24 | % applications and display is 1 to output progress 0 for 25 | % quiet. ([1e-6 1 0]) 26 | % termFN - name of the .m termination function (['maxGenTerm']) 27 | % termOps - options string to be passed to the termination function 28 | % ([100]). 29 | % selectFN - name of the .m selection function (['normGeomSelect']) 30 | % selectOpts - options string to be passed to select after 31 | % select(pop,#,opts) ([0.08]) 32 | % xOverFNS - a string containing blank seperated names of Xover.m 33 | % files (['arithXover heuristicXover simpleXover']) 34 | % xOverOps - A matrix of options to pass to Xover.m files with the 35 | % first column being the number of that xOver to perform 36 | % similiarly for mutation ([2 0;2 3;2 0]) 37 | % mutFNs - a string containing blank seperated names of mutation.m 38 | % files (['boundaryMutation multiNonUnifMutation ... 39 | % nonUnifMutation unifMutation']) 40 | % mutOps - A matrix of options to pass to Xover.m files with the 41 | % first column being the number of that xOver to perform 42 | % similiarly for mutation ([4 0 0;6 100 3;4 100 3;4 0 0]) 43 | 44 | % Binary and Real-Valued Simulation Evolution for Matlab 45 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 46 | % 47 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 48 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 49 | % Software, Submitted 1996. 50 | % 51 | % This program is free software; you can redistribute it and/or modify 52 | % it under the terms of the GNU General Public License as published by 53 | % the Free Software Foundation; either version 1, or (at your option) 54 | % any later version. 55 | % 56 | % This program is distributed in the hope that it will be useful, 57 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 58 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 59 | % GNU General Public License for more details. A copy of the GNU 60 | % General Public License can be obtained from the 61 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 62 | 63 | %%$Log: ga.m,v $ 64 | %Revision 1.10 1996/02/02 15:03:00 jjoine 65 | % Fixed the ordering of imput arguments in the comments to match 66 | % the actual order in the ga function. 67 | % 68 | %Revision 1.9 1995/08/28 20:01:07 chouck 69 | % Updated initialization parameters, updated mutation parameters to reflect 70 | % b being the third option to the nonuniform mutations 71 | % 72 | %Revision 1.8 1995/08/10 12:59:49 jjoine 73 | %Started Logfile to keep track of revisions 74 | % 75 | 76 | 77 | n=nargin; 78 | if n<2 | n==6 | n==10 | n==12 79 | disp('Insufficient arguements') 80 | end 81 | if n<3 %Default evalation opts. 82 | evalOps=[]; 83 | end 84 | if n<5 85 | opts = [1e-6 1 0]; 86 | end 87 | if isempty(opts) 88 | opts = [1e-6 1 0]; 89 | end 90 | 91 | if any(evalFN<48) %Not using a .m file 92 | if opts(2)==1 %Float ga 93 | e1str=['x=c1; c1(xZomeLength)=', evalFN ';']; 94 | e2str=['x=c2; c2(xZomeLength)=', evalFN ';']; 95 | else %Binary ga 96 | e1str=['x=b2f(endPop(j,:),bounds,bits); endPop(j,xZomeLength)=',... 97 | evalFN ';']; 98 | end 99 | else %Are using a .m file 100 | if opts(2)==1 %Float ga 101 | e1str=['[c1 c1(xZomeLength)]=' evalFN '(c1,[gen evalOps]);']; 102 | e2str=['[c2 c2(xZomeLength)]=' evalFN '(c2,[gen evalOps]);']; 103 | else %Binary ga 104 | e1str=['x=b2f(endPop(j,:),bounds,bits);[x v]=' evalFN ... 105 | '(x,[gen evalOps]); endPop(j,:)=[f2b(x,bounds,bits) v];']; 106 | end 107 | end 108 | 109 | 110 | if n<6 %Default termination information 111 | termOps=[100]; 112 | termFN='maxGenTerm'; 113 | end 114 | if n<12 %Default muatation information 115 | if opts(2)==1 %Float GA 116 | mutFNs=['boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation']; 117 | mutOps=[4 0 0;6 termOps(1) 3;4 termOps(1) 3;4 0 0]; 118 | else %Binary GA 119 | mutFNs=['binaryMutation']; 120 | mutOps=[0.05]; 121 | end 122 | end 123 | if n<10 %Default crossover information 124 | if opts(2)==1 %Float GA 125 | xOverFNs=['arithXover heuristicXover simpleXover']; 126 | xOverOps=[2 0;2 3;2 0]; 127 | else %Binary GA 128 | xOverFNs=['simpleXover']; 129 | xOverOps=[0.6]; 130 | end 131 | end 132 | if n<9 %Default select opts only i.e. roullete wheel. 133 | selectOps=[]; 134 | end 135 | if n<8 %Default select info 136 | selectFN=['normGeomSelect']; 137 | selectOps=[0.08]; 138 | end 139 | if n<6 %Default termination information 140 | termOps=[100]; 141 | termFN='maxGenTerm'; 142 | end 143 | if n<4 %No starting population passed given 144 | startPop=[]; 145 | end 146 | if isempty(startPop) %Generate a population at random 147 | %startPop=zeros(80,size(bounds,1)+1); 148 | startPop=initializega(80,bounds,evalFN,evalOps,opts(1:2)); 149 | end 150 | 151 | if opts(2)==0 %binary 152 | bits=calcbits(bounds,opts(1)); 153 | end 154 | 155 | xOverFNs=parse(xOverFNs); 156 | mutFNs=parse(mutFNs); 157 | 158 | xZomeLength = size(startPop,2); %Length of the xzome=numVars+fittness 159 | numVar = xZomeLength-1; %Number of variables 160 | popSize = size(startPop,1); %Number of individuals in the pop 161 | endPop = zeros(popSize,xZomeLength); %A secondary population matrix 162 | c1 = zeros(1,xZomeLength); %An individual 163 | c2 = zeros(1,xZomeLength); %An individual 164 | numXOvers = size(xOverFNs,1); %Number of Crossover operators 165 | numMuts = size(mutFNs,1); %Number of Mutation operators 166 | epsilon = opts(1); %Threshold for two fittness to differ 167 | oval = max(startPop(:,xZomeLength)); %Best value in start pop 168 | bFoundIn = 1; %Number of times best has changed 169 | done = 0; %Done with simulated evolution 170 | gen = 1; %Current Generation Number 171 | collectTrace = (nargout>3); %Should we collect info every gen 172 | floatGA = opts(2)==1; %Probabilistic application of ops 173 | display = opts(3); %Display progress 174 | 175 | while(~done) 176 | %Elitist Model 177 | [bval,bindx] = max(startPop(:,xZomeLength)); %Best of current pop 178 | best = startPop(bindx,:); 179 | 180 | if collectTrace 181 | traceInfo(gen,1)=gen; %current generation 182 | traceInfo(gen,2)=startPop(bindx,xZomeLength); %Best fittness 183 | traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %Avg fittness 184 | traceInfo(gen,4)=std(startPop(:,xZomeLength)); 185 | end 186 | 187 | if ( (abs(bval - oval)>epsilon) | (gen==1)) %If we have a new best sol 188 | if display 189 | fprintf(1,'\n%d %f\n',gen,bval); %Update the display 190 | end 191 | if floatGA 192 | bPop(bFoundIn,:)=[gen startPop(bindx,:)]; %Update bPop Matrix 193 | else 194 | bPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)... 195 | startPop(bindx,xZomeLength)]; 196 | end 197 | bFoundIn=bFoundIn+1; %Update number of changes 198 | oval=bval; %Update the best val 199 | else 200 | if display 201 | fprintf(1,'%d ',gen); %Otherwise just update num gen 202 | end 203 | end 204 | 205 | endPop = feval(selectFN,startPop,[gen selectOps]); %Select 206 | 207 | if floatGA %Running with the model where the parameters are numbers of ops 208 | for i=1:numXOvers, 209 | for j=1:xOverOps(i,1), 210 | a = round(rand*(popSize-1)+1); %Pick a parent 211 | b = round(rand*(popSize-1)+1); %Pick another parent 212 | xN=deblank(xOverFNs(i,:)); %Get the name of crossover function 213 | [c1 c2] = feval(xN,endPop(a,:),endPop(b,:),bounds,[gen xOverOps(i,:)]); 214 | 215 | if c1(1:numVar)==endPop(a,(1:numVar)) %Make sure we created a new 216 | c1(xZomeLength)=endPop(a,xZomeLength); %solution before evaluating 217 | elseif c1(1:numVar)==endPop(b,(1:numVar)) 218 | c1(xZomeLength)=endPop(b,xZomeLength); 219 | else 220 | %[c1(xZomeLength) c1] = feval(evalFN,c1,[gen evalOps]); 221 | eval(e1str); 222 | end 223 | if c2(1:numVar)==endPop(a,(1:numVar)) 224 | c2(xZomeLength)=endPop(a,xZomeLength); 225 | elseif c2(1:numVar)==endPop(b,(1:numVar)) 226 | c2(xZomeLength)=endPop(b,xZomeLength); 227 | else 228 | %[c2(xZomeLength) c2] = feval(evalFN,c2,[gen evalOps]); 229 | eval(e2str); 230 | end 231 | 232 | endPop(a,:)=c1; 233 | endPop(b,:)=c2; 234 | end 235 | end 236 | 237 | for i=1:numMuts, 238 | for j=1:mutOps(i,1), 239 | a = round(rand*(popSize-1)+1); 240 | c1 = feval(deblank(mutFNs(i,:)),endPop(a,:),bounds,[gen mutOps(i,:)]); 241 | if c1(1:numVar)==endPop(a,(1:numVar)) 242 | c1(xZomeLength)=endPop(a,xZomeLength); 243 | else 244 | %[c1(xZomeLength) c1] = feval(evalFN,c1,[gen evalOps]); 245 | eval(e1str); 246 | end 247 | endPop(a,:)=c1; 248 | end 249 | end 250 | 251 | else %We are running a probabilistic model of genetic operators 252 | for i=1:numXOvers, 253 | xN=deblank(xOverFNs(i,:)); %Get the name of crossover function 254 | cp=find(rand(popSize,1) p2(numVar+1)) 39 | bt = p1; 40 | wt = p2; 41 | else 42 | bt = p2; 43 | wt = p1; 44 | end 45 | while i= b1)) 53 | i = retry; 54 | good=1; 55 | else 56 | i = i + 1; 57 | end 58 | end 59 | 60 | % If new child is not feasible just return the new children 61 | if(~good) 62 | c1 = wt; 63 | end 64 | 65 | % Crossover functions return two children therefore return the best 66 | % and the new child created 67 | c2 = bt; 68 | 69 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/idprefs.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/遗传算法优化/gaot/idprefs.mat -------------------------------------------------------------------------------- /遗传算法优化/gaot/initializega.m: -------------------------------------------------------------------------------- 1 | function [pop] = initializega(num, bounds, evalFN,evalOps,options) 2 | % function [pop]=initializega(populationSize, variableBounds,evalFN, 3 | % evalOps,options) 4 | % initializega creates a matrix of random numbers with 5 | % a number of rows equal to the populationSize and a number 6 | % columns equal to the number of rows in bounds plus 1 for 7 | % the f(x) value which is found by applying the evalFN. 8 | % This is used by the ga to create the population if it 9 | % is not supplied. 10 | % 11 | % pop - the initial, evaluated, random population 12 | % populatoinSize - the size of the population, i.e. the number to create 13 | % variableBounds - a matrix which contains the bounds of each variable, i.e. 14 | % [var1_high var1_low; var2_high var2_low; ....] 15 | % evalFN - the evaluation fn, usually the name of the .m file for 16 | % evaluation 17 | % evalOps - any options to be passed to the eval function defaults [] 18 | % options - options to the initialize function, ie. 19 | % [type prec] where eps is the epsilon value 20 | % and the second option is 1 for float and 0 for binary, 21 | % prec is the precision of the variables defaults [1e-6 1] 22 | 23 | % Binary and Real-Valued Simulation Evolution for Matlab GAOT V2 24 | % Copyright (C) 1998 C.R. Houck, J.A. Joines, M.G. Kay 25 | % 26 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 27 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 28 | % Software, Submitted 1996. 29 | % 30 | % This program is free software; you can redistribute it and/or modify 31 | % it under the terms of the GNU General Public License as published by 32 | % the Free Software Foundation; either version 1, or (at your option) 33 | % any later version. 34 | % 35 | % This program is distributed in the hope that it will be useful, 36 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 37 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 38 | % GNU General Public License for more details. A copy of the GNU 39 | % General Public License can be obtained from the 40 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 41 | 42 | if nargin<5 43 | options=[1e-6 1]; 44 | end 45 | if nargin<4 46 | evalOps=[]; 47 | end 48 | 49 | if any(evalFN<48) %Not a .m file 50 | if options(2)==1 %Float GA 51 | estr=['x=pop(i,1); pop(i,xZomeLength)=', evalFN ';']; 52 | else %Binary GA 53 | estr=['x=b2f(pop(i,:),bounds,bits); pop(i,xZomeLength)=', evalFN ';']; 54 | end 55 | else %A .m file 56 | if options(2)==1 %Float GA 57 | estr=['[ pop(i,:) pop(i,xZomeLength)]=' evalFN '(pop(i,:),[0 evalOps]);']; 58 | else %Binary GA 59 | estr=['x=b2f(pop(i,:),bounds,bits);[x v]=' evalFN ... 60 | '(x,[0 evalOps]); pop(i,:)=[f2b(x,bounds,bits) v];']; 61 | end 62 | end 63 | 64 | 65 | numVars = size(bounds,1); %Number of variables 66 | rng = (bounds(:,2)-bounds(:,1))'; %The variable ranges' 67 | 68 | if options(2)==1 %Float GA 69 | xZomeLength = numVars+1; %Length of string is numVar + fit 70 | pop = zeros(num,xZomeLength); %Allocate the new population 71 | pop(:,1:numVars)=(ones(num,1)*rng).*(rand(num,numVars))+... 72 | (ones(num,1)*bounds(:,1)'); 73 | else %Binary GA 74 | bits=calcbits(bounds,options(1)); 75 | xZomeLength = sum(bits)+1; %Length of string is numVar + fit 76 | pop = round(rand(num,sum(bits)+1)); 77 | end 78 | 79 | for i=1:num 80 | eval(estr); 81 | end 82 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/initializeoga.m: -------------------------------------------------------------------------------- 1 | function [pop] = initializeoga(num,bounds,evalFN,evalOps,options) 2 | % initializeoga(populationSize, variableBounds,evalFN,evalOps,options) 3 | % initializeoga creates a matrix of random permutations with 4 | % a number of rows equal to the populationSize and a number 5 | % columns equal to the size of the permutation plus 1 for 6 | % the f(x) value which is found by applying the evalFN. 7 | % This initization function is used with an order-based 8 | % representation. 9 | % 10 | % pop - the initial, evaluated, random population 11 | % num - the size of the population, i.e. the number to create 12 | % bounds - the number of permutations in an individual (e.g., number 13 | % of cities in a tsp 14 | % evalFN - the evaluation fn, usually the name of the .m file for evaluation 15 | % evalOps- any options to be passed to the eval function defaults [] 16 | % options- options to the initialize function, ie. [eps float/binary prec] 17 | % where eps is the epsilon value and the second option is 1 for 18 | % orderOps, prec is the precision of the variables defaults [1e-6 1] 19 | 20 | if nargin<5 21 | options=[1e-6 1]; 22 | end 23 | if nargin<4 24 | evalOps=[]; 25 | end 26 | 27 | if any(evalFN<48) %Not a .m file 28 | estr=['x=pop(i,:); pop(i,xZomeLength)=', evalFN ';']; 29 | else %A .m file 30 | estr=['[pop(i,:) pop(i,xZomeLength)]=' evalFN '(pop(i,:),[0 evalOps]);']; 31 | end 32 | 33 | 34 | numVars = bounds; %Number of variables 35 | 36 | xZomeLength = numVars+1; %Length of string is numVar + fit 37 | pop = zeros(num,xZomeLength); %Allocate the new population 38 | for i=1:num 39 | pop(i,:)=[randperm(numVars) 0]; 40 | eval(estr); 41 | end 42 | 43 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/inversionMutation.m: -------------------------------------------------------------------------------- 1 | function [child] = inversionMutation(par,bounds,genInfo,Ops) 2 | % Inversion mutation inverts the bits or permutation between two 3 | % cut points. 4 | % 5 | % function [newSol] = inversionMutation(parent,bounds,Ops) 6 | % parent - the first parent ( [solution string function value] ) 7 | % bounds - the bounds matrix for the solution space 8 | % Ops - Options for binaryMutation [gen prob_of_mutation] 9 | 10 | % Binary and Real-Valued Simulation Evolution for Matlab 11 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 12 | % 13 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 14 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 15 | % Software, Submitted 1996. 16 | % 17 | % This program is free software; you can redistribute it and/or modify 18 | % it under the terms of the GNU General Public License as published by 19 | % the Free Software Foundation; either version 1, or (at your option) 20 | % any later version. 21 | % 22 | % This program is distributed in the hope that it will be useful, 23 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 24 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 25 | % GNU General Public License for more details. A copy of the GNU 26 | % General Public License can be obtained from the 27 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 28 | 29 | sz = size(par,2)-1; 30 | pos1 = round(rand*sz + 0.5); 31 | pos2 = round(rand*sz + 0.5); 32 | if pos1 ~= pos2 33 | if pos1 > pos2 34 | t = pos1; pos1 = pos2; pos2 = t; 35 | end 36 | child = [par(1:pos1-1) fliplr(par(pos1:pos2)) par(pos2+1:(sz+1))]; 37 | else 38 | child = par; 39 | end 40 | 41 | 42 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/linerorderXover.m: -------------------------------------------------------------------------------- 1 | function [c1,c2]=lox(p1,p2,bounds,genInfo,ops) 2 | % Linearorder crossover takes two parents P1,P2 and performs linear order 3 | % crossover for permutation strings. 4 | % 5 | % function [c1,c2] = linearOrderXover(p1,p2,bounds,Ops) 6 | % p1 - the first parent ( [solution string function value] ) 7 | % p2 - the second parent ( [solution string function value] ) 8 | % bounds - the bounds matrix for the solution space 9 | % Ops - Options matrix for simple crossover [gen #SimpXovers]. 10 | 11 | % Binary and Real-Valued Simulation Evolution for Matlab 12 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 13 | % 14 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 15 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 16 | % Software, Submitted 1996. 17 | % 18 | % This program is free software; you can redistribute it and/or modify 19 | % it under the terms of the GNU General Public License as published by 20 | % the Free Software Foundation; either version 1, or (at your option) 21 | % any later version. 22 | % 23 | % This program is distributed in the hope that it will be useful, 24 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 25 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 26 | % GNU General Public License for more details. A copy of the GNU 27 | % General Public License can be obtained from the 28 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 29 | sz=size(p1,2)-1; 30 | c1=p1(1:sz);%zeros(1,sz); 31 | c2=p2(1:sz);%zeros(1,sz); 32 | cut1=round(rand*(sz-1)+1.5); 33 | cut2=round(rand*(sz-1)+1.5); 34 | while cut2 == cut1 35 | cut2 = round(rand*sz + 0.5); 36 | end 37 | if cut1 > cut2 38 | t = cut1; cut1 = cut2; cut2 = t; 39 | end 40 | for i=cut1:cut2 41 | c1=strrep(c1,p2(i),-1); 42 | c2=strrep(c2,p1(i),-1); 43 | end 44 | g1=find(c1>-1); 45 | g2=find(c2>-1); 46 | c1=[c1(g1(1:(cut1-1))) p2(cut1:cut2) c1(g1(cut1:end)) p1(end)]; 47 | c2=[c2(g2(1:(cut1-1))) p1(cut1:cut2) c2(g2(cut1:end)) p2(end)]; 48 | 49 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/maxGenTerm.m: -------------------------------------------------------------------------------- 1 | function [done] = maxGenTerm(ops,bPop,endPop) 2 | % function [done] = maxGenTerm(ops,bPop,endPop) 3 | % 4 | % Returns 1, i.e. terminates the GA when the maximal_generation is reached. 5 | % 6 | % ops - a vector of options [current_gen maximum_generation] 7 | % bPop - a matrix of best solutions [generation_found solution_string] 8 | % endPop - the current generation of solutions 9 | 10 | % Binary and Real-Valued Simulation Evolution for Matlab 11 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 12 | % 13 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 14 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 15 | % Software, Submitted 1996. 16 | % 17 | % This program is free software; you can redistribute it and/or modify 18 | % it under the terms of the GNU General Public License as published by 19 | % the Free Software Foundation; either version 1, or (at your option) 20 | % any later version. 21 | % 22 | % This program is distributed in the hope that it will be useful, 23 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 24 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 25 | % GNU General Public License for more details. A copy of the GNU 26 | % General Public License can be obtained from the 27 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 28 | 29 | currentGen = ops(1); 30 | maxGen = ops(2); 31 | done = currentGen >= maxGen; -------------------------------------------------------------------------------- /遗传算法优化/gaot/multiNonUnifMutation.m: -------------------------------------------------------------------------------- 1 | function [parent] = multiNonUnifMutation(parent,bounds,Ops) 2 | % Multi-Non uniform mutation changes all of the parameters of the parent 3 | % based on a non-uniform probability distribution. This Gaussian 4 | % distribution starts wide, and narrows to a point distribution as the 5 | % current generation approaches the maximum generation. 6 | % 7 | % function [newSol] = multiNonUnifMutate(parent,bounds,Ops) 8 | % parent - the first parent ( [solution string function value] ) 9 | % bounds - the bounds matrix for the solution space 10 | % Ops - Options for multiNonUnifMutation 11 | % [gen #MultiNonUnifMutations maxGen b] 12 | 13 | % Binary and Real-Valued Simulation Evolution for Matlab 14 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 15 | % 16 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 17 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 18 | % Software, Submitted 1996. 19 | % 20 | % This program is free software; you can redistribute it and/or modify 21 | % it under the terms of the GNU General Public License as published by 22 | % the Free Software Foundation; either version 1, or (at your option) 23 | % any later version. 24 | % 25 | % This program is distributed in the hope that it will be useful, 26 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 27 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 28 | % GNU General Public License for more details. A copy of the GNU 29 | % General Public License can be obtained from the 30 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 31 | 32 | cg=Ops(1); % Current Generation 33 | mg=Ops(3); % Maximum Number of Generations 34 | b=Ops(4); % Shape parameter 35 | df = bounds(:,2) - bounds(:,1); % Range of the variables 36 | numVar = size(parent,2)-1; % Get the number of variables 37 | % Now mutate that point 38 | md = round(rand(1,numVar)); 39 | for i = 1:numVar 40 | if md(i) 41 | parent(i)=parent(i)+delta(cg,mg,bounds(i,2)-parent(i),b); 42 | else 43 | parent(i)=parent(i)-delta(cg,mg,parent(i)-bounds(i,1),b); 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/nonUnifMutation.m: -------------------------------------------------------------------------------- 1 | function [parent] = nonUnifMutate(parent,bounds,Ops) 2 | % Non uniform mutation changes one of the parameters of the parent 3 | % based on a non-uniform probability distribution. This Gaussian 4 | % distribution starts wide, and narrows to a point distribution as the 5 | % current generation approaches the maximum generation. 6 | % 7 | % function [newSol] = multiNonUnifMutate(parent,bounds,Ops) 8 | % parent - the first parent ( [solution string function value] ) 9 | % bounds - the bounds matrix for the solution space 10 | % Ops - Options for nonUnifMutate[gen #NonUnifMutations maxGen b] 11 | 12 | % Binary and Real-Valued Simulation Evolution for Matlab 13 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 14 | % 15 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 16 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 17 | % Software, Submitted 1996. 18 | % 19 | % This program is free software; you can redistribute it and/or modify 20 | % it under the terms of the GNU General Public License as published by 21 | % the Free Software Foundation; either version 1, or (at your option) 22 | % any later version. 23 | % 24 | % This program is distributed in the hope that it will be useful, 25 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 26 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 27 | % GNU General Public License for more details. A copy of the GNU 28 | % General Public License can be obtained from the 29 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 30 | 31 | cg=Ops(1); % Current Generation 32 | mg=Ops(3); % Maximum Number of Generations 33 | b=Ops(4); % Shape parameter 34 | df = bounds(:,2) - bounds(:,1); % Range of the variables 35 | numVar = size(parent,2)-1; % Get the number of variables 36 | % Pick a variable to mutate randomly from 1 to number of vars 37 | mPoint = round(rand * (numVar-1)) + 1; 38 | md = round(rand); % Choose a direction of mutation 39 | if md % Mutate towards upper bound 40 | newValue=parent(mPoint)+delta(cg,mg,bounds(mPoint,2)-parent(mPoint),b); 41 | else % Mutate towards lower bound 42 | newValue=parent(mPoint)-delta(cg,mg,parent(mPoint)-bounds(mPoint,1),b); 43 | end 44 | parent(mPoint) = newValue; % Make the child 45 | 46 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/normGeomSelect.m: -------------------------------------------------------------------------------- 1 | function[newPop] = normGeomSelect(oldPop,options) 2 | % NormGeomSelect is a ranking selection function based on the normalized 3 | % geometric distribution. 4 | % 5 | % function[newPop] = normGeomSelect(oldPop,options) 6 | % newPop - the new population selected from the oldPop 7 | % oldPop - the current population 8 | % options - options to normGeomSelect [gen probability_of_selecting_best] 9 | 10 | % Binary and Real-Valued Simulation Evolution for Matlab 11 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 12 | % 13 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 14 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 15 | % Software, Submitted 1996. 16 | % 17 | % This program is free software; you can redistribute it and/or modify 18 | % it under the terms of the GNU General Public License as published by 19 | % the Free Software Foundation; either version 1, or (at your option) 20 | % any later version. 21 | % 22 | % This program is distributed in the hope that it will be useful, 23 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 24 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 25 | % GNU General Public License for more details. A copy of the GNU 26 | % General Public License can be obtained from the 27 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 28 | 29 | q=options(2); % Probability of selecting the best 30 | e = size(oldPop,2); % Length of xZome, i.e. numvars+fit 31 | n = size(oldPop,1); % Number of individuals in pop 32 | newPop = zeros(n,e); % Allocate space for return pop 33 | fit = zeros(n,1); % Allocates space for prob of select 34 | x=zeros(n,2); % Sorted list of rank and id 35 | x(:,1) =[n:-1:1]'; % To know what element it was 36 | [y x(:,2)] = sort(oldPop(:,e)); % Get the index after a sort 37 | r = q/(1-(1-q)^n); % Normalize the distribution, q prime 38 | fit(x(:,2))=r*(1-q).^(x(:,1)-1); % Generates Prob of selection 39 | fit = cumsum(fit); % Calculate the cumulative prob. func 40 | rNums=sort(rand(n,1)); % Generate n sorted random numbers 41 | fitIn=1; newIn=1; % Initialize loop control 42 | while newIn<=n % Get n new individuals 43 | if(rNums(newIn)= maxGen) | ((optimal - bestSolVal) <= epsilon); -------------------------------------------------------------------------------- /遗传算法优化/gaot/orderBasedExample.m: -------------------------------------------------------------------------------- 1 | echo on 2 | % This script shows how to use the ga using an order-based representation. 3 | % You should see the demos for 4 | % more information as well. gademo1, gademo2, gademo3 5 | global distMatrix 6 | % Setting the seed to the same for binary 7 | rand('seed',156789) 8 | 9 | % 6 city problem 10 | t=[ 92.6112 59.0801; 49.1155 50.0000; 12.5000 57.9436; 75.0000 19.3703; 11 | 8.6504 13.7113; 36.8786 92.9628]; 12 | t=100*rand(15,2); 13 | sz=size(t,1); 14 | distMatrix=dists(t,t); 15 | 16 | 17 | % Order-based Representation Crossover Operators 18 | % cyclicXover.m 19 | % erXover.m 20 | % enhancederXover.m 21 | % linerorderXover.m 22 | % orderbasedXover.m 23 | % partmapXover.m 24 | % singleptXover.m 25 | % uniformXover.m 26 | 27 | xFns = 'cyclicXover uniformXover partmapXover orderbasedXover ' 28 | xFns =[xFns,'singleptXover linerorderXover']; 29 | % xFns = [xFns,'enhancederXover linerorderXover'] 30 | % xFns = [xFns,'linerorderXover singleptXover'] 31 | xOpts = [2;2;2;2;2;2];% 2; 2; 2; 2; 2; 2; 2]; 32 | 33 | % Order-based Mutation Operators 34 | % inversionMutation 35 | % adjswapMutation.m 36 | % shiftMutation.m 37 | % swapMutation.m 38 | % threeswapMutation.m 39 | 40 | mFns = 'inversionMutation adjswapMutation shiftMutation swapMutation threeswapMutation'; 41 | mOpts = [2;2;2;2;2]; 42 | 43 | % Termination Operators 44 | termFns = 'maxGenTerm'; 45 | termOps = [100]; % 200 Generations 46 | 47 | % Selection Function 48 | selectFn = 'normGeomSelect'; 49 | selectOps = [0.08]; 50 | 51 | % Evaluation Function 52 | evalFn = 'tspEval'; 53 | evalOps = []; 54 | 55 | type tspEval 56 | 57 | % Bounds on the number of cities in the TSP 58 | bounds = [sz]; 59 | 60 | % GA Options [epsilon float/binar display] 61 | gaOpts=[1e-6 1 1]; 62 | 63 | % Generate an intialize population of size 20 64 | startPop = initializeoga(80,bounds,'tspEval',[1e-6 1]); 65 | 66 | % Lets run the GA 67 | %Hit a return to continue 68 | pause 69 | [x endPop bestPop trace]=ga(bounds,evalFn,evalOps,startPop,gaOpts,... 70 | termFns,termOps,selectFn,selectOps,xFns,xOpts,mFns,mOpts); 71 | 72 | % x is the best solution found 73 | x 74 | %Hit a return to continue 75 | pause 76 | 77 | % endPop is the ending population 78 | %endPop 79 | %%Hit a return to continue 80 | %pause 81 | 82 | % bestPop is the best solution tracked over generations 83 | bestPop 84 | %Hit a return to continue 85 | pause 86 | 87 | % trace is a trace of the best value and average value of generations 88 | trace 89 | 90 | %Hit a return to continue 91 | pause 92 | 93 | % Plot the best over time 94 | clf 95 | plot(trace(:,1),trace(:,2)); 96 | %Hit a return to continue 97 | pause 98 | 99 | % Add the average to the graph 100 | hold on 101 | plot(trace(:,1),trace(:,3)); 102 | %Hit a return to continue 103 | pause 104 | 105 | figure(2) 106 | clf 107 | A=ones(sz,sz); 108 | A= xor(triu(A),tril(A)); 109 | [xg yg]=gplot(A,t); 110 | clf 111 | plot(xg,yg,'b:','MarkerSize',24); 112 | h=gca; 113 | hold on 114 | ap=x; 115 | plot(t(x(1:sz),1),t(x(1:(sz)),2),'r-') 116 | plot(t([x(1),x(sz)],1),t([x(1),x(sz)],2),'r-') 117 | plot(xg,yg,'b.','MarkerSize',24); 118 | 119 | j=1; 120 | for i=1:sz 121 | str=sprintf('C-%d',j); 122 | if t(i,1)<50 123 | j=j+1; 124 | text(t(i,1)-7,t(i,2),str); 125 | else 126 | j=j+1; 127 | text(t(i,1)+2,t(i,2),str); 128 | end 129 | end 130 | legend('Path','Best Found Path') 131 | echo off 132 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/orderbasedXover.m: -------------------------------------------------------------------------------- 1 | function [c1,c2]= oox(p1,p2,bounds,Ops) 2 | % Orderbased crossover takes two parents P1,P2 and performs order 3 | % based crossover by Davis. 4 | % 5 | % function [c1,c2] = orderbasedXover(p1,p2,bounds,Ops) 6 | % p1 - the first parent ( [solution string function value] ) 7 | % p2 - the second parent ( [solution string function value] ) 8 | % bounds - the bounds matrix for the solution space 9 | % Ops - Options matrix for simple crossover [gen #SimpXovers]. 10 | 11 | % Binary and Real-Valued Simulation Evolution for Matlab 12 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 13 | % 14 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 15 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 16 | % Software, Submitted 1996. 17 | % 18 | % This program is free software; you can redistribute it and/or modify 19 | % it under the terms of the GNU General Public License as published by 20 | % the Free Software Foundation; either version 1, or (at your option) 21 | % any later version. 22 | % 23 | % This program is distributed in the hope that it will be useful, 24 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 25 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 26 | % GNU General Public License for more details. A copy of the GNU 27 | % General Public License can be obtained from the 28 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 29 | sz=size(p1,2)-1; 30 | n=floor(sz/2); 31 | cut1 = round(rand*(n-1)+0.5); %Generate random cut point U(1,n/2); 32 | cut2 = round(rand*(sz-cut1-1)+1+cut1); %Generate random cut point U(cut1+1,n-1); 33 | pm1=p1(1:end-1); 34 | pm2=p2(1:end-1); 35 | c1=p1; 36 | c2=p2; 37 | for i=[1:cut1 (cut2+1):sz] 38 | pm1=strrep(pm1,p2(i),-1); 39 | pm2=strrep(pm2,p1(i),-1); 40 | end 41 | c1((cut1+1):cut2)=p2(find(pm2>0)); 42 | c2((cut1+1):cut2)=p1(find(pm1>0)); 43 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/parse.m: -------------------------------------------------------------------------------- 1 | function [x] = parse(inStr) 2 | % parse is a function which takes in a string vector of blank separated text 3 | % and parses out the individual string items into a n item matrix, one row 4 | % for each string. 5 | % 6 | % function [x] = parse(inStr) 7 | % x - the return matrix of strings 8 | % inStr - the blank separated string vector 9 | 10 | % Binary and Real-Valued Simulation Evolution for Matlab 11 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 12 | % 13 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 14 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 15 | % Software, Submitted 1996. 16 | % 17 | % This program is free software; you can redistribute it and/or modify 18 | % it under the terms of the GNU General Public License as published by 19 | % the Free Software Foundation; either version 1, or (at your option) 20 | % any later version. 21 | % 22 | % This program is distributed in the hope that it will be useful, 23 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 24 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 25 | % GNU General Public License for more details. A copy of the GNU 26 | % General Public License can be obtained from the 27 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 28 | 29 | sz=size(inStr); 30 | strLen=sz(2); 31 | x=blanks(strLen); 32 | wordCount=1; 33 | last=0; 34 | for i=1:strLen, 35 | if inStr(i) == ' ' 36 | wordCount = wordCount + 1; 37 | x(wordCount,:)=blanks(strLen); 38 | last=i; 39 | else 40 | x(wordCount,i-last)=inStr(i); 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/partmapXover.m: -------------------------------------------------------------------------------- 1 | function [ch1,ch2] = partmapXover(par1,par2,bounds,Ops) 2 | % Partmap crossover takes two parents P1,P2 and performs a partially 3 | % mapped crossover. 4 | % 5 | % function [c1,c2] = partmapXover(p1,p2,bounds,Ops) 6 | % p1 - the first parent ( [solution string function value] ) 7 | % p2 - the second parent ( [solution string function value] ) 8 | % bounds - the bounds matrix for the solution space 9 | % Ops - Options matrix for simple crossover [gen #SimpXovers]. 10 | 11 | % Binary and Real-Valued Simulation Evolution for Matlab 12 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 13 | % 14 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 15 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 16 | % Software, Submitted 1996. 17 | % 18 | % This program is free software; you can redistribute it and/or modify 19 | % it under the terms of the GNU General Public License as published by 20 | % the Free Software Foundation; either version 1, or (at your option) 21 | % any later version. 22 | % 23 | % This program is distributed in the hope that it will be useful, 24 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 25 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 26 | % GNU General Public License for more details. A copy of the GNU 27 | % General Public License can be obtained from the 28 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 29 | sz = size(par1,2)-1; 30 | pos1 = round(rand*sz + 0.5); 31 | pos2 = round(rand*sz + 0.5); 32 | while pos2 == pos1 33 | pos2 = round(rand*sz + 0.5); 34 | end 35 | if pos1 > pos2 36 | t = pos1; pos1 = pos2; pos2 = t; 37 | end 38 | ss1 = par1(pos1:pos2); ss2 = par2(pos1:pos2); 39 | ch1 = par2; ch2 = par1; 40 | for i = [1:pos1-1 pos2+1:sz] 41 | ch1(i) = par1(i); 42 | j = find(ch1(i) == ss2); 43 | while ~isempty(j) 44 | ch1(i) = ss1(j); 45 | j = find(ch1(i) == ss2); 46 | end 47 | ch2(i) = par2(i); 48 | j = find(ch2(i) == ss1); 49 | while ~isempty(j) 50 | ch2(i) = ss2(j); 51 | j = find(ch2(i) == ss1); 52 | end 53 | end 54 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/plotCorana.m: -------------------------------------------------------------------------------- 1 | function [z, a] = coranaEval(per) 2 | i=0; 3 | a=-0.9:per:0.9; 4 | sz=size(a,2); 5 | z=zeros(sz,sz); 6 | for x=a 7 | i=i+1; j=0; 8 | for y=a 9 | j=j+1; 10 | z(i,j)=coranaFeval([x y]); 11 | end 12 | end 13 | %Done! 14 | 15 | %First let's look at it in each dimension independently 16 | clg 17 | plot(z(:,1)) %Plot a slice of the function in x max 250.25 18 | %Notice the range is [250.0-250.25] 19 | pause %Strike any key to continue 20 | clg 21 | plot(z(1,:)) %Plot a slice of the function in y 22 | %Notice the range is [0-250] 23 | pause %Strike any key to continue 24 | mesh(a,a,z); 25 | view(30,60); 26 | grid; 27 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/roulette.m: -------------------------------------------------------------------------------- 1 | function[newPop] = roulette(oldPop,options) 2 | %roulette is the traditional selection function with the probability of 3 | %surviving equal to the fittness of i / sum of the fittness of all individuals 4 | % 5 | %function[newPop] = roulette(oldPop,options) 6 | %newPop - the new population selected from the oldPop 7 | %oldPop - the current population 8 | %options - options [gen] 9 | 10 | %Get the parameters of the population 11 | numVars = size(oldPop,2); 12 | numSols = size(oldPop,1); 13 | 14 | %Generate the relative probabilites of selection 15 | totalFit = sum(oldPop(:,numVars)); 16 | prob=oldPop(:,numVars) / totalFit; 17 | prob=cumsum(prob); 18 | 19 | rNums=sort(rand(numSols,1)); %Generate random numbers 20 | 21 | %Select individuals from the oldPop to the new 22 | fitIn=1;newIn=1; 23 | while newIn<=numSols 24 | if(rNums(newIn) cpos 33 | child = [par(1:cpos-1) par(ppos) par(cpos:ppos-1) par(ppos+1:sz) par(sz+1)]; 34 | else 35 | child = [par(1:ppos-1) par(ppos+1:cpos) par(ppos) par(cpos+1:sz) par(sz+1)]; 36 | end 37 | else 38 | child = par; 39 | end 40 | 41 | 42 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/simpleXover.m: -------------------------------------------------------------------------------- 1 | function [c1,c2] = simpleXover(p1,p2,bounds,Ops) 2 | % Simple crossover takes two parents P1,P2 and performs simple single point 3 | % crossover. 4 | % 5 | % function [c1,c2] = simpleXover(p1,p2,bounds,Ops) 6 | % p1 - the first parent ( [solution string function value] ) 7 | % p2 - the second parent ( [solution string function value] ) 8 | % bounds - the bounds matrix for the solution space 9 | % Ops - Options matrix for simple crossover [gen #SimpXovers]. 10 | 11 | % Binary and Real-Valued Simulation Evolution for Matlab 12 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 13 | % 14 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 15 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 16 | % Software, Submitted 1996. 17 | % 18 | % This program is free software; you can redistribute it and/or modify 19 | % it under the terms of the GNU General Public License as published by 20 | % the Free Software Foundation; either version 1, or (at your option) 21 | % any later version. 22 | % 23 | % This program is distributed in the hope that it will be useful, 24 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 25 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 26 | % GNU General Public License for more details. A copy of the GNU 27 | % General Public License can be obtained from the 28 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 29 | 30 | numVar = size(p1,2)-1; % Get the number of variables 31 | % Pick a cut point randomly from 1-number of vars 32 | cPoint = round(rand * (numVar-2)) + 1; 33 | 34 | c1 = [p1(1:cPoint) p2(cPoint+1:numVar+1)]; % Create the children 35 | c2 = [p2(1:cPoint) p1(cPoint+1:numVar+1)]; 36 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/singleptXover.m: -------------------------------------------------------------------------------- 1 | function [c1,c2]= singlePtX(p1,p2,bounds,Ops) 2 | % function [c1,c2] = singlePtXover(p1,p2,bounds,Ops) 3 | % p1 - the first parent ( [solution string function value] ) 4 | % p2 - the second parent ( [solution string function value] ) 5 | % bounds - the bounds matrix for the solution space 6 | % Ops - Options matrix for simple crossover [gen #SimpXovers]. 7 | 8 | % Binary and Real-Valued Simulation Evolution for Matlab 9 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 10 | % 11 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 12 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 13 | % Software, Submitted 1996. 14 | % 15 | % This program is free software; you can redistribute it and/or modify 16 | % it under the terms of the GNU General Public License as published by 17 | % the Free Software Foundation; either version 1, or (at your option) 18 | % any later version. 19 | % 20 | % This program is distributed in the hope that it will be useful, 21 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 22 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 23 | % GNU General Public License for more details. A copy of the GNU 24 | % General Public License can be obtained from the 25 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 26 | sz=size(p1,2)-1; 27 | cut = round(rand*(sz-1)+0.5); %Generate random cut point U(1,n-1) 28 | pm1=p1(1:sz); 29 | pm2=p2(1:sz); 30 | c1=p1; 31 | c2=p2; 32 | c1(1:cut)=p1(1:cut); 33 | c2(1:cut)=p2(1:cut); 34 | for i=1:cut 35 | pm1=strrep(pm1,p2(i),-1); 36 | pm2=strrep(pm2,p1(i),-1); 37 | end 38 | c1((cut+1):sz)=p2(find(pm2>0)); 39 | c2((cut+1):sz)=p1(find(pm1>0)); 40 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/startup.m: -------------------------------------------------------------------------------- 1 | % path(path,'E:\matlab\genetic\gaot'); 2 | 3 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/swapMutation.m: -------------------------------------------------------------------------------- 1 | function [child] = swapmutate(par,bounds,genInfo,Ops) 2 | % Swap mutation exchanges the positions of two randomly 3 | % chosen genes in a permutation 4 | % 5 | % function [newSol] = adjswapmutation(parent,bounds,Ops) 6 | % parent - the first parent ( [solution string function value] ) 7 | % bounds - the bounds matrix for the solution space 8 | % Ops - Options for binaryMutation [gen prob_of_mutation] 9 | 10 | % Binary and Real-Valued Simulation Evolution for Matlab 11 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 12 | % 13 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 14 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 15 | % Software, Submitted 1996. 16 | % 17 | % This program is free software; you can redistribute it and/or modify 18 | % it under the terms of the GNU General Public License as published by 19 | % the Free Software Foundation; either version 1, or (at your option) 20 | % any later version. 21 | % 22 | % This program is distributed in the hope that it will be useful, 23 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 24 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 25 | % GNU General Public License for more details. A copy of the GNU 26 | % General Public License can be obtained from the 27 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 28 | sz = size(par,2)-1; 29 | pos1 = round(rand*sz + 0.5); 30 | pos2 = round(rand*sz + 0.5); 31 | if pos1 ~= pos2 32 | if pos1 > pos2 33 | t = pos1; pos1 = pos2; pos2 = t; 34 | end 35 | child = [par(1:pos1-1) par(pos2) par(pos1+1:pos2-1) par(pos1) par(pos2+1:(sz+1))]; 36 | else 37 | child = par; 38 | end 39 | 40 | 41 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/threeswapMutation.m: -------------------------------------------------------------------------------- 1 | function [c] = threeswapMutation(p,bounds,genInfo,Ops) 2 | % Three swap mutation performs a three way swap of three randomly 3 | % chosen genes in a permutation 4 | % 5 | % function [newSol] = threeswapMutation(parent,bounds,Ops) 6 | % parent - the first parent ( [solution string function value] ) 7 | % bounds - the bounds matrix for the solution space 8 | % Ops - Options for binaryMutation [gen prob_of_mutation] 9 | 10 | % Binary and Real-Valued Simulation Evolution for Matlab 11 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 12 | % 13 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 14 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 15 | % Software, Submitted 1996. 16 | % 17 | % This program is free software; you can redistribute it and/or modify 18 | % it under the terms of the GNU General Public License as published by 19 | % the Free Software Foundation; either version 1, or (at your option) 20 | % any later version. 21 | % 22 | % This program is distributed in the hope that it will be useful, 23 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 24 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 25 | % GNU General Public License for more details. A copy of the GNU 26 | % General Public License can be obtained from the 27 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 28 | sz = size(p,2)-1; 29 | j=randperm(sz); 30 | jobs=j(1:3); 31 | c=p; 32 | c(jobs)=c(jobs(randperm(3))); 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/tournSelect.m: -------------------------------------------------------------------------------- 1 | function[newPop] = tournSelect(oldPop,options) 2 | % Performs a tournament selection. 3 | % 4 | % function[newPop] = tournSelect(oldPop,options) 5 | % newPop - the new population selected from the oldPop 6 | % oldPop - the current population 7 | % options - options to normGeomSelect [gen tournament_size] 8 | 9 | % Binary and Real-Valued Simulation Evolution for Matlab 10 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 11 | % 12 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 13 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 14 | % Software, Submitted 1996. 15 | % 16 | % This program is free software; you can redistribute it and/or modify 17 | % it under the terms of the GNU General Public License as published by 18 | % the Free Software Foundation; either version 1, or (at your option) 19 | % any later version. 20 | % 21 | % This program is distributed in the hope that it will be useful, 22 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 23 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 24 | % GNU General Public License for more details. A copy of the GNU 25 | % General Public License can be obtained from the 26 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 27 | 28 | tournSize=options(2); % Get the number of tournaments 29 | e = size(oldPop,2); % xZome length 30 | n = size(oldPop,1); % number in Population 31 | newPop = zeros(n,e); % Create the memory for newPop 32 | tourns=floor(rand(tournSize,n)*n)+1; % Schedule of tournaments 33 | % Determine the winner of the tournaments 34 | [c b]=max(reshape(oldPop(tourns,e),tournSize,n)); 35 | newPop=oldPop(diag(tourns(b,:)),:); % Copy the winners in to newPop 36 | 37 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/tspEval.m: -------------------------------------------------------------------------------- 1 | function [sol,val] = tsp(sol,options) 2 | global distMatrix; 3 | sol; 4 | numvars=size(sol,2)-1; 5 | val = -sum(diag(distMatrix(sol(1:numvars),[sol(2:numvars) sol(1)]))); 6 | 7 | 8 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/unifMutation.m: -------------------------------------------------------------------------------- 1 | function [parent] = uniformMutate(parent,bounds,Ops) 2 | % Uniform mutation changes one of the parameters of the parent 3 | % based on a uniform probability distribution. 4 | % 5 | % function [newSol] = multiNonUnifMutate(parent,bounds,Ops) 6 | % parent - the first parent ( [solution string function value] ) 7 | % bounds - the bounds matrix for the solution space 8 | % Ops - Options for uniformMutation [gen #UnifMutations] 9 | 10 | % Binary and Real-Valued Simulation Evolution for Matlab 11 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 12 | % 13 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 14 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 15 | % Software, Submitted 1996. 16 | % 17 | % This program is free software; you can redistribute it and/or modify 18 | % it under the terms of the GNU General Public License as published by 19 | % the Free Software Foundation; either version 1, or (at your option) 20 | % any later version. 21 | % 22 | % This program is distributed in the hope that it will be useful, 23 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 24 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 25 | % GNU General Public License for more details. A copy of the GNU 26 | % General Public License can be obtained from the 27 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 28 | 29 | df = bounds(:,2) - bounds(:,1); % Range of the variables 30 | numVar = size(parent,2)-1; % Get the number of variables 31 | % Pick a variable to mutate randomly from 1-number of vars 32 | mPoint = round(rand * (numVar-1)) + 1; 33 | newValue = bounds(mPoint,1)+rand * df(mPoint); % Now mutate that point 34 | parent(mPoint) = newValue; % Make the child 35 | -------------------------------------------------------------------------------- /遗传算法优化/gaot/uniformXover.m: -------------------------------------------------------------------------------- 1 | function [ch1,ch2,t] = uniformxover(par1,par2,bounds,Ops) 2 | % Uniform crossover takes two parents P1,P2 and performs uniform 3 | % crossover on a permuation string. 4 | % 5 | % function [c1,c2] = linearOrderXover(p1,p2,bounds,Ops) 6 | % p1 - the first parent ( [solution string function value] ) 7 | % p2 - the second parent ( [solution string function value] ) 8 | % bounds - the bounds matrix for the solution space 9 | % Ops - Options matrix for simple crossover [gen #SimpXovers]. 10 | 11 | % Binary and Real-Valued Simulation Evolution for Matlab 12 | % Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 13 | % 14 | % C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function 15 | % optimization: A Matlab implementation. ACM Transactions on Mathmatical 16 | % Software, Submitted 1996. 17 | % 18 | % This program is free software; you can redistribute it and/or modify 19 | % it under the terms of the GNU General Public License as published by 20 | % the Free Software Foundation; either version 1, or (at your option) 21 | % any later version. 22 | % 23 | % This program is distributed in the hope that it will be useful, 24 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 25 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 26 | % GNU General Public License for more details. A copy of the GNU 27 | % General Public License can be obtained from the 28 | % Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 29 | sz = size(par1,2)-1; 30 | ch1 = par1; 31 | ch2 = par2; 32 | t = round(rand(1,sz)); 33 | szt = sum(t); 34 | idx = 1:sz; 35 | idxt = idx(logical(t)); 36 | plst = idxt; 37 | for i = 1:szt 38 | plst(i) = find(par2 == par1(idxt(i))); 39 | end 40 | plst = sort(plst); 41 | for i = 1:szt 42 | ch1(idxt(i)) = par2(plst(i)); 43 | end 44 | szt = sz - szt; 45 | idxt = idx(~t); 46 | plst = idxt; 47 | for i = 1:szt 48 | plst(i) = find(par1 == par2(idxt(i))); 49 | end 50 | plst = sort(plst); 51 | for i = 1:szt 52 | ch2(idxt(i)) = par1(plst(i)); 53 | end 54 | 55 | 56 | -------------------------------------------------------------------------------- /遗传算法优化/optimal.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/遗传算法优化/optimal.m -------------------------------------------------------------------------------- /遗传算法优化/slidemodel.mdl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Princewjh/Matlab-GA/c5b24ffb4f596f0c009d7a8d7126d5a48e0497d0/遗传算法优化/slidemodel.mdl -------------------------------------------------------------------------------- /遗传算法优化/slidemodel_plot.m: -------------------------------------------------------------------------------- 1 | close all; 2 | figure(1); 3 | subplot(311); 4 | plot(t,x(:,1),'b','linewidth',2); 5 | xlabel('Time(s)');ylabel('x'); 6 | legend('x'); 7 | subplot(312); 8 | plot(t,x(:,3),'b','linewidth',2); 9 | xlabel('Time(s)');ylabel('y'); 10 | legend('y'); 11 | subplot(313); 12 | zd=3*t./t; 13 | plot(t,x(:,5),'b','linewidth',2); 14 | xlabel('Time(s)');ylabel('z'); 15 | legend('z'); 16 | 17 | figure(2); 18 | subplot(311); 19 | plot(t,x(:,7)/pi*180,'k','linewidth',2); 20 | legend('\phi (degree)'); 21 | subplot(312); 22 | plot(t,x(:,9)/pi*180,'k','linewidth',2); 23 | legend('\theta (degree)'); 24 | subplot(313); 25 | plot(t,x(:,11)/pi*180,'k','linewidth',2); 26 | legend('\psi (degree)'); 27 | figure(3); 28 | subplot(411); 29 | plot(t,ut(:,1),'k','linewidth',2); 30 | legend('u1'); 31 | subplot(412); 32 | plot(t,ut(:,2),'k','linewidth',2); 33 | legend('u2'); 34 | subplot(413); 35 | plot(t,ut(:,3),'k','linewidth',2); 36 | legend('u3'); 37 | subplot(414); 38 | plot(t,ut(:,4),'k','linewidth',2); 39 | legend('u4'); --------------------------------------------------------------------------------