MATLAB Part 1 - Matlab Environment

Dave White

Matlab Philosophy

Non-technical syntax for scientific computing
Everything is an array (atomic type/object)
No need to download other packages

Matlab is great for

Cons

This Lecture's Goals
Use matlab graphing calculator - plotting
Matrices - batch processing of data

Terminology nopres

Array

Vector or matrix or tensor, that holds a number or character

5x1 array

1
2
3
4
5

2x3 array

1 3 5
2 4 6

Elements numbered down rows, then columns (RC)

Why

They are compact, easy to organize.
They can be computationally efficent (especially using linear algebra).
You can avoid most looping procedures.

Intuition

A table with:

Workspace

Workspace variables

A=3
<click on A in workspace>    %Get more info and edit if not too big
clear                        %Clears your variables

Clutter

somelongtexthere<C-c>        %<c-C> gets you a new command-line
clc                          %Clears display

History
Press Up and Down to browse history.
Use comments to keep notes of what you are doing.

Completion

variableA=1
vari<Tab>                    % Use tab completion to make things faster

Operators

Arithmetic

% Anything after a percent sign is a comment - it will not be evaluated
8+5                          % + is an operator
8*5                          % Multiplication
(5+3)/2                      % Order of operations apply!

Boolean

b=3
a=-3
b >= abs(a)                   % Is b greater than abs(a)?
b <= abs(a)                   % Is b less than abs (a)?
b == 3                     % Is b equal to 3? Notice to equal signs instead of 1.
b ~= 3                     % Is b not equal to 3?
b <= 4                       % Is b less than or equal to 4?
b >= 4                       % Is b greater than or equal to 4?
true==1                      % True and 1 are are the same
false==0                     % False and zero are the same
~true==false                 % ~ takes the compliment of a test (flips the sign)
c = b==4                   % Assigning result of logical test

Combined logic

~(b <= 4)                    % Is b less _greater_ than or equal to 4?
b==5 | abs(a)==3             % OR
b==5 & abs(a)==3             % AND
(b==3 & abs(a)==3 ) | c      % Grouping

R and Python

Python & R
! Negation operator
R
TRUE boolean symbol*
FALSE boolean symbol*
<- binding operator
Python
True boolean symbol*
False boolean symbol*

Calling functions

Functions take inputs

sqrt(5)                      % Functions have parentheses
abs(-3)
abs(3-7)                     % Inputs can be simplified before being evaluated in functions

Rounding
Many ways to 'round' a number

round(7/2)                   % Normal rounding
floor(7/2)                   % Round down
ceil(7/2)                    % Round up
fix(7/2)                     % Round towards zero

Zero Inputs

pi()
pi                           % If function takes zero inputs, parentheses are optional

Multiple inputs

times(3,3)                   % Multiple inputs separated by a comma
mod(10,2)                    % Modulus is the remainder of division
                             % 10 divided by 2 has a remainder of zero

Getting Help

Can't remember a function
Tab completion
Google

help <function>
doc <function>

DO EXERCISE 1

Namespaces part 1

sqrt and our variables are in the same namespace!

sqrt(5)                      % Functions have parentheses

3=sqrt

sqrt(5)

which sqrt

clear sqrt

which sqrt

Symbols for functions are easily rebound!

Anonymous Functions

f=@(x) x.^2+3                % With 1 input
f(4)
g=@(x,y) x.^2+y.^2+3         % With 2 inputs
g(4,5)

binding a function to symbol f
f is NOT a variable, its a funciton.

Integration

integral(f,0,1)              % Integrate using anonymous functions

python

f=lambda x: x**2 + 1
f(3)

regular functions act as anonymous ones

f <- funciton(x) x^2 + 1
f(3)
size(A) % also an array

Namespaces

General (not global)
Local (within functions or workspace)
Global (rarely used)

All namespaces include general

General namespace auto-populated by things in your path

Local overrides general
Local namespaces only created by creating fucntions

f=@(x) x+3
x=5
y=3
f(y)

f=@(x,f) x+3 + f
f(3,5)

Files & Directories

File Manager
.m file extension specify scripts and functions (plaintext format)
.mat specifies data (binary format)
using the browser is limiting - I never use it - become apparent next time

Directories/Folders
Where are we saving to?

pwd         %lists current directory
ls          %lists files in current directory

Things that matlab is aware of

  1. Things in your current directory (pwd)
  2. Variables in your workspace
  3. Command History
  4. Things in your path

Create a directory and move into it
Save functions F and g from before in filename 'myfunctions'
f=@(x) x.2+3 With 1 input
g=@(x,y) x.2+y.2+3 With 2 inputs

Absolute vs relative directories

Absolute begin with a slash in unix
Absolute begin with drive then backslash
Difference between windows and mac/linux/unix
/Users/dambam %mac
/home/dambam %unix
C:\ %windows
Relative directories are relative to where you are, they don't start with a slash

cd('C:\')             %absolute
cd('Documents\test1') %relative

matlab

Loading and saving

Save/Load/Delete

save('myvariables')          % No error means successfully saved
clear                        % Clears all variables from workspace
load('myvariables')          % Restores workspace that was saved

save('myvariables','a','b')  % Optional inputs save only variables A & B
load('myvariables')
clear
load('myvariables')
delete('myvariables')        % .mat is required

NOTE
'save' and 'load' take filenames and variable names as inputs.
If i tried saving without quotations

save(myvariables,a,b)

matlab would try read myvariables, a, and b as variables themselves

Path

  1. Current directory
  2. Directories that are listed in your path variable

Add directories to your path under HOME-> ENVIRONMENT-> PATH
Anything file/directory in your path can be autocompleted and loaded without an explicit structure

WARNING: If you have multiple files of the same name, matlab will use the first one it finds without any warning
Functions and variables often look the same

which <filename>    % Lists which one matlab will use

Editor

More than just a couple of lines, use the editor
You can use any editor you like as well.

Comments start with % - won't be ran

Sections marked by %%

Essetial editor tab buttons

Most everything has a shortcut
Hover over buttons and wait to see shortcuts
OR
preferences->keyboard->shortcuts

Script

Scripts are appended to whatever they are ran in.
Same namespace, scope extended

create a new script
saved with .m

Writing Scripts

Basic

Just write your commands in the editor
a=100
b=100
f=@(x) x^2-6
f(a)
b(a)

RUN
Click the run button

Comment stuff

%Initial Values
a=100
b=101
%A Quadratic function
f=@(x) x^2-6

%% evaluating functions
f(a) % run a
f(b) % run b

RUN

Suppress Output

%Initial Values
a=100;
b=101;
%A Quadratic function
f=@(x) x^2-6;

%% evaluating functions
f(a); % run a
f(b); % run b

RUN

Excercise

See if you can implement the quadratic function from before as a script

%Runs just like inputting a bunch of commands in the commandline
%All variables will end up in your workspace
%Writing a script is the best way to begin writing a function

%Lets write a script that solves a quadratic equation
x(1) = -b + sqrt(b^2-4*a*c)/(2*a);
x(2) = -b - sqrt(b^2-4*a*c)/(2*a);

%save as "quadratic"
%assign some variables
a=1;
b=0:
c=0;
quadratic

a=1
b=-1
c=-2
quadratic