214 views (last 30 days)

I have the following code, producing 10 different lines in one graph. Each of these lines correspond to a certain variance of a, for which I want to create a legend.

With the current code, the legend just states "data1, data2,data3 etc" for each line.

I want the values of the array variance_a, which I produce outside of the for loop, to match data 1, data2,data3 etc and to add the text "variance_a=" in front of the value. In short, I want the legend to look like this:

variance_a= (first output of variance_a array)

variance_a=(second output of variance_a array)

etc.

I can't seem to figure out how to call values out of the array to the legend, and I want to avoid having to enter each input bij hand, as the number of values in variance_a needs to be changed. Any help here?

sample=10000;

s = -1 + (2).*rand(sample,1);

s = nonzeros(s);

s(s<0)=-1;

s(s>0)=1;

change_a=0.2:0.2:2

variance_a=sqrt(change_a)*(1/12)

for i=1:length(change_a)

%Define Channel

change_n=0:0.2:2;

a=change_a(i)*rand(sample,1);

n=change_n.*randn(sample,1);

%channel output

y=a.*s+n;

%Define received signal as negative y equals -1 and positive y equals 1

z=y;

z(y<0)=-1;

z(y>0)=1;

%compare source signal to received signal

c=z==s;

for i=1:size(z,2)

errors(i)=size(z,1)-nnz(c(:,i));

error_percent=errors./(size(z,1))*100.

end

%plot for each value of change_a a line

plot(var(n),error_percent)

xlabel('variance noise')

ylabel('error percentage')

hold on

end

legend()

Thiago Henrique Gomes Lobato
on 6 Oct 2019

You can pass an cell array of strings to the legend() (here for documentation https://de.mathworks.com/help/matlab/ref/legend.html) function in order to have what you want. For this just initialize an array before and then, for each interation, save the string that you want to be shown (I change your inner loop index so it is not the same i as the outer loop):

sample=10000;

s = -1 + (2).*rand(sample,1);

s = nonzeros(s);

s(s<0)=-1;

s(s>0)=1;

change_a=0.2:0.2:2

variance_a=sqrt(change_a)*(1/12)

LegendsStrings = cell(length(change_a),1); % Initialize array with legends

for i=1:length(change_a)

%Define Channel

change_n=0:0.2:2;

a=change_a(i)*rand(sample,1);

n=change_n.*randn(sample,1);

%channel output

y=a.*s+n;

%Define received signal as negative y equals -1 and positive y equals 1

z=y;

z(y<0)=-1;

z(y>0)=1;

%compare source signal to received signal

c=z==s;

for ii=1:size(z,2)

errors(ii)=size(z,1)-nnz(c(:,ii));

error_percent=errors./(size(z,1))*100.

end

%plot for each value of change_a a line

plot(var(n),error_percent)

xlabel('variance noise')

ylabel('error percentage')

hold on

% Save legend entry

LegendsStrings{i} = ['variance_a = ',num2str(variance_a(i))];

end

legend(LegendsStrings, 'Interpreter', 'none') % To be able to show _a

Sign in to answer this question.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.