\documentclass[xcolor=pdftex,dvipsnames,table]{beamer}
%\documentclass[10pt]{beamer}
\usepackage{beamerthemesplit}
%\usetheme{Berkeley}
\usetheme[
  outer/progressbar=foot,
  outer/numbering=none
]{metropolis}
%\usepackage[framed,numbered,autolinebreaks,useliterate]{mcode}
\usepackage[framed,autolinebreaks,useliterate]{mcode}
%  \usepackage[finnish]{babel}
\usepackage[english]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}% http://ctan.org/pkg/lm
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{xcolor}
\usepackage{hyperref}
\usepackage{tipa}
\usepackage[font=footnotesize,labelfont=bf]{caption}
\definecolor{links}{HTML}{2A1B81}
\hypersetup{colorlinks,linkcolor=,urlcolor=links}

\title{Lecture x: MATLAB - advanced use cases}

\author{ Heikki Apiola and Juha Kuortti} \date{\today}
\subtitle{\small Parallel computing with Matlab's toolbox}

\institute[Aalto] % Your institution as it will appear on the bottom of every slide, may be shorthand to save space
{
Aalto University \\ % Your institution for the title page
\medskip
\textit{juha.kuortti@aalto.fi, heikki.apiola@aalto.fi} % Your email address
}
\begin{document}
\maketitle

\section{Parallel Computing Toolbox}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{frame}[fragile]
\frametitle{General concepts}
The PCT (Parallel Computing Toolbox) allows exploitation of multicore
processors, and it supports the use of computer clusters 
%(resources of connected computers) 
and graphics processing units (GPUs).

\textbf{Goals of parallel computing}

\begin{itemize}
  \item \textbf{Efficiency}: Gain remarkable speedup distributing a computational task
between several computing units, which work simultaneously with parts of the task. (Decompose your task into independent parts that may or may not communicate
with each other.)
 \item \textbf{Memory}: Solve larger problems than can be done in one computational unit.
\end{itemize}
\end{frame}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}[fragile]
\frametitle{Difficulties with parallel computing}
%\mcode{>> }
\begin{itemize}
 \item Computer architectures evolve $\Rightarrow$ programming techniques have 
to evolve as well.
 \item 
  How the data has to be stored and shared between computational resources
 \item 
  In some cases it may be difficult to achive satisfactory speed 
improvements, especially when there's need to communicate between
different computational units.
 \item Writing and debugging parallel code is often difficult
\end{itemize}
\end{frame}
%\end{document}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}[fragile]
\frametitle{What Matlab's PCT is good for}
%\mcode{>> }
\begin{itemize}
 \item 
Relatively easy to write parallel programs using just minor extensions of the
language.
 \item 
\textbf{Limitations:} Special parallel computing languages provide more flexibility (but require more programming effort).
 \item 
Prototype parallel code by working on your local (at least two kernel) 
computer before running on a remote cluster. 

\end{itemize}
\textbf{Note:} The cluster on which you run jobs must be running the 
{\tt MATLAB} Distributed Computing Server, such as our \emph{Triton}.

\end{frame}
%\end{document}  OK
\begin{frame}[fragile]
\frametitle{Parallel pool, workers, client}
%\mcode{>> }
\textbf{Terminology:}
\begin{itemize}
 \item  \emph{Client}: Matlab-session running on your laptop or remote computer (like Triton).
 \item \emph{Workers} are MATLAB computational engine processes running on
laptop or remote cluster. Workers don't have a MATLAB desktop, they can communicate between themselves and the client.
\item \emph{Pool}: A set of workers forms a parallel pool. A pool can be started
with the command  \mcode{>>parpool} and closed with \mcode{>>delete(gcp)}
 
%\item
\end{itemize}
\end{frame}
%\end{document} OK
\begin{frame}[fragile]
\frametitle{Example: Open pool, doc parallel.Pool}
%\mcode{>> }
\begin{lstlisting}
>> p=parpool
Starting parallel pool (parpool) using the 'local' profile ...
connected to 2 workers.
p = 
 Pool with properties: 
           Connected: true
           NumWorkers: 2
              Cluster: local
        AttachedFiles: {}
    AutoAddClientPath: true
          IdleTimeout: 30 minutes (30 minutes remaining)
          SpmdEnabled: true
>> p.NumWorkers
ans =
     2
\end{lstlisting}
\end{frame}
%\end{document}  OK
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}[fragile]
\frametitle{Controlling pool, profile}
%\begin{lstlisting}
%   parpool  % 
%\end{lstlisting}
\begin{itemize}
\item \mcode{parpool} -  Open parallel pool with default profile.
\item \mcode{parpool(n)} -  Open parallel pool with n workers.
\item \mcode{delete(gcp)} -  Close pool (deault idle time: 30 min).
%\item 
%\item
\end{itemize}
Most of the parallel computing constructs (\mcode{parfor,spmd},etc.) 
to be discussed, will automatically open a pool with default profile.

