3.5.1: Create a 2D x-y Sine-Wave Plot with a for Loop
- Page ID
- 84378
By Carey A. Smith
2-Dimensional plots of a time sequence can be easily created in MATLAB and in Octave.
% Octave needs graphics toolkit to plot graph.
graphics_toolkit("fltk") % Do not use with MATLAB
The key lines of code are:
figure; % Open a figure window. The plot is created in this figure window.
plot(t, sin_t, 'o')
- The first variable, t, is the x coordinate of the point.
- The second variable, sin_t, is the x coordinate of the point.
- The 'o' means to use a circle for point's marker.
hold on; % Let additional points be plotted on the same figure
It can be useful to code this example together as a class.
% Compute and plot points of a sine wave
% using a script with a "for loop"
clear all; % Clear all variables
clc; % Clear the console (computer screen)
close all; % close all figures
format compact; % Don't insert blank lines on the console
graphics_toolkit("fltk") % Include this line when using Octave. Not for Matlab.
%% Initialize variables
period = 0.5; % seconds
t_end = 3*period; % The end of the interval
dt = period/16; % time between points
%%
figure; % Open a figure window
xlim([0,t_end]) % Set the x-axis to be 0 to t_end
ylim([-1,1]) % Set the x-axis to be -1 to 1
grid on; % Draw grid lines
hold on; % Let additional points be plotted on the same figure
%%
for t = 0 : dt : t_end % t = 0, dt, 2*dt, ... t_end
% Compute the sine for the current value of t
sin_t = sin(2*pi*t/period);
plot(t, sin_t, 'o')
pause(0.3) % pause long enuf to see each point as it is plotted
end
Solution