I'm in truble with the legend function.
I have a function plot_f.m which plots a function with its legend.
function plot_fM=1000;x=linspace(-11,15,M);y=linspace(-7,11,M);f1=0.1.*x.^3+12.*sin(x)+1.7.^(-x)-x.^2;f2=0.1.*y.^3+12.*sin(y)+1.7.^(-y)-y.^2;f=@(x)(0.1.*x.^3+12.*sin(x)+1.7.^(-x)-x.^2);p1=plot(x,f1,'Color','b'); hold on;p2=plot(y,f2,'Color',[0,1,0],'LineWidth',3);p3=plot(-7.000,f(-7.000),'sq','MarkerSize',8,'MarkerFaceColor',[1 0 0]); plot(-1.850,f(-1.850),'sq','MarkerSize',8,'MarkerFaceColor',[1 0 0]); plot( 4.931,f( 4.931),'sq','MarkerSize',8,'MarkerFaceColor',[1 0 0]); plot(10.007,f(10.007),'sq','MarkerSize',8,'MarkerFaceColor',[1 0 0]);xlim([-15 15])ylim([-70 80])ax = gca;ax.XAxisLocation = 'origin';ax.YAxisLocation = 'origin';legend([p1,p2,p3],{'Función', 'Función en [-7,11]', 'Óptimos locales'})box offhold onend
In the main program I make a call to this function and I want to add more information to the legend.
% Ejercicio 2:
% Uso de Matlab para la minimización de una funcion real
% con varios puntos de minimo local :
%
% min: f(x)=0.1.*x.^3+12.*sin(x)+1.7.^(-x)-x.^2
% restricciones: ninguna
clear all;close all;options = optimset('Display','iter');%,'PlotFcns',@optimplotfval);
salida = fopen('output.txt','w');global xx; xx=[];figure; plot_fhold onx0=1.2;% La convergencia del metodo numerico depende
% esencialmente del iterante inicial elegido.
% No obstante, nunca va a converger a -7
% converge a -7, que es 'a simple vista', el minimo
% global del problema con restricciones.
%Convergencias:
% x0 = -5; % xmin = -7.852.
% x0 = -3; % xmin = -1.850.
% x0 = 5; % xmin = 4.931.
% x0 = 10; % xmin = 10.007.
% Cambiar el solver local segun se
% desee: fminsearch o fminunc
f=@(x)f(x);tic[xmin,fmin,exitflag,outputs] = fminsearch('f',x0,options);t1 = toc;p4 = plot(x0,f(x0),'sq','MarkerSize',8,'MarkerFaceColor',[0 1 1]);hold onp5 = plot(xx(:,1),xx(:,2),'ro','MarkerSize',3);hold onp6 = plot(xmin,f(xmin),'o','MarkerSize',5,'MarkerFaceColor',[1 1 0]);hold onlegend([p4,p5,p6],{'Iterante inicial','Iterantes','Optimo local'})hold offfprintf(salida,'\n');fprintf(salida,'Solucion con optimizador local:');fprintf(salida,'\n');fprintf(salida,'Solucion optima: xmin = %.3f.' ,xmin);fprintf(salida,'\n');fprintf(salida,'Valor de f: fmin = %.3f.',fmin);fprintf(salida,'\n');fprintf(salida,'Evaluaciones de la funcion objetivo: k = %i.',outputs.funcCount);fprintf(salida,'\n');fprintf(salida,'Tiempo total: t1 = %.3f.',t1);fprintf(salida,'\n');fprintf(salida,'Iteraciones del metodo: n = %i',outputs.iterations);fprintf(salida,'\n');fprintf(salida,'\n');function f=f(x) global xx; f = 0.1.*x.^3+12.*sin(x)+1.7.^(-x)-x.^2; xy = [x,f]; xx = [xx; xy];end
However, I'm just overwriting the data which is currently in the plot's legend. How can I solve this?
Best Answer