% 1. Exercise Neuroinformatics
%
% based on the Matlab Help file
% Based on the script by Vitek Zyka and Hynek Bakstein and the text for the course
% X33ROB
%
% The MathWorks Inc. (http://www.mathworks.com/)
% MATrix LABoratory

% Table of Contents :
% - Introduction to Matlab
% - How to work and how to predict
% - Matrices, constants, simple calculations
% - Indexing matrices
% - Program constructions
% - Why not use a loop

%%% Intro--------------------------------------------------------------
% Matlab :
% - Numerical calculations, analyses; symbolic calculations
% - complete programming language, parts in C/C++, Forman
% - block simulations (Simulink)
% - visualization of 1D, 2D, 3D data, images, video, 3D objects
% - simple GUI

% Programming efficiency:
% + strong domain support
% (toolboxes: http://www.mathworks.com/products/products_by_category.jsp
% real time, image processing, optimizations, neural networks,
% signal processing, splines, wavelets, statistics, mapping,
% symbolic computations, video)
% - interpreted code
% + debugging, profiler (html output)
% + programming in C/C++, Fortran
% Other:
% - high price
% Conclusion:
% -> +++ development, research; - applications

% Basics -------------------------------------------------------------
% GUI overview:
% - command window
A = 1
% - workspace + variable editor
% - command history
% - current dir

% Running code + shortcuts  -----------------------------------------------------
%
% F5 - run the current active m-file in the editor
% F9 - run marked code in the console
% Ctrl-Enter - run current code section (separated by double percent sign %% )
% Ctrl-d - open source of the currently marked function in the editor

% Working with directories ----------------------------------------------------

cd C:\users\
cd('C:\users\')
cd ..

ls
dir

%%% Getting help -----------------------------------------------

help sum

doc sum % graphical help

lookfor fourier

%% % Notation of simple matrices ------------------------------------------

% All variables are matrices. 
% Vectors and scalars are matrices of special dimensions.

% Vectors (case sensitive) 
F = [1,2,3] % carta separates columns -> radical vector
F = [1 2 3] % equivalent to the previous entry

f = [1;2;3] % hyphen separates rows -> column vector

% the semicolon at the end of a line suppresses the output
f = [2;3;4];

% Matrix (for clarity it is useful to separate with a line)
k = [9, 8, 7; 6, 5, 4; 3, 2, 1; 0 -1 -2]

l = [cos(0.5) -sin(0.5); sin(0.5) cos(0.5)] % watch out!
L = [cos(0.5), -sin(0.5); sin(0.5), cos(0.5)]

K = [k  k+100; k+200  k+300] % spojovani bloku

% sequences
1:6
1:2:6
.5:-.1:0

x = [1:5;2:6]

%% % Info on variables --------------------------------------------

size(k)
size(k,2) % variable, number of dimension
length(k)
whos

exist('k')

clear('K')

%%% Generating simple matrices -------------------------------------

Z1 = zeros(2,5) % number of rows, number of columns
Z2 = ones(1,7)
Z3 = eye(3)
Z4 = diag([1 2 3 4 5])

%%% Special constants -------------------------------------------------

ans          % answer
inf          % 1/0 infinity
nan          % 0/0 not-a-number

isfinite(Z4)
isnan(Z3)

pi
i, j         % do not use for variables, better use k,l,m or ii, jj for cycles 

%% % Indices, conversions  ---------------------------------------------

% The first dimension is always rows, second is columns

k
k(1,2)           % two parameters -> (noncontinuous) coordinates (sub)
k(2,[2 3])
k(2,[1 3])
k(2,[1:3])
k(2,1:3)
k(2,1:end)
k(2,:)

k([1 4 5])         % single parameter -> vector coordinate (ind)
k([1;4;5])
k([1 2;3 4;8 9])

k([2, 3],[3, 2])
k(sub2ind(size(k),[2 3],[3 2]))
ind2sub(size(k),[1 2;3 4;8 9])

kk = k;
kk(:,2) = []     % all rows + second column only

k(:)             % matrix -> vector

%% % Generating random numbers ---------------------------------------

r1 = rand(1,1000); % uniform distribution
r2 = randn(100,100); % normal distribution
r3 = randi([5,50],10,10);

hist(r1)
hist(r2(:))
 
%%% Simple transformations -----------------------------------------------

% transpozition
L'
% matrix by scalar multiplication
p = 5 * k
% matrix multiplication
s = k * k'
% element-wise operation
p .* k                 % .* .+ .- .^ ./

% division
% A*x = y
A = [2 -3; 3 1]
y = [1; 7]

x  = A\y    % left division     x  = pinv(A)*y
xa = y'/A   % dight division    xa = y'*pinv(A)
xb = A/y'   % right division   xb = A*pinv(y')

%inversion
inv(L)

% comparison operators
ki = k>5       % ==  ~=  >  <  <=  >=  &  |  ~

% associative selection
find([1 0 -5])
ind = find(k>5)
[s u] = find(k>5)
k(ind)

kk = k;
kk(kk>5) = NaN

%%% Matrix operations -------------------------------------------------------

sum(A) % column sums (across rows)
sum(A')

sum(A,2) % sum across given dimension (1-rows, 2-columns, 3...)

min(A)
[u v] = max(A)
min(A(:))

%%% Loops and programming constructs --------------------------------------------------
%for l = [1:5]
for l = [1,3,5,2]
  l
  a(l) = l^2;
end
% i=1:20; a= i.^2;

% if
a = [1 2];
if( any(a>1) )
  disp('t')  
else
  disp('f')
end
% elseif any all

if( any(a>1) ), disp('t'); else disp('f'); end

while(l)
    pause % waits for a key
    break % ends the cycle
end
%% Why to avoid cycles-------------------------------------------

% Note: cycles got dramatically faster since 

tic
x = [1:10000000];
toc

tic
for k = 1:10000000
if(x(k)>30)
x(k)=0;
end
end
toc

tic; x(x>30)=0; toc
% see additional examples towards the end of the file


%% Visualizations -------------------------------------------------------------
% 1D
t = 0:pi/10:2*pi;
y = sin(t);
plot(y)
plot(t,y)

% multiple plots n one figure
y2 = sin(t-.25);
y3 = sin(t-.5);

f = figure;
plot(t,y,'r.',t,y2,'',t,y3,'--o')

% another option
plot(t,y,'r')
hold on
plot(t,y2,'g')

% other options at the end of the file


%% Other data types ------------------------------------------------

% retezec
s = 'ahoj';
disp(s);
                                                                
% multidimensional matrices
o(:,:,1) = [1 2; 3 4];
o(:,:,2) = [5 6; 7 8]

% structure
dog.variety  = 'bulldog';
dog.name = 'Abraxas';
dog
dog.variety

% matrix of structures (one-dimensional)
dog(2).variety  = 'maxipes';
dog(2).name = 'Fik';

% call array: non-homogeneous matrix structure
animal = {};
animal{1} = dog(1);
animal{2} = dog(2);
animal{3} = 'giraffe'
animal{2}

% cell array (non-homogeneous matrix)
p1 = 'row';
p2 = 'a longer row';
p  = [p1; p2]; % throws error

p  = {p1; p2};
P1 = p{1,1} % !!! - curly brackets to get the content, rather than 1x1 cell
P2 = p(1,1) % get 1x1 cell array
whos P1 P2

%% % Bonuses
% ===========================================================================
% BONUS: 3D data visualization (function z = f(x,y))
figure(2);
[X,Y] = meshgrid(-8:.5:8,-5:.2:5);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
mesh(X,Y,Z)
pause
surf(Z)
pause
plot3(X,Y,Z)


% BONUS: MORE EXAMPLES FOR INDEXING -----------------------------------------
n = 10000;
% Task: Production of a checkerboard (n dimension)
% Write an efficient program that creates a matrix with zeros and ones on
% "black and white" boxes on the matrix, respectively


% Task: Column numbers
% create a square matrix A of size n, with a square in each column
% contain only the number of the given column, e.g. for n=3 would be A=[1 2 3; 1 2 3; 1 2 3]
% compare the speed of your solution with the solution using the meshgrid() function


% Task: create a matrix such that x(i,j) = max(i,j)

%% % Definition of custom functions ------------------------------------------
% 
% - the file name must be the same as the function name
% - the function can contain subfunctions (only for own use)
% - subfunctions have to be defined at the end of the file
% - the first block of comments in the function is printed if
%   help(functionName) is called
% - 

% Create a new file larger.m
larger(1,10)

function x = larger(a,b)
% LARGER returns 1 if the first parameter is greater
% this is the place for the function description - prediction
% x = greater(a,b)
% a,b - scalars

    if(nargin~=2) % kontrola poctu parametru
        error('Two parameters required')
    end

    if(a>b)
        x = true;
        return
    end
    x = false;
end