% A Brief Introduction to Matlab
%
% This script is intended to introduce novices to
%  the Matlab environment. It is meant to be executed 
%  line-by-line, allowing for interactive exploration
%  of data types and whatnot. 
%
% Notes:
%  - odd spaces between cells for demonstration purposes!
%  - navigate between cells using <ctrl>+<down> <ctrl>+<up>
%
% by Jason Taylor (18 Nov 2011 + subsequent small updates)
%    MRC Cognition and Brain Sciences Unit
%    Cambridge, UK
%      email: <first>.<last>@mrc-cbu.cam.ac.uk
%    School of Psychological Sciences
%    University of Manchester
%      email: <first>.<last>@manchester.ac.uk

















%% SOME TIPS:
%
% GENERAL:
%  %         indicates a comment (ignored)
%  ;         (@ end of command) means don't print result
%  
% COMMAND WINDOW:
%  >>        this is the 'prompt': type commands here!
%  <up>      scrolls through command history, last-to-first
%             - all commands if you've typed nothing
%             - matching commands if you've typed something
%  <tab>     completes (e.g., mea<tab> gives 'mean'...)
%  <ctrl+c>  stop command
%  clc       clears command window
%  clear     clears variables from workspace (use with caution!)
%
% EDITOR:
%  %%        begins a new 'cell' (section of code)
%  <F9>      executes a highlighted line (or set of lines)
%  <ctrl+dn> go to next cell
%  <ctrl+up> go to prev cell






%% STARTING MATLAB

% Windows: Start->Matlab or double-click icon
%  * Note: can set startup preferences in shortcut
%           e.g., starting dir, -nojvm, etc.

% Linux Machines: 
%  Type 'matlab'
%  Type 'matlab <-options>'
%  Type 'spm <options>'      *wrapper script @ CBU
%  ... see demo, Russell's talk, Yaara's talk















%% Matlab & Linux

% Within matlab, linux commands can be run:
%  ! <command>
% or:
%  [status,result] = unix(<command>);

% e.g.:
! hostname
[status,hname] = unix('hostname');
if ~status, fprintf(1,'You are connected to %s\n',hname); end






































%% PATH
%   = search path Matlab uses to identify and execute
%     commands, functions, scripts...

% Report the contents of path:
path

% Add a directory to your path (prepend):
% >> addpath <path/to/directory>

% e.g., (linux version):
addpath /imaging/jt03/demo/scripts/
% or, append:
addpath /imaging/jt03/demo/scripts/ -END

% e.g., (windows version):
addpath \\cbsu\data\imaging\jt03\demo\scripts

% edit /home/<user>/matlab/startup.m

% Find the path of a particular function/script/command:
%  which <command>
which mean








%% THE WORKSPACE
%   = variables that are currently available to be used
%      by you (or by functions as input)

% Two ways to get the mean of a vector:
mean([4.1 3.3 4.8]) % <-this will give you the answer

% or,
x = [4.1 3.3 4.8]   % <- this will store the values 
mx = mean(x)        %     and the answer in variables














%% ... and now you can:

% - get other summary statistics, 
sx = std(x)
[min(x) max(x)]

% - plot
bar(x);
hold on; 
plot(2,mx,'ko','MarkerFaceColor','r','MarkerSize',12);

% - write it to a text file:
dlmwrite('x.txt',x,'\t');

% - save as a .mat file
save('x.mat','x');
clear x
load('x.mat')

% - etc.
figure; imagesc(rand(64,64)*std(x));










%% Some WORKSPACE Commands:

% List names of all variables in the workspace:
who

% List names, size, class of all variables in the workspace:
whos

% List ... of a subset of variables in the workspace:
%  whos [<variablenamelist>] 

% eg.,  
whos x
whos *x*     % <- '*' = wildcard

% Clear (all or subset of) variables out of workspace:
clear x








%% NUMERIC VARIABLES:

% Scalar values:
x = 42

% Vectors:
xvec  = [1 2 3 4 5 6]
xvec2 = 1:6                    % equivalent

% Matrices:
xmat  = [1 2 3; 4 5 6; 7 8 9]
xmat'

% N-dimensional arrays:
x3d = cat(3,xmat,xmat+10)

% Get size of each dimension:
size(xmat)

% Indexing:
xmat(:,[2 3])  % <- all rows, columns 2 and 3







%% MATHS (  + - * / ^  )

% Add/subtract
42+10
x + 10
y = x - 10

% Multiply/divide (scalar):
y = x * 5
y = x/2

% Multiply/divide (vector):
y = xvec .* [10 100 1000 10 100 1000]
y = xvec/(xvec(1))

% etc.:
y = sqrt(x^3)






%% LOGIC & LOGICAL INDEXING (  == ~= > < & && | ||  )

% Logic:
v = xvec*10
v > 30
v > 30 & v ~= 60

% Find index of 'true' (or nonzero, generally):
find(v>30 & v~=60)

% Use logical index:
v(v>30 & v~=60)
v(find(v>30 & v~=60))   % equivalent

% Use logical index on a different variable:
xvec(v>30 & v~=60)

% Valid numbers:
v(end) = NaN
v(end) = 0/0
v(~isnan(v))



%% STRINGS AND CELLS (  ‘’ {} isstr iscell findstr strmatch )

% Strings:
mystring = 'hello world'
xstr = '42'   % not the same as x = 42 (see 'isnumeric')
% but:
xnum = str2double(xstr) % is now numeric!

% String matching:
findstr('o',mystring)
findstr('world',mystring)

% Cell arrays (may mix types, sizes):
mycell = {'hello' 'world'} % both string
xcell = {x xstr} % one numeric, one string
xcell(2) % returns a cell
xcell{2} % returns *contents* of the cell
isstr(xcell(2)) % no, it's not a string
isstr(xcell{2}) % yes, it is a string!

% Cell-string matching:
strmatch('world',mycell)











%% STRUCTURES (  struct fieldnames isfield  )
%   ** SPM users take note (SPM.mat)   **

% Struct:
S = struct()
S.subj = 's01'
S.sex  = 'male'
S.age  = 27
S.data = [1 2 3 4 5 6]
isfield(S,'age')
fieldnames(S)

% Adding layers:
S(2).subj = 's02';
S(2).sex  = 'female';
S(2).age  = 19;
S(2).data = [11 12 13 14 15 16]

% Extracting data:
[S.age]
{S.sex}





%% LOOPS & CONDITIONAL STATEMENTS:

% FOR loop:
for i = 1:10
    i*10
end

% For loop & IF statement:
for i = 1:10
    if i>3
        fprintf(1,'subject %02d\n',i); 
    end
    keyboard % pause execution, let user 
             % explore workspace.
             % use 'dbcont' to continue
             % or 'dbquit' to exit
end

% WHILE loop:
i = 0;
while i<3
    i = i+1;
    fprintf(1,'subject %02d\n',i);
end













%% Loops continued

% Switch ... case ... otherwise ...
for i=1:length(S)
 switch S(i).sex
  case 'male'
    fprintf(1,'He is subject %s.\n',S(i).subj);
  case 'female'
    fprintf(1,'She is subject %s.\n',S(i).subj);
  otherwise
    fprintf(1,'Subject %s''s sex was not recorded.\n',S(i).subj);
 end
end




















%% That's enough for now!

% On to scripts and functions...

% If you got here via the presentation, type 'return' + [ENTER] at the
% command line, or highlight and <F9>:

return































