Clear Filters
Clear Filters

Error using plot Vectors must be the same length.

2 views (last 30 days)
Hi, I just started using MatLab. How can I get the plot like it is in the picture? I wrote this code, but I get the Error using plot Vectors must be the same length.
fs=500;
t=(0:(6*fs-1))/fs;
sygnal2a=sin(t(1:500)*1*2*pi);
sygnal2b=sin(t(1:500)*1*2*pi+2*pi);
sygnal2c=sawtooth(t(2:500)*3*2*pi+4*pi,0.5);
sygnal2d=square(t(2:500)*1*2*pi+6*pi,25);
sygnal2=[sygnal2a sygnal2b sygnal2c sygnal2d];
figure;
plot(t', sygnal2');
Error using plot
Vectors must be the same length.
grid on;
tp = 1.8;
ip = floor(tp*fs)+1;
tk = 3.3;
ik = floor(tk*fs)+1;
hold on;
plot(t(ip:ik)', [sygnal2(ip:ik)']);
Here is the content of the task:
Generate a signal called signal2, which will last 6 s and will consist of the following fragments:
• for t=<0;2) s will be the sum of sinusoidal signals with amplitudes 1 and frequencies 1 and 4 Hz,
• for t=<2;4) s will be a triangle signal with a frequency of 3 Hz,
• for t=<4;6) s will be a square wave signal with a frequency of 1 Hz, 25% duty cycle and variable values between 0 and 1.
Sampling frequency fs = 500 Hz. Make a graph of the signal.

Accepted Answer

Walter Roberson
Walter Roberson on 16 Mar 2024
fs=500;
t=(0:(6*fs-1))/fs;
sygnal2a=sin(t(1:500)*1*2*pi);
sygnal2b=sin(t(1:500)*1*2*pi+2*pi);
sygnal2b is the same as sygnal2a except for a phase shift of 2*pi . But since the operation is sin(), a phase shift of 2*pi is the same as a phase shift of 0 (to within round-off error). So your sygnal2a and sygnal2b are the same (to within round-off error)
Through coincidence between fs and 1:500, each of them covers 1 second worth of signal.
sygnal2c=sawtooth(t(2:500)*3*2*pi+4*pi,0.5);
sygnal2d=square(t(2:500)*1*2*pi+6*pi,25);
Those are each one sample short of 1 second worth of signal. The reason for being one sample short is not obvious.
sygnal2=[sygnal2a sygnal2b sygnal2c sygnal2d];
The signals are concatenated together, giving a total of 2 samples less than 4 seconds.
It is likely that sygnal2b and sygnal2c and sygnal2d should be using t() some other offset -- (501:1000), (1000:1498), (1499:1998)
whos t sygnal2
Name Size Bytes Class Attributes sygnal2 1x1998 15984 double t 1x3000 24000 double
figure;
plot(t', sygnal2');
Error using plot
Vectors must be the same length.
You try to use the full t (length 3000) even though your composite signal is decidedly shorter. You should be using t(1:length(sygnal2))
  3 Comments

Sign in to comment.

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!