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)
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
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
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
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
THINK IF YOU CAN DO YOUR OPERATION WITHOUT A LOOP FIRST
OTHERWISE
Preallocate - assining placeholder values in matrix/cell before its populated with desired values
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
Difference between a function and a script
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
Also comment the body of your function for later reference
ADD IN COMMENTS
TEST HELP
Very practical statistics example
Putting lots of concepts together
Example of what you can really do with matlab.
Bootstrap Theory
Resampling
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