<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">\documentclass[onecolumn,letterpaper,11pt]{article}

%===================================================================
% Include common packages, environments, counters etc
\input{common_latex/common_latex_packages}
\input{common_latex/common_latex_lab_format}
\input{common_latex/common_latex_definitions}
%===================================================================
\setcounter{tocdepth}{2}
%===================================================================

\begin{document}
\wikidoc{file=Lab.Matlab02}
\wikidoc{auth=mikerb@mit.edu}
\helplevelsubsec

%===================================================================
% Build the Cover Page in an environment style easy for wiki parsing
\begin{labcover}
\labtitle{Matlab Plotting Lab 02 - Bar Plots}
\vspace{0.2in}
\labcourse{Pavlab: Matlab Bar Plotting}
\vspace{0.5in}
\labpng{0.25}{figures/matlab.png}
\vspace{0.25in}
\labdate{Jan 4th, 2023}
\vspace{0.23in}
\labauth{Michael Benjamin, mikerb@mit.edu}
\labauth{Department of Mechanical Engineering}
\labauth{MIT, Cambridge MA 02139}
\labtoc{small}
\labtocdepth{2}
\end{labcover}

%===================================================================
% Add a blank page so first body page is on the right when doubleside
\blankpage

%===================================================================
% Begin the body of the text
%===================================================================
\section{Overview and Objectives}
%===================================================================

\begin{labinfo}
%\labinfoheader{Topics:}
\begin{packed_itemize}[2]
\item Goal - Make a plot with manually entered data
\item Goal - Plotting data from a file
\item Goal - Running a matlab script 
\item Goal - Plot two datasets into one plot
\end{packed_itemize}
\end{labinfo}

%=======================================================================
\subsection*{Preliminaries}

Make sure that Matlab is installed on your computer. On Linux or MacOS systems
you should be able to confirm from the command line:

\vspace{0.1in}
\begin{consoleverb}
$ which matlab
/Applications/MATLAB_R2022b.app/bin/matlab
\end{consoleverb}

\vspace{0.1in}
\noindent
After launching matlab, a window like the below should open:

\vspace{0.1in}
\begin{figure}[H]
  \centering
  \includegraphics[width=0.9\textwidth]{figures/matlab_main.png}
  \caption{The initial Matlab window upon launch}
  \label{fig_matlab_main}
\end{figure}
\vspace{0.1in}

\noindent
Assuming thing look like the above, you should be good to proceed.

%=======================================================================
\section{Simple Plotting}
%=======================================================================

%=======================================================================
\subsection{A First Bar Plot with Labels}

In the Command Window of Matlab a first simple plot can be generated with
the following commands:

\vspace{0.1in}
\begin{consoleverb}
;; wget https://oceanai.mit.edu/matlab/examples/example2A.m
&gt;&gt; x=0:5:100;      % Plot from [0,100] sampling at steps of 5            
&gt;&gt; y=x.^2;
&gt;&gt; hold on;
&gt;&gt; xlabel('x');
&gt;&gt; ylabel('x^2');
&gt;&gt; bar(x,y);
\end{consoleverb}

\vspace{0.1in}
\noindent
A separate pop-up window should appear looking something like:

\vspace{0.1in}
\begin{figure}[H]
  \centering
  \includegraphics[width=0.6\textwidth]{figures/plot2A.png}
  \caption{A simple bar plot of $y=x^2$}
  \label{fig_plot2A}
\end{figure}
\vspace{0.1in}

%=======================================================================
\subsection{Multiple Bar Graphs in a Single Plot}

Multiple plots may be overlayed in the same graph. Below is a simple example
that extends the first example.

\vspace{0.1in}
\begin{consoleverb}
% wget https://oceanai.mit.edu/matlab/examples/example2B.m
% open example2B.m
% &gt;&gt; example2B
x=0:5:100;      % Plot from [0,100] sampling at each integer
y=x.^2;
hold on;
xlabel('x');
ylabel('x^2');
bar(x,y,'r');
z=10000 - x.^2;
hold on         % prevents first plot from being overwritten
bar(x,z,'b');
hold off
\end{consoleverb}

\vspace{0.1in}
\begin{figure}[H]
  \centering
  \includegraphics[width=0.6\textwidth]{figures/plot2B.png}
  \caption{A simple bar plot of $f(x)=x^2$ and $f(x)=10000 - x^{2}$}
  \label{fig_plot2B}
\end{figure}
\vspace{0.1in}

%=======================================================================
\subsection{Using Transparencey in Bar Graphs with Multiple Plots}

