Hi , please how to make a loop for subplot , I need to plot plot 5 signals on 3 rows & 2 columns , signals to plot x , y , cr_x , cr_y and cr_xy given below in the code for auto-correlation and cross-correlation

1 view (last 30 days)
% Autocorrealtion and cross correlation
f01=50;
f02=500;
fs=3000;
dt=1/fs;
t=0:dt:0.2;
L=length(t);
x=sin(2*pi*f01.*t)+(3+0.5*randn(1,L));
y=cos(2*pi*f02.*t+exp(-t/(randn(1,L))));
[cr_x,lgs_x] = xcorr(x); % Auto correlation of x
[cr_y,lgs_y] = xcorr(y); % Auto correlation of y
[cr_xy,lgs_xy] = xcorr(x,y); % Cross correlation of x and y
plot(t,x)
plot(lgs_x/fs,cr_x/L)
xlabel('Lag (x)')
plot(lgs_y/fs,cr_y/L)
plot(t,y)
xlabel('Lag (y)')
plot(lgs_xy/fs,cr_xy/L)
xlabel('Lag (x&y)')
grid on
grid minor

Accepted Answer

Star Strider
Star Strider on 6 Feb 2019
I doubt that a loop would be more efficient than simply allocating the subplot calls using your existing code.
Try this:
figure
subplot(3,2,1)
plot(t,x)
grid on
grid minor
subplot(3,2,2)
plot(lgs_x/fs,cr_x/L)
xlabel('Lag (x)')
grid on
grid minor
subplot(3,2,3)
plot(lgs_y/fs,cr_y/L)
grid on
grid minor
subplot(3,2,4)
plot(t,y)
xlabel('Lag (y)')
grid on
grid minor
subplot(3,2,5)
plot(lgs_xy/fs,cr_xy/L)
xlabel('Lag (x&y)')
grid on
grid minor
If you absolutely must use a loop for this, your code becomes significantly more complicated, because you have to assign the variables you are plotting to elements of a cell array or structure.
  2 Comments
Star Strider
Star Strider on 6 Feb 2019
I just copied and pasted in the code I posted. That is much easier than creating all the cell arrays you would otherwise need for a loop.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!