Skip to main content
Library homepage
 
Engineering LibreTexts

3.5.1: Create a 2D x-y Sine-Wave Plot with a for Loop

  • Page ID
    84378
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    By Carey A. Smith

    2-Dimensional plots of a time sequence can be easily created in 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.

    Example \(\PageIndex{1}\) Plot points of a sine wave

    % 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

    %% 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

    Sine_wave_script_example.png

     

     


    This page titled 3.5.1: Create a 2D x-y Sine-Wave Plot with a for Loop is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Carey Smith.

    • Was this article helpful?