In Figure \ref{fig_plot2B}, the plot rendered last obscures prior
rendered bars. We can add transparency to the bars to allow both
plots to be rendered fully. This is accomplished when invoking the
\var{bar()} command:

\vspace{0.1in}
\noindent
The simple command:

\vspace{0.1in}
\begin{consoleverb}
bar(x,y)
\end{consoleverb}
\vspace{0.1in}

\noindent
becomes:

\vspace{0.1in}
\begin{consoleverb}
bar(x,y,'r','DisplayName', 'f(x)=x^2', 'FaceAlpha',0.2);
\end{consoleverb}
\vspace{0.1in}

\noindent
Note that we give each bar plot a distinct color, e.g., red in
the example above with \var{'r'}. The \var{FaceAlpha} component
specifies the transparancy. Note in the example below, we specify
the legend location by choosing \var{'best'}, which lets Matlab
determine a reasonably good location of the legend relative to
the plotted data.

\vspace{0.1in}
\begin{consoleverb}
% wget https://oceanai.mit.edu/matlab/examples/example2C.m
% open example2C.m
% &gt;&gt; example2C
x=0:5:100;      % Plot from [0,100] sampling at each integer
y=x.^2;
hold on;
xlabel('x');
ylabel('f(x)');
bar(x,y,'r','DisplayName', 'f(x)=x^2', 'FaceAlpha',0.2);
z=10000 - x.^2;
title('A Bar Plot with Two Sets of Data')
hold on         
legend('Location', 'best', 'FontSize', 12);
bar(x,z,'b','DisplayName', 'f(x)=10,000 - x^2', 'FaceAlpha',0.2);
hold off
\end{consoleverb}

\vspace{0.1in}
\noindent
The result is in Figure \ref{fig_plot2C} below.

\vspace{0.1in}
\begin{figure}[H]
  \centering
  \includegraphics[width=0.6\textwidth]{figures/plot2C.png}
  \caption{A simple bar plot, using transparancy, of $f(x)=x^2$ and
    $f(x)=10000 - x^{2}$}
  \label{fig_plot2C}
\end{figure}
\vspace{0.1in}

%=======================================================================
\section{Plotting Data from a File}
%=======================================================================

%=======================================================================
\subsection{Preliminaries}

Ultimately we are interested in plotting data from missions. So we'll use
the Alpha mission as an example of this pipeline. Sticking with the
theme of bar plots, we'll use bar plots to convey how often certain
events happen. 

\vspace{0.1in}
\noindent
The pipeline will happen in three steps:

\vspace{0.1in}
\begin{packed_itemize}
\item Run the mission while creating an alog file of data
\item Pruned the alog file to isolate the relevant data
\item Modify the pruned data into a plottable form
\item Plot the data with Matlab
\end{packed_itemize}

\vspace{0.1in}
\noindent
The alpha mission is shown in Figure \ref{fig_alpha}. The vehicle will
simply traverse the five shown vertices repeatedly. In our example, the
logged data is from a mission where the vehicle traversed the points for
about 100 loops. 

\vspace{0.1in}
\begin{figure}[H]
  \centering
  \includegraphics[width=0.6\textwidth]{figures/alpha_coords.png}
  \caption{The alpha mission and coordinates of the five traversal
    vertices.}
  \label{fig_alpha}
\end{figure}
\vspace{0.1in}

\noindent
In the examples below, the \mvar{NAV\_X} and \mvar{NAV\_Y} data is
isolated. This is the \var{(x,y)} coordinates of the vehicle during
the traversal. 

%=======================================================================
\subsection{Extracting the Data}

After the mission is run, and the corresponding alog file has been
created, the following three steps are taken:

\begin{packed_itemize}
\item The alog file is reduced to a smaller alog file with isolated data
\item The \mvar{NAV\_X} and \mvar{NAV\_Y} data is isolated into two files
\item The frequency information of each variable is calculated
\end{packed_itemize}

\vspace{0.1in}
\noindent
After the Alpha mission completes, find the alog file generated by the
mission. We'll call this \var{alpha.alog}. The first step, a step of
convenience, is just to prune the alog file file down to contain only
the logged values for \mvar{NAV\_X} and \mvar{NAV\_Y}. We'll call this
new file \var{alpha\_xy.alog}.

\vspace{0.1in}
\begin{consoleverb}
$ aloggrep alpha.alog NAV_X NAV_Y alpha_xy.alog
\end{consoleverb}
\vspace{0.1in}

\noindent
In the next step we isolate the \mvar{NAV\_X} and \mvar{NAV\_Y} data
into their own files. The goal is to have each line in the file contain
only the nav information. A line in the alog file might look like:

