How to create plot legend in a loop

9 views (last 30 days)
Allan Prince
Allan Prince on 7 Jul 2021
Commented: Mohammad Sami on 8 Jul 2021
I am attempting to add a legend for frequency response plots that are generated in a loop.
I have read through a number of similar answers on this topic but I have not found any that seem to work.
One of the solutions I found mentions indexing a string variable by curly brace but this
just causes an error "Unable to perform assignment because brace indexing is not supported for
variables of this type". Then I went through a blog post that discussed brace indexing but I did not
find a relevant solution there either. I also tried using smooth braces on the 'txt' variable but then
matlab complains that the size of the variable on the left does not match that on the right, even
though they both use the same index.
I would greatly appreciate it if someone could offer a solution to this issue.
Below is my code.
Thank you.
w = 0.01:0.01:20;
zeta = [0.1 0.3 0.707 1.0 3.0 10.0];
w0 = 1;
H = zeros(1, length(w));
figure()
plot(0,0)
hold on
index = 1:1:length(w);
for k=1:length(zeta)
txt{k} = strcat('\zeta', num2str(zeta(k)));
H(index) = abs(1./(1+(2*zeta(k)*1j*w./w0)+(1j*w./w0).^2));
plot(0:0.01:20-0.01, H);
end
hold off
legend(txt)
xlabel('Frequency \omega/\omega_o')
ylabel('Amplitude')
title('Frequency Response |H(j\omega)|')
  3 Comments
Allan Prince
Allan Prince on 8 Jul 2021
Edited: Allan Prince on 8 Jul 2021
When I attempted to make the code work as written, I was getting an error that indicated my use of brace indexing was not supported so the code wouldn't run. The following line was giving the error:
txt{k} = strcat('\zeta= ', num2str(zeta(k)));
After I made this post, however, I closed out of matlab to work on another project and when I reopened it, the code started working. I do not understand what caused this issue. I didn't change the code after I restarted matlab so the problem should have still been there. Apparently the issue is fixed now. I wish I could recreate it so I could understand what the issue was for future reference. Thanks for your response. The issue appears to be resolved.
Mohammad Sami
Mohammad Sami on 8 Jul 2021
I think most likely what happened was that txt variable was already created elsewhere and it was not a cell array. If that was the case matlab will give you an error when you try to do txt{k}.

Sign in to comment.

Answers (0)

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!