<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.Matlab04}
\wikidoc{auth=mikerb@mit.edu}
\helplevelsubsec

%===================================================================
% Build the Cover Page in an environment style easy for wiki parsing
\begin{labcover}
\labtitle{Matlab Plotting Lab 04 - C-style function args in Matlab}
\vspace{0.2in}
\labcourse{Pavlab: Passing in C-style args into Matlab functions}
\vspace{0.5in}
\labpng{0.25}{figures/matlab.png}
\vspace{0.25in}
\labdate{Aug 15th, 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}
%===================================================================

Matlab functions, especially those that serve the purpose of creating
a plot, can have many input parameters. In this lab we cover how to
pass arguments into a Matlab function in the style familiar to C/C++
programmers. A pattern is shown for providing an unlimited number of
arguments, and parsing and handling each argument.

\begin{labinfo}
%\labinfoheader{Topics:}
\begin{packed_itemize}[2]
\item Goal - Passing in C-style command line args into a Matlab function.
\item Goal - Invoking the plotting function from within a shell script.
\item Goal - Using a shell script to launch an experiment and auto generate a 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     (or similar depending on your install)
\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{A Plotting Function with Configuration Parameters}
%=======================================================================

%=======================================================================
\subsection{A Ploting Function First with No Configuration Params}

Below is a plotting function that will read plottable data from a file
and produce a .png image file

\vspace{0.1in}
\begin{fileverb}
% wget https://oceanai.mit.edu/matlab/examples/example4.txt
% wget https://oceanai.mit.edu/matlab/examples/example4A.m
% open example4A.m
% &gt;&gt; example4A
function example4A()
  clf
  A=load("example4.txt");
  hold on;
  errorbar(A(:,1),A(:,2),A(:,3),A(:,4),'b');
  title("An example Title 123")
  xlabel("xval")
  ylabel("yval")
  ax = gca;
  ax.YAxis.Exponent = 0;
  hold off
  saveas(gcf, "example4.png")
end
\end{fileverb}

\vspace{0.1in}
\noindent
To run this:

\vspace{0.1in}
\begin{consoleverb}
$ matlab example4A.m    (in bash)
&gt;&gt; example4A            (in Matlab)
\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.75\textwidth]{figures/plot4A.png}
  \caption{A simple errorbar plot.}
  \label{fig_plot4A}
\end{figure}
\vspace{0.1in}

%=======================================================================
\subsection{Passing in the Data and Image Files as Arguments}

To improve on the above function, (a) the name of the data file, (c)
the plot title, and (c) the name of the image file, will be passed as
arguments (\var{arg1,arg2,arg3}) to the function:

\vspace{0.1in}
\begin{fileverb}
% wget https://oceanai.mit.edu/matlab/examples/example4.txt
% wget https://oceanai.mit.edu/matlab/examples/example4B.m
% open example4B.m
% &gt;&gt; example4B example4.txt "A More Dynamic Title" example4B.png
function example4B(arg1, arg2, arg3)
  clf
  A=load(arg1);
  hold on;
  errorbar(A(:,1),A(:,2),A(:,3),A(:,4),'b');
  title(arg2)
  xlabel("xval")
  ylabel("yval")
  ax = gca;
  ax.YAxis.Exponent = 0;
  hold off
  saveas(gcf, arg3)
end
\end{fileverb}

\vspace{0.1in}
\noindent
To run this:

\vspace{0.1in}
\begin{consoleverb}
$ matlab example4B.m    (in bash)
&gt;&gt; example4B example4.txt 'A More Dynamic Title' plot.png   (in Matlab)
\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.75\textwidth]{figures/plot4B.png}
  \caption{A simple errorbar plot, create with dynamic arguments.}
  \label{fig_plot4B}
\end{figure}
\vspace{0.1in}

%=======================================================================
\subsection{A Better Way of Passing in Arguments}

In the above example, the Matlab function is a bit more
general-purpose in that the input data, title and name of the image
file are not hard-coded into the function. A couple things are still
not ideal. (1) the order of the arguments matters. This is prone to error
and a more civilized function would be more forgiving on the ordering. (2)
This approach is unwieldy if we have say 8 input parameters. It starts to
look overly complex and the ordering of arguments woudl be even harder to
keep straight.

\vspace{0.1in}
\noindent
For those with background in C/C++, and familiar with the
\var{main(argc,argv)} style of parameter passing, a more generalized approach
for handling arguments is preferred. Matlab does support this. The example
provided below shows how this is done and is structured in a way that C/C++
programmers may find comfortably familiar.

\vspace{0.1in}
\noindent
In the below example, the label for the x and y axes may also be passed as
arguments. 


\vspace{0.1in}
\begin{fileverb}
% wget https://oceanai.mit.edu/matlab/examples/example4.txt
% wget https://oceanai.mit.edu/matlab/examples/example4C.m
% open example4C.m
% &gt;&gt; example4C --file=example4.txt --title='Realy Cool Title" \
%              --img=example4C.png --xlabel=Elements --ylabel=Rate
function example4C(varargin)
  %------------------------------------------
  % Part 1: Init default values
  %------------------------------------------
  file1="";
  imgfile="tmp_result.png";
  titlestr="No title";
  xlabelstr="X";
  ylabelstr="Y";
  
  %------------------------------------------
  % Part 2: Process args
  %------------------------------------------
  for i=1:length(varargin)
    argi=varargin{i};
    if(startsWith(argi,"--file1="))
      file1=extractAfter(argi,"--file1=");
    elseif(startsWith(argi,"--img="))
      imgfile=extractAfter(argi,"--img=");
    elseif(startsWith(argi,"--title="))
      titlestr=extractAfter(argi,"--title=");
    elseif(startsWith(argi,"--xlabel="))
      xlabelstr=extractAfter(argi,"--xlabel=");
    elseif(startsWith(argi,"--ylabel="))
      ylabelstr=extractAfter(argi,"--ylabel=");
    else
      disp("Bad Arg:" + argi);
    end
  end

  clf
  A=load(file1);
  hold on;
  errorbar(A(:,1),A(:,2),A(:,3),A(:,4),'b');
  title(titlestr)
  xlabel(xlabelstr)
  ylabel(ylabelstr)
  ax = gca;
  ax.YAxis.Exponent = 0;
  hold off
  saveas(gcf, imgfile)
end

\end{fileverb}

\vspace{0.1in}
\noindent
To run this:

\vspace{0.1in}
\begin{consoleverb}
$ matlab example4C.m    (in bash)
&gt;&gt; example4C --file=example4.txt --title='Really Cool Title' \
             --img=plot.png --xlabel=Elements --ylabel=Rate     (in Matlab)
\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.75\textwidth]{figures/plot4C.png}
  \caption{A simple errorbar plot, utilizing very dynamic argument handling.}
  \label{fig_plot4C}
\end{figure}
\vspace{0.1in}



%=======================================================================
\section{Invoking the Plotting Function from a Bash Script}
%=======================================================================

In this section, an example bash "plot script" is provided. A plot
script represents a stage of the post-mission or benchtesting pipeline
that (a) ingests the raw results, e.g., alog files, and (b) processes
those files into a format suitable for plotting, and (c) invokes
Matlab (or similar) to produce a plot in the format of a \var{.png}
file.




\end{document}

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