\textbf{Note:} The parallel profile can also be viewed and edited by  opening
the ``Parallel''-tab at the bottom right part of the ``home''-view of the desktop.
For more, see the Mathworks' pages which lead us to our next topic:

\href{https://se.mathworks.com/help/distcomp/spmd.html}{https://se.mathworks.com/help/distcomp/spmd.html} and
\href{https://se.mathworks.com/help/distcomp/run-code-on-parallel-pools.html}{https://se.mathworks.com/help/distcomp/run-code-on-parallel-pools.html}

\end{frame}
% \end{document}  OK
\section{Parallel computing constructs}

\begin{frame}[fragile]
\frametitle{spmd,parfor,...}
We will be concerned with 
\begin{itemize}
\item \mcode{spmd} : Single program multiple data
\item \mcode{parfor} : parallel for-loop
\item \mcode{parfeval} (possibly) : parallel evaluation 
\end{itemize}
%\end{frame}
%\end{document} NO

The \mcode{spmd}-construct gives the user full control and understanding of the
parallelization process. It allows the same code to be run on multiple 
workers with each worker using different data, which might for example
be different parts of the same array.
%\end{frame}
%\end{document} NOK
\mcode{parfor} is technically simplest, just replace \mcode{for} by 
\mcode{parfor}.
%\end{frame}
%\end{document}  OK
MATLAB decides how to distribute the computation among the workers.
Some limitations compared to \mcode{for}: nested loops are not allowed
and some loop index limitations exist, etc.
\end{frame}
%\end{document} NOK
\begin{frame}[fragile]
\frametitle{Toolbox specific parallelization tools}


Some toolboxes, like the \emph{optimization toolbox} provide 
support for parallel computation, provided that the PCT is installed 
(like with us). 

There the user just needs to
turn a ``parallel switch on'', and observe the difference in performance.

For example, in the \textcolor{blue}{Optimization Toolbox} there is a setting
\mcode{'UseParallel',true} in the \mcode{options} structure passed to the 
solver. (Compare to ODE-solvers for a similar structure for controlling 
tolerances etc.)

\end{frame}
%\end{document} NOK
%%%%%%%%%%%%%%
\begin{frame}[fragile]
\frametitle{Single program, multiple data -- spmd}

The \mcode{spmd} statement defines a block of code to be run simultaneously
on multiple workers that should be reserved using \mcode{parpool.}

The first couple of slides contain quotations of the text in:

\href{https://se.mathworks.com/help/distcomp/spmd.html}{https://se.mathworks.com/help/distcomp/spmd.html}

%\textbf{Assumption:} You have the \emph{Parallel Computing Toolbox} installed
The general form of an spmd (single program, multiple data) statement is:

\begin{lstlisting}
% nlabs=2 % on laptop
% parpool(nlabs)   % Open pool if not open already
spmd
    statements
end
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
\frametitle{Open pool, \mcode{parpool,labindex,myPool.NumWorkers}}
MATLAB executes the spmd body statements on \mcode{nlabs} workers 
simultaneously. 

First open a pool of MATLAB workers using \mcode{parpool} or have your 
parallel prefences allow the automatic start of a pool.

Inside the body of the spmd statement, each MATLAB worker has a unique value of \mcode{labindex}. 

Opening the pool by \mcode{>>myPool=parpool} uses the default
number of workers stored in \mcode{myPool.NumWorkers}. \\ 
Alternatively one can start
 by \\ 
\mcode{>>nlabs=16; parpool(nlabs)}\\ 
in case there are \mcode{nlabs} 
workers available in the pool.
%while \mcode{numlabs} denotes the total number of workers 
%executing the block in parallel. 

Communication functions such as \mcode{labSend} and 
\mcode{labReceive} can transfer data between the workers.
\end{frame}

\begin{frame}[fragile]
\frametitle{Examples of spmd}
\begin{lstlisting}
nlabs=2;       % laptop
% nlabs=24;    % Triton (default 24)
parpool(nlabs) % Opening the pool takes some time.
spmd
  % build magic squares in parallel
  q = magic(labindex + 2);
end
\end{lstlisting}
The variable \mcode{q} is a \textcolor{blue}{Composite object}. 
The value \mcode{q\{k\}} is the value stored in the $k^{th}$ worker,
whereas  \mcode{q\(k\)} is the cell array of values stored in the 
$k^{th}$ worker.\\
\textbf{Note:} The indexing of a composite object is exactly similar
 to that of a \emph{cell array}.

\verb_ for ii=1:length(q);figure,imagesc(q{ii});end_




\end{frame}
\begin{frame}[fragile]
\frametitle{Composite objects}

\textbf{Note:} As the last line showed us, the composite object \mcode{q} remains available
even outside the \mcode{spmd}-block as long as the pool is open.

\begin{lstlisting}
>> q
q = 
   Lab 1: class = double, size = [3  3]
   Lab 2: class = double, size = [4  4]

>> q{1:nlabs}
ans =
     8     1     6
     3     5     7
     4     9     2
ans =
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1
\end{lstlisting}

\end{frame}
\begin{frame}[fragile]
\frametitle{Composite objects to cell arrays, results from workers to client}

As noted above,
the variable \mcode{q} ``behaves'' like a cell array. 
After closing the pool it isn't available (the workers are gone).
Here's how to store the contents of q ``permanently'' into the client:

\begin{lstlisting}
Q=cell(1,nlabs);        % Create a cell array Q.
Q(1:nlabs)=q(1:nlabs);  % Copy q into cell array Q.
% Q=q;                  % Not allowed.
delete(gcp)   % q no more available, Q remains.
cellplot(Q), figure
surf(Q{nlabs})  % Plot (surf) the last (largest) magic. 
\end{lstlisting}
\end{frame}
%%%%%%%%%%%%%%%
\begin{frame}[fragile]
\frametitle{Run the same script in Triton}

\begin{verbatim}
slogin -X -lscip triton.aalto.fi
Mat...xLab...y2018
$ cd $WRKDIR
$ mkdir USER_OWN_DIR
module load matlab
\end{verbatim}
\begin{lstlisting}
>>parpool 
  Pool with properties: 
            Connected: true
            NumWorkers: 24
            Cluster: local
            ...
>>spmd
>> q = magic(labindex + 2);
>>end
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
%\frametitle{Continued ...}
\begin{verbatim}
>> q(1:6:24)
ans =
  1×4 cell array
   {3×3 double}{9×9 double}{15×15 double}{21×21 double}
>> surf(q{24})
\end{verbatim}
\textbf{Note:} The ``protype code'' (on laptop) and the remote computer 
code (on Triton) need no change, the latter, using Triton default uses 24 workers.
\begin{lstlisting}
>> Q=cell(1,24);
>> Q(1:24)=q(1:24);
>> delete(gcp)   % close pool 
                 % q is gone, Q remains.
\end{lstlisting}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}[fragile]
\frametitle{Spmd-example: Numerical integration}
%^^^^ ^ ^ ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ powerhatcapsup
%\mcode{>> } \begin{lstlisting} \end{lstlisting}
% \begin{itemize} \item \end{itemize}
% \textcolor{blue}{\texttt{}}

Task: Integrate numerically: $\int_0^1 \frac{4}{1+x^2} dx$, \\
decomposing the interval of integration ``Labwise''.

\begin{center}
\includegraphics[height=5cm, width=8cm]{paralleldemo_quadpi_mpi_01.png}
\end{center} 

\end{frame}
\begin{frame}[fragile]

Define the variables a and b on all the workers, but let their values
depend on \mcode{labindex} so that the intervals 
$[a, b]$ correspond to the
subintervals shown in the figure.\\
\textbf{Note}: The code in the body of the \mcode{spmd} statement is
 executed in parallel on all the workers in the parallel pool.
\begin{lstlisting}
p=parpool  % If not open. (Take a while.)
numlabs=p.NumWorkers
spmd
    a = (labindex - 1)/numlabs;
    b = labindex/numlabs;
    fprintf('Subinterval: [%-4g, %-4g]\n', a, b);
end
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]

Let's work on this both on Laptop and Triton:\\

\verb+spmd_example1_numint.m+  
{\tiny (Link doesn't work here, use index.html)}

\begin{lstlisting}
p = parpool;  % Start parallel pool.
numlabs=p.NumWorkers
%%
spmd
    a = (labindex - 1)/numlabs;
    b = labindex/numlabs;
    fprintf('Subinterval: [%-4g, %-4g]\n', a, b);
end
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{More examples on spmd}

\begin{itemize}
\item
Find all local min/max and/or zeros of a univariate function.
Exercise on this.
\item Multivariate optimization, ``domain decomposition''
\item ``Method of lines'' for certain PDE's, semidiscretization, uses a 
large number of calls to ODE-solvers. (Matlab-demo exists.)
\item ``Parameter sweep'' on differential equations, optimization and many others. (One example on diff, equ. included as a link.)
\end{itemize}
Some of the above may be well (or better) suited to \mcode{parfor} 
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}[fragile]
\frametitle{Parallel for -- parfor}
The easiest way to use the parallel toolbox is to replace \mcode{for} by 
\mcode{parfor}.
%\begin{}
A \mcode{parfor}-loop splits the computation inside the loop among available 
workers in an automatic way, in an unspecified order. 

Restrictions:
\begin{enumerate}
\item
The loop variable must increase in steps 1.
\item
No data dependencies between different iterations. Example:
\begin{lstlisting}
s=ones(10,1);
parfor i=1:10,s(i)=i^2             % Allowed
parfor i=2:10, s(i)=s(i-1)^2+i^2    % Not allowed
\end{lstlisting}
\item
A \mcode{parfor}-loop can't contain another for-loop, but
it can contain a call to a function that contains a parfor loop
\end{enumerate}

%\end{}


\end{frame}
\end{document} %%% THIS IS THE END %%%%%%%%%%%%%%%%

%%%%% TEMPLATE FRAME : %%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}[fragile]
\frametitle{}
%^^^^ ^ ^ ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ powerhatcapsup
%\mcode{>> } \begin{lstlisting} \end{lstlisting}
% \begin{itemize} \item \end{itemize}
% \textcolor{blue}{\texttt{}}
\begin{itemize}
\item
\textcolor{blue}{\texttt{>> help ode45}}
 \begin{itemize}
  \item
\textcolor{blue}{\texttt{ode23}}

  \end{itemize}
\end{itemize}
\end{frame}









%%%%%%%%%%% MODEL template %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}[fragile]
\frametitle{FT}
%\mcode{>> }
\begin{itemize}
 \item The command \mcode{>>save} 
