How can I use a string in legend()?
128 ビュー (過去 30 日間)
古いコメントを表示
I have the following string:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/392638/image.png)
Now I want to use this string to produce a legend to my figure. So I use
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/392643/image.png)
and get this:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/392648/image.png)
But I would like to have this,
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/392653/image.png)
which I got by using the following command:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/392658/image.png)
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.
採用された回答
Ameer Hamza
2020 年 10 月 26 日
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))
0 件のコメント
その他の回答 (1 件)
Alan Stevens
2020 年 10 月 26 日
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 件のコメント
Ameer Hamza
2020 年 10 月 26 日
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)
参考
カテゴリ
Help Center および File Exchange で Legend についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!