How to fix problem with subplot and for loop

15 views (last 30 days)
I'm having trouble plotting with subplot. I've been trying to plot multiple graphs since the variables I'm plotting have multiple outputs but I tried using the comand - subplot(3,2,i5) since im trying to plot 3 rows in two coloums by pulling my info form a for loop. It's giving me a graph but it's also giving me an error "Index exeeds number of subplots". What should I do?
(to solve a little bit of confusion, I'm trying to plot the noise factors + the sine wave to get different snr noise levels)
This is my code:
clear;
clc;
load('ver.mat')
Time_5=0:0.01:5;
f=3;
x_5= sin(2*pi*f*Time_5*6);
Max_diff=length(Time_5);
disp(Max_diff); % length of time vector
501
plot(Time_5,x_5);
title('Signal vs. Time Vector');
ylabel('Signal');
xlabel('Time');
N_fact=0.2:0.6:4; % noise vector
for i5=1:length(N_fact)
noise=rand(size(Time_5))-0.5;
noise_sig= x_5+noise*N_fact(i5);
% for SNR:
sig_pwr=sum(x.^2)/length(x);
noise_pwr=sum((noise_sig-x).^2)/length(x);
snr=10*log10(sig_pwr/noise_pwr);
subplot(3,2,i5);
plot(Time_5,noise_sig);
xlabel('Time in s');
ylabel('Signal');
title(sprintf('SNR=%.2f dB',snr));
end
Unrecognized function or variable 'x'.
  2 Comments
Gabriela
Gabriela on 15 Sep 2023
I forgot to add something. I changed the line
snr=10*log10(sig_pwr/noise_pwr);
for:
snr=snr(x,noise_sig);
I think this one works better...? If not please let me know and thank you for the help!
Torsten
Torsten on 15 Sep 2023
Next error follows.
Please test your code next time by using the green RUN arrow.

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 15 Sep 2023
You are plotting seven subplots so you need to make room for them.
Try this —
clear;
clc;
load('ver.mat')
Time_5=0:0.01:5;
f=3;
x= sin(2*pi*f*Time_5*6);
Max_diff=length(Time_5);
disp(Max_diff); % length of time vector
501
plot(Time_5,x);
title('Signal vs. Time Vector');
ylabel('Signal');
xlabel('Time');
N_fact=0.2:0.6:4; % noise vector
for i5=1:length(N_fact)
noise=rand(size(Time_5))-0.5;
noise_sig= x+noise*N_fact(i5);
% for SNR:
sig_pwr=sum(x.^2)/length(x);
noise_pwr=sum((noise_sig-x).^2)/length(x);
snr=10*log10(sig_pwr/noise_pwr);
subplot(2,4,i5);
plot(Time_5,noise_sig);
xlabel('Time in s');
ylabel('Signal');
title(sprintf('SNR=%.2f dB',snr));
end
.

More Answers (1)

Image Analyst
Image Analyst on 15 Sep 2023
N_fact=0.2:0.6:4
N_fact = 1×7
0.2000 0.8000 1.4000 2.0000 2.6000 3.2000 3.8000
numel(N_fact)
ans = 7
You can see that you need at least 7 plots but with "3,2" you're setting up a layout of only 6 plot slots. To fix, use 3,3 in subplot, not 3,2
subplot(3, 3, i5)

Community Treasure Hunt

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

Start Hunting!