\end{itemize}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{columns}[c]
\column{0.8in}
\textbf{textmat.dat}:\\
%\begin{lstlisting}
%\framebox{
\begin{lstlisting}
1 2 3 4
5 6 7 8
\end{lstlisting}
\column{2.2in}
%In Matlab:
\begin{lstlisting}
>> load -ascii textmat.dat
>> % You can omit -ascii here
>> textmat
textmat =
     1     2     3     4
     5     6     7     8
\end{lstlisting}
\end{columns}





%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{ Numeric data in a text file}
  If you have straight up numerical data in an array, with no missing
  values, you can use simply use \texttt{load}.

 
\end{frame}




\section{Importing data: advanced}


\begin{frame}{*read-functions}
  There are various functions for importing data (\texttt{lookfor
    read}). For our basic examples we'll use \texttt{csvread} and
  \texttt{dlmread}.

  Both are designed to read delimited textfiles, \texttt{csvread} if
  the delimiter is comma, and \texttt{dlmread} for a general delimiter.

  The issue with both is that they can only read \textit{numerical
    data}. If your file contains something else --- if your file
  contains something else, you'll need to use the options to exclude
  the offending entries.
\end{frame}

\begin{frame}{Exercise}
  Download the files \texttt{electricity.csv} and \texttt{formants.csv}.

  \begin{itemize}
  \item Try reading in the numerical data of \texttt{gasPrices.csv}
    using function \texttt{csvread}. The calling convention is as
    follows \texttt{csvread('fileToRead',startRow,StartCol)} --- look at
    the file to decide good place to start reading.
  \item Then try reading \texttt{formants.csv}. The delimeter is now
    semicolon, so \texttt{csvread} won't work. Use help page to work
    out how to make \texttt{dlmread} work.
  \end{itemize}
\end{frame}



\begin{frame}{The GUI-way}
  Whenever you have a file containing data you wish to import, try
  dragging and dropping the file onto the command window. If the file
  is recognised by MATLAB as importable, an import wizard will appear
  giving you a plethora of options to import the data.
\end{frame}


\begin{frame}{One final read function}
  MATLAB has a data type that can contain various types of
  entries. Table datatype is a fairly recent addition, and is
  specifically created for the purposes of data-analysis.

  You can use function \texttt{readtable} to read a csv-file to a
  table.
\end{frame}

\begin{frame}{Demonstration of table datatype}
  \begin{itemize}
  \item Read in file \texttt{electricity.csv} using \texttt{tableread}.
  \item Separate the variables from descriptors
  \item Separete the dates from data.
  \item Extract the numerical data.
  \item Plot the data
  \end{itemize}


\end{frame}


\section{The Case of Missing Data}



\begin{frame}{How to handle missing data}

  \begin{itemize}
  \item Leave the data as is and ignore any NaN elements when
    performing calculations. Maintains the integrity of the data but
    can be difficult to implement for involved calculations.
  \item Remove all NaN elements from the data.  Simple but, to keep
    observations aligned, must remove entire rows of the matrix where
    any data is missing, resulting in a loss of valid data.
  \item Replace all NaN elements in the data.  Keeps the data aligned
    and makes further computation straightforward, but modifies the
    data to include values that were not actually measured or
    observed.
  \end{itemize}

\end{frame}

\begin{frame}[fragile]{Case 1: Ignoring NaNs}
  When performing any operation containing a NaN, the result will
  always be either NaN, or false, depending on context.

  Especially:
  \begin{lstlisting}
    A = [1,2,3,4,3,1,3,4,5,nan,13,5];
    avg = mean(A) % will be nan
  \end{lstlisting}

  To avoid this, either use functions called \texttt{nan*}
  (e.g. \texttt{nanmean}), that automatically omit nans, or look for
  appropriate flags in the documentation:
  \begin{lstlisting}
    avg = mean(A,'omitnan')
  \end{lstlisting}
\end{frame}


\begin{frame}{Case 2: Hunt'em down}
  We can also identify all corrupted entries, and just delete them
  from our data entirely. This can lead to huge data loss, but
  uncertainty involve in guessing data will be less.

  You can locate the corrupted entries using either \texttt{isnan} or
  \texttt{ismissing} functions. \texttt{isnan} deals specifically with
  NaN values, while \texttt{ismissing} is more general, allowing you
  to specify the erroneous values.
\end{frame}

\begin{frame}[fragile]{Case 2 continued}
  \begin{lstlisting}
    data = readtable('electricity.csv');
    idx = ismissing(data); % logical indices of missing values
    idxR = any(idx,2); % look for all the rows that are missing data
    data(:,idxR) = []; % delete all the rows that have data missing
  \end{lstlisting}
\end{frame}


\begin{frame}{Case 3: Try and Guess}
  Sometimes data is too spotty to remove all corrupted entries ---
  sometimes we know that data is by nature continous. In such cases we
  can make educated guesses as to what the data would be, and obtain
  more data points. This is called \textit{interpolation}.

  From previous course, we remember the \texttt{interp*}-functions,
  that did the interpolation. For data science, there is a useful
  helper-function called \texttt{fillmissing}, that is much more
  forgiving about the sampling points (e.g. you can omit the eval
  points, or you can use dates etc.)
\end{frame}



\begin{frame}[fragile]{Case 3 continued}
  \texttt{fillmissing} has a lot of options, as one might
  imagine. Help page is your friend, as usual.
  \begin{lstlisting}
    data = readtable('electricity.csv');
    usage = data{:,2:end}; % extract the numerical data
    dates = data.Date; % extract the date
    intUsage1 = fillmissing(usage,'linear','samplepoints',dates);
    intUsage2 = fillmissing(usage,'nearest'); % assumes even sampling
  \end{lstlisting}


\end{frame}

\section{Some additional examples}


\begin{frame}[fragile]{Curve fitting - Example}
  The very basic example --- fitting a trend line on a dataset.
  \begin{lstlisting}
    % create some data
x = 5:21;
y = 3.5*x+4 + 4*randn(size(x))+5;
plot(x,y,'ro')
%% the hardcore mathy way
V = [x',ones(size(x'))];
coeff = V\y';
xfit = linspace(x(1),x(end),256);
yfit = coeff(1)*xfit + coeff(2);
plot(x,y,'ro',xfit,yfit)
%% The more consistent way
p = polyfit(x,y,1);
plot(x,y,'ro',xfit,polyval(p,xfit))

  \end{lstlisting}
