MATLAB: Plotting legends in loop for mean and standard deviation of spectra

legendloopMATLABpatchplot

I have mean values for my spectra and their standard deviation saved as
meanC=mean(C)
stdC=std(C)
the labels for my C data are saved as labelC
wavenumbers1 is the x axis of my data.
I wand to plot the mean spectra(meanC) vs wavenumbers and I want each spectrum to have a legend. I also want to plot the meanC+std and meanC-std as a shaded area around each mean. But I want to get the legend of the standard deviation curve only one time since it's the same color for all means. How should I go about this?
at the moment since I am using a loop, I get half of the legends of the mean spectra in my plot…. should I turn off the legends for the standard deviation? how would I do that using patch?
I am open to doing this with other functions if it's more efficient that way! I'm using Matlab R2018a
Thank you!
for i=1:M;
plot(wavenumbers1,(meanC(i,:)); legend(labelC)
hold on
patch([wavenumbers1' fliplr(wavenumbers1')], [((meanC(i,:))+stdC(i,:)) fliplr((meanC(i,:))-stdC(i,:))], 'r', 'FaceAlpha',0.5, 'EdgeColor','none')
end

Best Answer

I think what you want to do is utilize the subset input for legend. What I usually do is something like this:
lns = [];
for i=1:M
lns(i) = plot(wavenumbers1,(meanC(i,:));
hold on;
% plot other stuff
end
legend(lns,{"Label1", "Label2", "LabelM"});
Related Question