\vspace{0.1in}
\begin{fileverb}
108.93710   NAV_X    uSimMarineV22   133.05592 
\end{fileverb}

\vspace{0.1in}
\noindent
The first column is the timestamp, the second column is the variable
itself, the fourth column is the source that published the value, and
the final column is the actual data. The goal is to have simply:

\vspace{0.1in}
\begin{fileverb}
133.05592 
\end{fileverb}
\vspace{0.1in}

\noindent
A file for each variable is made with:

\vspace{0.1in}
\begin{consoleverb}
$ aloggrep alpha_xy.alog NAV_X --v &gt; nav_x.log
$ aloggrep alpha_xy.alog NAV_Y --v &gt; nav_y.log
\end{consoleverb}
\vspace{0.1in}

\noindent
The \var{--v} argument will tell \cmd{aloggrep} to keep only the
fourth column of data, and also results in the header lines of the
alog file to be ommitted. See the documentation for \cmd{aloggrep}
or run with \var{--help} to see a quick list of options.

\vspace{0.1in}
\noindent
In the final step, the isolated \mvar{NAV\_X} and \mvar{NAV\_Y}
data are ingested to a utility call \cmd{alogbin}. This utility
will create distinct bins of \mvar{NAV\_X} and \mvar{NAV\_Y} values
and then tally the number of entries that fall in each bin.

\vspace{0.1in}
\begin{consoleverb}
$ alogbin --delta=10 nav_x.log nav_x_delta10.txt
$ alogbin --delta=10 nav_y.log nav_y_delta10.txt
$ cat nav_x_delta10.txt
55  3794
65  8156
75  1830
85  1719
95  1764
105  1588
115  1618
125  1683
135  1767
145  1828
155  3757
165  3795
175  3854
185  31
\end{consoleverb}
\vspace{0.1in}

\noindent
The bin data for \mvar{NAV\_X} is shown above. Note from Figure
\ref{fig_alpha} that the vehicle when traversing on the west side
of the region generally has a \mvar{NAV\_X} value around 60. We can
see the bin of $65$ has a large number of entries as a result. When
traversing on the east side of the region, the \mvar{NAV\_X} values
are in the range of $150$ to $180$. The bins in this range have
correspondingly high values.

\vspace{0.1in}
\noindent
This format of data is ripe for plotting with bar plots, shown next.


%=======================================================================
\subsection{A Bar Plot from Data Read from a File}
In most cases plotted data will be read in from a file. In this example
the data from the alpha mission described above will be plotted as
bar graph data. Namely the files:

\begin{packed_itemize}
\item \var{nav\_x\_delta10.txt}
\item \var{nav\_y\_delta10.txt}
\end{packed_itemize}


\vspace{0.1in}
\begin{consoleverb}
% wget https://oceanai.mit.edu/matlab/examples/example2D.m
% open example2D.m
% &gt;&gt; example2D
A=load('nav_x_delta10.txt');
B=load('nav_y_delta10.txt');
hold on;
bar(A(:,1),A(:,2),'r','DisplayName', 'NAV\_X', 'FaceAlpha',0.2);
title('Frequency of NAV\_X and NAV\_Y in the Alpha Mission')
hold on
legend('Location', 'best', 'FontSize', 12);
bar(B(:,1),B(:,2),'b','DisplayName', 'NAV\_Y', 'FaceAlpha',0.2);
hold off
\end{consoleverb}

\vspace{0.1in}
\noindent
The result is in Figure \ref{fig_plot2D} below.

\vspace{0.1in}
\begin{figure}[H]
  \centering
  \includegraphics[width=0.75\textwidth]{figures/plot2D.png}
  \caption{Bar plots showing the frequency of \var{NAV\_X} and
    \var{NAV\_Y} values from the Alpha mission.}
  \label{fig_plot2D}
\end{figure}
\vspace{0.1in}

\noindent
Aligning with with intuition, there are peaks for \mvar{NAV\_X} around
the values of 60 and the range 150-180 on the east region. For
\mvar{NAV\_Y} the peaks are around the values of -40 and -160. See Figure
\ref{fig_alpha}.

%=======================================================================
\subsection{Plotting Data from a File Named as Matlab Argument}

In this next example, the previous example is expanded to define a
Matlab function that accepts two data files as arguments:

