How can I plot a rectified square wave from sine waves?
3 views (last 30 days)
Show older comments
I have tried to plot a rectified square wave of length T (1 second) and amplitude A (0.226) that oscillates between 0 and A on the y-axis using the code below. I have tried both formulas listed (one commented out) and either get a plot of A and -A which takes about 20 minutes to generate with a high speed computer, or "Operation terminated by user during sym/symsum (line 68)" when there are only 11 lines of code in the .m file. How do I fix the code below to generate the graph I'm looking for? Thank you
clear all;
T=1;
A=0.226;
t=[0:0.01:4*pi];
wo=2*pi/T;
syms n
%f=(A/2)+(4*A/pi)*symsum((sin((2*n-1)*wo*t))/(2*n-1),n,[1 Inf]);
f=abs((4/pi)*symsum((1/(2*n-1))*sin(((2*n-1)*pi*t)/(T/2)),n,1,Inf));
hold on;
plot(t,f)
hold off;
0 Comments
Answers (1)
Anudeep Kumar
on 11 Mar 2025
Hey W M,
It looks like you are trying to generate a rectified square wave using symbolic summation, which can be computationally intensive. I would like to suggest using a numerical approach to generate the rectified square wave. Here's a modified version of your code that should work more efficiently:
clear all;
T = 1;
A = 0.226;
t = 0:0.01:4*T; % Adjusted to match the period T
wo = 2*pi/T;
f = zeros(size(t)); % Initialize the waveform
% Number of harmonics to include in the Fourier series
N = 100;
for n = 1:N
f = f + (4*A/pi) * (1/(2*n-1)) * sin((2*n-1)*wo*t);
end
f = abs(f); % Rectify the waveform
hold on;
plot(t, f);
xlabel('Time (s)');
ylabel('Amplitude');
title('Rectified Square Wave');
hold off;
In the above code I used a numerical summation approach to generate the rectified square wave. It includes a specified number of harmonics (in this case, 100) to approximate the waveform. The “abs()” function is used to rectify the waveform, ensuring it oscillates between 0 and A.
Feel free to adjust the number of harmonics (N) to balance between accuracy and computational efficiency.
I hope that works for your case!
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!