https://gitlab.com/opensourcedave/matlabcourse

Download zip

Unzip (on windows click and drag contents to a new directory)

In matlab cd to unzipped directory

(On windows you can click on an empty space of the address bar to get the address. Highlight it, then copy it. Then in matlab paste it after the cd command)

More complex mathematical operations, want to keep track of everything

Run as one big function or script

Conditional statements

Loops

Any questions on things I covered?

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

- <C-/> - comment a whole line with

- <C-T> - Uncomment a line with

Sections marked by %%

Essetial editor tab buttons

- Run (F5)

- Run section (ctrl enter)

- Run and advance (ctrl shift enter)

Most everything has a shortcut

Hover over buttons and wait to see shortcuts

OR

preferences->keyboard->shortcuts

__Basic__

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

__RUN__

Click the run button

__Comment stuff__

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

__RUN__

__Suppress Output__

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

__RUN__

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
1) = -b + sqrt(b^2-4*a*c)/(2*a);
x(2) = -b - sqrt(b^2-4*a*c)/(2*a);
x(
%save as "quadratic"
%assign some variables
=1;
a=0:
b=0;
c
quadratic
=1
a=-1
b=-2
c quadratic
```

Difference between a function and a script

- Other than input and output, functions create variables in different workspaces

- Good practice for writing a function - start out in a script then make it a function

Lets turn our script into a function

`function x = quadratic(a,b,c)`

Name of function needs to be the same as the filename*

Comment section - what it does, what inputs and outputs mean

Remember: matlab will not warn you if there are multiple functions of the same name

- If you have multiple functions of the same name, matlab will choose for you without warning

- Use 'which' function

Also comment the body of your function for later reference

__ADD IN COMMENTS__

__TEST HELP__

__IF ELSE ELSEIF__

Conditional statements allow for certain code to be ran if a certain condition is met.

In a single if-statement, you can have as many conditions as you like. The first must always be 'if'.

'elsif' and 'else are optional

__Basic__

imagine name as an input to a function

```
='DNW'
nameif strcmp(name,'DNW'):
='David;
firistelseif strcmp(name,'JLB'):
='Justin'
firstelse
='unkown'
firstend
```

__Example with numbers__

imagine a & b as inputs to a function

```
=randi(10,1)-5;
a=randi(10,1)-5;
bif a==b %if this condition is met
disp('Values are the same') %run this nested indented code
=3;
celseif a==(b*-1) %This condition in only checked if the previous statement was false
disp('Values have the same magnitude');
elseif a==0 %This condition in only checked if the previous statements were false
disp('A is zero');
else %no semicolon requred
disp('Values are not the same');
end
```

__ORDER OF STATEMENTS__

Multiple conditions may in fact be true, but the entire block (starting with 'if' ending with 'end') will erminate after the indeted code associated with the first match is met.

Therefore, it may be necessary to further condition your code, or use multiple if statements.

Semicolons do nothing on lines containing 'if', 'elseif', 'else', or 'end'

```
=5
aif a==5
disp('a is five')
elseif abs(a)==5
disp('magitude of a is five')
end
```

__SIMPLIFY TO SINGLE 1 OR ZERO__

Be careful about dimensions with if statements

Matlab will use the default of all() on your matrix

```
=randi(2,10)-1;
a=sum(sum(randi(2,10)-1));
aif a
disp('True')
else
disp('False')
end
=randi(2,2)-1;
aif all(a)
disp('All a are 1')
elseif any(a)
disp('Some a are 0')
end
```

Indentation is good form, but not required

If you are running the matlab editor, this is usually done automatically

```
function [b,ind] = isalpha(in)
%determine whether string is contains only letters
=['abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'];
alphaV=alphaV(:);
alphaVif any(~ismember(in,alphaV));
=1;
belse
=0;
bend
end %This end is required if multiple functions are in the same file
```

__MULTILPLE FUNCTIONS & SCOPE__

If I include multiple functions to a single file, your workspace is only aware of the function with the same name as the filename. However, that function itself is away of the additional functions.

```
% Put the below function in the same file as 'isalpha'!
% REmove the alphaV lines
function A = alphaV()
=['abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'];
A=A(:);
Aend
%By including a secondary funciton in the same file, we have limited the scope of this additional function.
%That is, it can only be called on by code within the file.
```

__COMBINING LOGIC__ & __SHORT CIRCUITING__

You can combine logical statements in your if statments using & and |

just like we did with basic logic.

But, you should also use && and || instead

```
#Defaults
clear
~exist('A','var') || isempty(A) % two symbols is a "short-circuity", no error
~exist('A','var') | isempty(A) % this line should result in an error
exist('A','var') && ~isempty(A) % this one won't create an error
exist('A','var') & ~isempty(A) % this one will create an error
if ~exist('A','var') || isempty(A)
disp('A is not assined to a value. I''m setting it to a default value')
=0;
Aend
%This type of behavior is useful for functions with optional inputs
function my_plot(x,y,color,shape)
if ~exist('color','var') || isempty(color)
='k';
colorend
if ~exist('shape,'var') || isempty(shape)
='.';
shapeend
plot(x,y,[color shape])
end
,y)
my_plot(x,y,[],':') my_plot(x
```

__LOOPS__

Loops allow you to repeat code as many times as you want.

For loops let you repeat that code, but each time it repeats, you can have a variable (commonly i) take on a specific number

```
disp(10)
pause(1)
disp(9)
pause(1)
disp(8)
pause(1)
disp(7)
% ...
disp(10)
pause(1)
%VS
=1:10
rfor i = r
disp(i)
pause(1)
end
```

__VISUALIZE A HISTOGRAM__

Assigning a temporary variable from a row vector on each iteration

```
:
Visualizing a sampling procedure as a movie=[]
Afor i = 1:100 %We are repeating the indented code 100 times. Systematically i will take on values 1:100 with each iteration
=[A; randn(10,1)]
A
histogram(A)drawnow
pause(.1)
end
```

__ANY ROW VECTOR__

You don't have to have i = 1:100. You can replace 1:100 with any row vector!

```
for i = randi(10,1,10)
display(['Draw ' num2str(i) ' cards.'])
input('Press Return');
end
```

__THINK IF YOU CAN DO YOUR OPERATION WITHOUT A LOOP FIRST__

- much faster to run and write

__OTHERWISE__

Preallocate - assining placeholder values in matrix/cell before its populated with desired values

- Makes sure that you have enough memory before you run

(Breaks on first line rather than later)

- Guarantees the proper dimensions

__Preallocation speeds things up__

```
clear
tic
=0;
xfor i = 2:100000000
i)=x(i-1)+10;
x(end
toc
=zeros(1,100000000);
xtic
for i = 2:100000000
i)=x(i-1)+10;
x(end
toc
```

__Preallocation can avoid waiting to find out if you have enough memory__

```
for i = 1:10000
:,:,:,i)=zeros(100,100,100)*i;
A(end
zeros(100,100,100,10000)
for i = 1:10000
:,:,:,i)=zeros(100,100,100)*i;
A(end
```

octave

Very practical statistics example

Putting lots of concepts together

Example of what you can really do with matlab.

__Bootstrap Theory__

- Estimating a population mean from some samples

- Say height of UPenn body

- How confident can we be in our estimate?

- If there is a lot of variation in the data, we need more samples

- How much is the variation in our sample biasing our estimate?

__Resampling__

- If we resampled our data, how different would the mean be?

- To avoid sampling bias with our resampling, lets resample many times.

- Look at the distribution of means

- If variation of our resampled means is large - we can't be too confident in our estimate.

```
function [SEM MM]=SEMboot(data,nBootS,bPlot)
% Bootstrapping to get Standard error of the mean
% be used for confidence intervals for the sample mean
if ~exist('data','var') || isempty(data)
,I]=data_gen();
[dataelse
I=[]
end
% BOOTSTRAP
=zeros(length(data),1);
Mfor i=1:nBootS
=datasample(data,length(data),'Replace',true);
yi)=mean(y);
M(end
=std(M);
SEM=mean(M(:));
MM=[MM-(SEM*1.96) MM+(SEM*1.96)]; %95 confidence intervals
CI
if bPlot
,M,SEM,CI,MM,I)
Plot(dataend
end
```

octave

```
function [data,I]=data_gen()
% Generates example data if you have noen
I=rand(1)*3+5;
=normrnd(I,1,100,1);
dataend
function []=Plot(data,M,SEM,CI,MM,I)
% HANDLE PLOTTING
figure(1)
subplot(1,2,1)
hold off
,ctrs]=hist(data);
[countsbar(ctrs,counts)
=max(counts);
y=[y y];
Yhold on
plot(CI,Y,'r','LineWidth',5)
plot(MM,y,'kd')
title('Data')
axis square
hold off
subplot(1,2,2)
;
histogram(M)axis square
=['Mean: ' num2str(mean(data)) newline ...
name'SEM: ' num2str(SEM) ];
if ~isempty(I)
=[name newline 'True = ' num2str(I)];
nameend
title(name);
end
```

__Until not true__

```
=0
awhile a>10
=a+1
adisp(a)
end
```

__GO UNTIL BREAK__

```
while true
=input('Please input your name: ','s');
rif isalpha(r)
break
else
disp('Invalid name. Try again')
end
end
OR
while true
=input('Please input your name: ','s');
rif ~isalpha(r)
disp('Invalid name. Try again')
continue % Ends current iteration and begins just under while loop
end
break
end
```

__CONTINUE & BREAK IN FOR LOOPS__

If using continue on a for-loop, will start on the next iteration value

```
for i = 1:5
if mod(i,2)
disp([i ' is even'])
continue
end
i ' is odd'])
dis([end
```

```
function tlines = txt2lines(fname)
% Opens a text file, returns each line of the file as an element in a cell
=fopen(fname); %opens file
fid= fgetl(fid);%reads file into variable
tline = cell(0,1);
tlines while ischar(tline)
end+1,1} = tline;
tlines{= fgetl(fid);
tline end
fclose(fid); %closes file
```

__LOAD DATA__

`='addquestions.txt'; fname`

switch-case is like if-statments but more convenient for simple conditions especially if you have a lot of them.

```
function [txt] = num2literal(num)
switch abs(num)
case 1
='one';
txtcase 2
='two';
txtcase 3
='three';
txtcase 4
='four';
txtcase 5
='five';
txtcase 6
='six';
txtcase 7
='seven';
txtcase 8
='eight';
txtcase 9
='nine';
txtcase 0
='zero';
txtcase{Inf,NaN} %Having a case like this is saying Inf | NaN
='infinity';
txtotherwise
if isalpha(num)
disp('String contains non-number') %We will change this later
end
end %Note only one end
if num<0
=['negative-' txt];
txtend
%switches are
```

In this tutorial we have covered about 99% of what is commonly used in matlab

There are many options that we didn't cover in the functions that we went over, so check the documentation

If you want to maintain what we've learned here, you should make your next project in matlab/octave