How to change the display format of a legend in MATLAB
I am looking for a way to force legend entries in a specific format. I am following the code, they display as
Instead, I want it to be like 1e-1,1e-2,1e-3,1e-4, 1e-5. Is there any way to do this.
MWE:
sig=[0.1 0.01 0.001 0.0001 0.00001];
for j=1:length(sig)
for x=1:10
Cost(j,x) = 2*x+j;
end
plot(1:10,Cost(j,:));
end
legend(strcat('\sigma^2_n=',num2str((sig)')));
set(h,'Interpreter','latex')
+3
source to share
1 answer
You must indicate that you want to use scientific notation when converting sig
to a string by passing the special format specifier beforenum2str
legend(strcat('\sigma^2_n=',num2str(sig.', '%.0e')));
If you want to remove the leading 0
in the exponent, you can remove them with a regular expression
S = regexprep(cellstr(num2str(sig.', '%.0e')), '(?<=e[-+])0*', '');
legend(strcat('\sigma^2_n=', S))
+5
source to share