How can I use a string in legend()?

174 vues (au cours des 30 derniers jours)
Marcel345614
Marcel345614 le 26 Oct 2020
Commenté : Penghao Duan le 18 Avr 2021
I have the following string:
Now I want to use this string to produce a legend to my figure. So I use
and get this:
But I would like to have this,
which I got by using the following command:
Tthis is exactly the string Legend copied into the function legend().
How can I use directly the string Legend, without copying it to the function legend()?
Edit: I forgot the following code sniplet:
p=zeros(2*length(HG),1);
hold on;
for iter2 = 1:length(HG)
p(2*iter2-1)=plot(freq,real(n(:,iter2)), 'color', cc(iter2,:));
p(2*iter2)= plot(freq,imag(n(:,iter2)),'--', 'color', cc(iter2,:));
end
I use the variable p to skip all dotted lines in the legend.
  3 commentaires
Marcel345614
Marcel345614 le 26 Oct 2020
Because I build the Legend-string and want to use it now. This is how I build it:
values=1:2:(2*length(HG)); %only the solid line should have a legend
Legend1=strcat('[',sprintf('p(%d) ',values),']',',');
Legend2=cell(length(HG),1);
quote=char(39);
for iter3=1:length(HG)
if iter3<length(HG)
Legend2{iter3}=strcat(quote,'HS+HG=', num2str(HS(iter3)),'+',num2str(HG(iter3)),quote,',');
else
Legend2{iter3}=strcat(quote,'HS+HG=', num2str(HS(iter3)),'+',num2str(HG(iter3)),quote);
end
end
Legend3=string(strjoin(Legend2));
Legend=strcat(Legend1,'{',Legend3,'}');

Connectez-vous pour commenter.

Réponse acceptée

Ameer Hamza
Ameer Hamza le 26 Oct 2020
Although Walter's comment already shows the problems with eval(), in case you still want to use the current method, then the closest you can get is something like this
fig = figure()
hold on
p(1) = plot(rand(1,10))
p(2) = plot(rand(1,10))
Legend_str1 = "[p(1) p(2)]";
Legend_str2 = "{'ABC', 'DEF'}";
legend(eval(Legend_str1), eval(Legend_str2))

Plus de réponses (1)

Alan Stevens
Alan Stevens le 26 Oct 2020
You could use
Legend = ['HS+HG = 0.5+5' ;'HS+HG = 1+5'];
legend(Legend)
But make sure there are the same number of characters (including spaces) in both strings.
  2 commentaires
Ameer Hamza
Ameer Hamza le 26 Oct 2020
Following alternatives does not require that character arrays have equal lengths.
Legend = {'HS+HG=0.5+5';'HS+HG=1+5'};
legend(Legend)
or
Legend = ["HS+HG=0.5+5";"HS+HG=1+5"];
legend(Legend)
Penghao Duan
Penghao Duan le 18 Avr 2021
Thanks, that is helpful

Connectez-vous pour commenter.

Produits


Version

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by