\vspace{0.1in}
\begin{consoleverb}
function example2E(arg1, arg2)  % Note the function def w/ 2 args
A=load(arg1);                   % Arg1 is loaded
B=load(arg2);                   % Arg2 is loaded
hold on;
bar(A(:,1),A(:,2),'r','DisplayName', 'NAV\_X', 'FaceAlpha',0.2);
title('Frequency of NAV\_X and NAV\_Y in the Alpha Mission')
hold on
legend('Location', 'best', 'FontSize', 12);
bar(B(:,1),B(:,2),'b','DisplayName', 'NAV\_Y', 'FaceAlpha',0.2);
hold off
end
\end{consoleverb}

\vspace{0.1in}
\noindent
The previous plot can then be generated as below. In this example,
the data uses smaller bins, of four meters instead of 10.

\vspace{0.1in}
\begin{consoleverb}
&gt;&gt; example2E nav_x_delta4.txt nav_y_delta4.txt
\end{consoleverb}
\vspace{0.1in}

\vspace{0.1in}
\begin{figure}[H]
  \centering
  \includegraphics[width=0.75\textwidth]{figures/plot2E.png}
  \caption{Bar plots showing the frequency of \var{NAV\_X} and
    \var{NAV\_Y} values from the Alpha mission. Bins in this example
    are only 4 meters.}
  \label{fig_plot2E}
\end{figure}
\vspace{0.1in}


%=======================================================================
\subsection{Plotting Data from a File Named as Linux Shell Argument}

In our final example, we extend the previous example by showing how we can
invoke Matlab from the Linux/MacOS command line, passing in arguments
naming both data files to be plotted, and the image file to be created.
In this example, interactive Matlab will not be launched. The goal is to
be able to invoke examples like this from within a bash script at the
culmination of an automated experiment. We're looking for a line as
simple as:

\vspace{0.1in}
\begin{consoleverb}
$ matlab plotfile.m datafile1.txt datafile2.txt image.jpg
\end{consoleverb}

\noindent
The below example has three additions over the previous example:

\begin{packed_itemize}
\item The main function \var{example2F} now accepts three
  arguments. The first two arguments are the data files to be plotted,
  and the third argument names the image file to be created from the
  plotted data.
\item It contains a line of the form \var{saveas(gcf,file.png)} which
  will save the plot image to a file, named in the function argument
  \var{arg3}.
\item The final addition is to add the \var{exit} line immediately
  after the plot file has been saved. This automatic exit is needed to
  bring down Matlab automatically and return to the shell command
  line.
\end{packed_itemize}

\vspace{0.1in}
\begin{fileverb}
% wget https://oceanai.mit.edu/matlab/examples/example2F.m
% matlab example2F.m -r "example2F(\"nav_x_delta4.txt\", \"nav_y_delta4.txt\", \"image.png\")"
function example2F(arg1, arg2, arg3)
clf
A=load(arg1);
B=load(arg2);
hold on;
bar(A(:,1),A(:,2),'r','DisplayName', 'NAV\_X', 'FaceAlpha',0.2);
title('Frequency of NAV\_X and NAV\_Y in the Alpha Mission')
hold on
legend('Location', 'best', 'FontSize', 12);
bar(B(:,1),B(:,2),'b','DisplayName', 'NAV\_Y', 'FaceAlpha',0.2);
hold off
saveas(gcf, arg3)
exit
end
\end{fileverb}

\vspace{0.1in}
\noindent
To invoke this on the command line, run:

\vspace{0.1in}
\begin{consoleverb}
$ matlab example2F.m -r "example2F(\"nav_x_delta4.txt\", \"nav_y_delta4.txt\", \"image.png\")"
\end{consoleverb}

\vspace{0.1in}
\noindent
This invokes matlab, reading in the function defined in \var{example2F.m}.
The \var{-r cmd} component will invoke the \var{example2F} function with
two arguments surrounded by parentheses. The double-quotes around the whole
part is to shield the parenthesis from the command-line shell. 

\vspace{0.1in}
\noindent
The above example code and command line invocation should produce
plots exactly as in Figure \ref{fig_plot2E}.

\vspace{0.1in}
\noindent
In the final part of this example, we would like to disable the launch
of the Matlab interactive GUI and splash window normally displayed
upon launch. Two more command line args are added:

\vspace{0.1in}
\begin{consoleverb}
$ matlab -nodisplay -nosplash example2F.m -r  \
  "example2F(\"nav_x_delta4.txt\", \"nav_y_delta4.txt\", \"image.png\")"
\end{consoleverb}

\vspace{0.1in}
\noindent
Notes:

\begin{packed_itemize}
\item The arguments \var{-nodisplay} and \var{-nosplash} come {\em before}
  \var{example2F.m}.
\item The argument \var{-r} comes {\em after} \var{example2F.m}.
\end{packed_itemize}

% what happens when/if the function doesn't match the filename?


\end{document}

</pre></body></html>