% Class 13 Optimization % Coded by Nigel F. Reuel on 2.26.19 % close all clc % In class exercise F1 = @(x) 2*x^2+4*x+6*x^3-7; %fplot(F1) %to find guess value of 0.6 % Derivative for Newton Raphson D1 = @(x) 4*x+4+18*x^2; [NR_root,~,~]=newtraph(F1,D1,.6) % For roots function, must order coefficients in descending order Ans_RootFunc = roots([6 2 4 -7]) % Fzero FZ_root = fzero(F1,0.6) % % Class notes % F1 = @(x) x^4+2*x^3+8*x^2+5*x; fplot(F1,[-2 1]) [x,~,~,~]=goldmin(F1,-2,1,1) % Example using fminbnd % Remember that this works for a single variable % with a single function (limited) % X_sol = fminbnd(F1,-2,1) % For optimization with one or more variables % (but still with ONE objective function) % use the fminsearch % Let's do example 7.11, make contour plot % then solve for minimum F2 = @(x,y) 2*x.^2+3*y.^2-4*x.*y-y-3*x; xvec = linspace(-10,10,100); yvec = linspace(-10,10,100); [xmat ymat] = meshgrid(xvec,yvec); zmat = F2(xmat,ymat); contourf(xvec,yvec,zmat) % Matlab solution to minimum location % V(1) = x, V(2) = y % Recast equation so it has one variable (array) F3 = @(V) 2*V(1).^2+3*V(2).^2-4*V(1).*V(2)... -V(2)-3*V(1); F4 = @(T) F2(T(1),T(2)); S = fminsearch(F3,[4 4]); hold on plot(S(1),S(2),'r+') % Example 7.38 from the textbook % alpha_vec = (45:1:135); np = length(alpha_vec); % Preallocate memory for the answers L_vec = zeros(np,1); for i = 1:np % Now, the value of alpha changes alpha = alpha_vec(i); a_rad = alpha/180*pi; w1 = 2; %m w2 = 2; %m Lfunc = @(theta) w1/sin(theta)+... w2/sin(pi-a_rad-theta); [theta_min, L] = fminsearch(Lfunc,30/180*pi); L_vec(i,1) = L; end % Now we have the solution vector, we can plot figure plot(alpha_vec,L_vec) xlabel('Alpha (deg)') ylabel('Length of Ladder (m)')