zenbeam
zenbeam

Reputation: 11

illegal plot error when trying to use subplot

I am trying to use subplot, but got an error message I do not know how to correct.

(Also, since only the value of w varies, is there a more compact way to write this code rather than saying "cos(stuff*t") ten times in a row? Thanks.)

my current code is

clear all
clc

t = 0:0.001:40;
% there are 10 values of w to show, so make a 2x5 grid to show them all via
% subplot (2,5, blank)

x1=cos(pi/16*t);
x2=cos(pi/8*t);
x3=cos(pi/4*t);
x4=cos(pi/2*t);
x5=cos(pi*t);
x6=cos(15*pi/8*t);
x7=cos(2*pi*t);
x8=cos(5*pi/2*t);
x9=cos(3*pi*t);
x10=cos(4*pi*t);

subplot(2,5,x1), plot(t,x,1), subplot(2,5,x2), plot(t,x,2), subplot(2,5,x3), 
plot(t,x,3), subplot(2,5,x4), plot(t,x,4), subplot(2,5,x5), plot(t,x,5), 
subplot(2,5,x6), plot(t,x,6), subplot(2,5,x7), plot(t,x,7), subplot(2,5,x8), 
plot(t,x,8), subplot(2,5,x9), plot(t,x,9), subplot(2,5,x10), plot(t,x,10);



%Error using subplot (line 330);

%Illegal plot number;

%Error in (line 19);
%subplot(2,5,x1), plot(t,x,1);

Upvotes: 0

Views: 908

Answers (1)

Rotem
Rotem

Reputation: 32084

You just mixed the parameters of plot and subplot.

Read subplot documentation.

Here is a corrected version of you code:

clear all
clc

t = 0:0.001:40;
% there are 10 values of w to show, so make a 2x5 grid to show them all via
% subplot (2,5, blank)

x1=cos(pi/16*t);
x2=cos(pi/8*t);
x3=cos(pi/4*t);
x4=cos(pi/2*t);
x5=cos(pi*t);
x6=cos(15*pi/8*t);
x7=cos(2*pi*t);
x8=cos(5*pi/2*t);
x9=cos(3*pi*t);
x10=cos(4*pi*t);

subplot(2,5,1);
plot(t,x1);
subplot(2,5,2);
plot(t,x2);
subplot(2,5,3);
plot(t,x3);
subplot(2,5,4);
plot(t,x4);
subplot(2,5,5);
plot(t,x5);
subplot(2,5,6);
plot(t,x6);
subplot(2,5,7);
plot(t,x7);
subplot(2,5,8);
plot(t,x8);
subplot(2,5,9);
plot(t,x9);
subplot(2,5,10);
plot(t,x10);

Here is how to do it using for loops:

clear all
clc

t = 0:0.001:40;
% there are 10 values of w to show, so make a 2x5 grid to show them all via
% subplot (2,5, blank)

W = [1/16, 1/8, 1/4, 1/2, 1, 15/8, 2, 5/2, 3, 4]*pi;

%X Replaces x1 to x10
X = zeros(10, length(t));

%Fill X with 10 rows (X(1, :) matches x1, X(2, :) matches x2...)
for i = 1:10
    X(i, :) = cos(W(i)*t);
end

%Plot using a for loop
for i = 1:10
    subplot(2,5,i);
    plot(t, X(i, :));
end

You can even do it without the first for loop:

t = 0:0.001:40;

W = [1/16, 1/8, 1/4, 1/2, 1, 15/8, 2, 5/2, 3, 4]*pi;

%Fill X with 10 rows (X(1, :) matches x1, X(2, :) matches x2...)
X = cos(W'*t);

%Plot using a for loop
for i = 1:10
    subplot(2,5,i);
    plot(t, X(i, :));
end

Upvotes: 2

Related Questions