MATLAB: Holding plot legend inside loop & between two for loops plot I am writing legend inside for loop here i am able to hold plot but not the legend Best Answer I would recommend against this workflow. Insert the legend once at the end. For example:figure;hold on;h =zeros(10,1);colors = 'rgbcyk';for ii = 1:numel(h); h(ii) = plot(1:10,rand(1,10)+sin(rand(1,10)),colors(rem(ii,6)+1));endlegend(h) Related SolutionsMATLAB: How to add legends in graphs generated within a for loop. There is an example at https://www.mathworks.com/matlabcentral/answers/347894-duplicating-data-name-when-using-legend-in-a-for-loop MATLAB: Plot with ‘DisplayName’ in for loop Put this line: legend('-DynamicLegend');After the plot command. Like:for k=1:7 diffSum = 0; for % inside for loop I calculate diffSum end plot(diffSum, 'color', rand(1,3), 'LineWidth', 3, 'DisplayName', sprintf('Group Thermal Comfort: %d', tc(k)));hold on; legend('-DynamicLegend'); legend('show'); drawnow; end hold off; Related QuestionHolding legend on a Matlab plot inside a loop
Best Answer