How to create plot legend in a loop

2 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));
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);
hold off
xlabel('Frequency \omega/\omega_o')
title('Frequency Response |H(j\omega)|')
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)




Community Treasure Hunt

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

Start Hunting!