\end{frame}


\begin{frame}[fragile]{Underfitting a polynomial}
  Let's try to fit a polynomial to US census data.

  \begin{lstlisting}
% create time vectors -- dense and sparse
t = 1900:10:1990;
tt = 1900:1:2010;
pop = [76 92 106 122 132 150 179 203 226 248];
% for show, try the maximum degree polynomial
P = polyfit(t,pop,length(pop)-1);
plot(tt,polyval(P,tt));
% It fails -- as is expected
P = polyfit(t,pop,3);
plot(tt,polyval(P,tt));
  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]{Nonlinear fitting}
  \begin{lstlisting}
x = 20:65;
y = [0 0 0 1 2 5 15 65 71 79 55 48 46 26 25 25 16 9 18 ...
    8 8 6 4 6 5 5 2 6 4 2 0 0 1 1 1 0 1 1 0 0 0 0 0 2 0 0];

f = @(beta,x)beta(1)*x.^9 .* exp(-beta(2)*x);
fobj = @(lam)norm(f(lam,x)-y);
beta0 = [1 -1];
betaOpt = fminsearch(fobj,beta0);

%%

xfit = linspace(20,65,128);
plot(xfit,f(betaOpt,xfit),x,y)
  \end{lstlisting}
\end{frame}


\begin{frame}[fragile]{Noise gating --- example}
  \vspace{-0.5cm}
  \begin{lstlisting}
% Create and visualize the data
t = linspace(0,0.5*pi,256);
carrier = sin(2*pi*t) + sin(6*2*pi*t);
plot(t,carrier)
%% add some noise
noisySignal = carrier + 2*rand(size(carrier))-1;
plot(t,carrier,t,noisySignal)
%% Go to frequency spectrum
X = fft(carrier);
plot(abs(X))
Xnoisy = fft(noisySignal);
plot(abs(Xnoisy))
%% Identify the noise component, and gate it out
Xnoisy(abs(Xnoisy)<30) = 0;
%% Go back to time domain
xnew = real(ifft(Xnoisy));
plot(t,carrier,t,xnew)
  \end{lstlisting}
\end{frame}
\end{document}
