Legend don't match with line style
24 次查看(过去 30 天)
显示 更早的评论
w = 2*pi;
k = (0:4);
t_2 = (0:0.01:1)';
T = t_2 * ones(1, 5);
Phi_k = exp(T*diag(k)*w*1i);
%Plot Re{Phi(t)} vs. t, 0 <= t < 1, for k = 0...4, all 5 curves in one
%figure
k = 0;
Phi_0 = exp(T*diag(k)*w*1i);
Phi_1 = exp(T*diag(k+1)*w*1i);
Phi_2 = exp(T*diag(k+2)*w*1i);
Phi_3 = exp(T*diag(k+3)*w*1i);
Phi_4 = exp(T*diag(k+4)*w*1i);
plot(t_2, real(Phi_0), '-.', t_2, real(Phi_1), '--d', t_2, real(Phi_2), ':o', t_2, real(Phi_3), '-.*', t_2, real(Phi_4), '-s');
legend('0th','1st','2nd', '3rd', '4th');
xlabel('t_2'); ylabel('Amplitude');
I'm pretty new in matlab and I don't quite understand why legend isn't doing what I wanted it to do.
0 个评论
采纳的回答
Walter Roberson
2022-9-11
k = 0;
Phi_0 = exp(T*diag(k)*w*1i);
T is 101 x 5.
In your earlier calculations k was a vector of length 5 so diag(k) was 5x5, and (101 x 5) * (5 x 5) is well defined giving a 101x5 result that you then multiplied by a scalar w giving a matrix result.
In the present section, k is scalar, so diag(k) is scalar. (101 x 5)*scalar gives a 101x5 result. Then w is scalar so you end up with a matrix result.
When you plot() a 2d matrix, it will generally create one line per column. So you plot 5 lines multiple times, for a total of 25 lines drawn, but only 5 legends.
My guess is that you should construct diag(0:4) but extract one column each time, so 101x5 * 5x1 giving 101x1 results.
But... you already calculated that into Phi_k so just plot the columns of Phi_k
3 个评论
Walter Roberson
2022-9-12
h = plot(t_2, real(Phi_k));
h(1).Linespec = '-.';
h(2).Linespec = '--'; h(2).MarkerShape = 'd';
h(3).Linespec = ':'; h(3).MarkerShape = 'o';
h(4).Linespec = '-.'; h(4).MarkerShape = '*';
h(5).Linespec = '-'; h(5).MarkerShape = 's';
更多回答(1 个)
Cris LaPierre
2022-9-11
The legend in MATLAB assigns labels based on the order the line objects are created in. What is perhaps unexpected here is that T is a matrix (101x5), and the result of your calculation of Phis has the same size. You may have expected them to be vectors instead.
In MATLAB, each column is treated as a unique data series, so the first five lines plotted are the 5 columns of Phi_0. You also have 5 legend labels, which get assigned to these five lines, all of which have the same linestyle. MATLAB automatically cycles the colors using the default colororder.
w = 2*pi;
k = (0:4);
t_2 = (0:0.01:1)';
T = t_2 * ones(1, 5);
Phi_k = exp(T*diag(k)*w*1i);
Phi_0 = exp(T*diag(k)*w*1i)
plot(t_2, real(Phi_0), '-.');
legend('0th','1st','2nd', '3rd', '4th');
xlabel('t_2'); ylabel('Amplitude');
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Legend 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!