%% Theory2: % MSc MATLAB Crash Course: Cell-arrays, functions and programming. % % Originally written by Nick Hale, Oct 2013. % Extended by Mohsin Javed, Oct 2014. % Modified by Behnam Hashemi and Hadrien Montanelli, Sep. 2016. rmpath functions %% CELL ARRAYS C = cell(3) C{1} = 1 C{2} = 2 C{2,1} = zeros(2) % the same as C{2} here C{2,2} = rand(3) % the same as C{5} C{3,3} = [1; 2; 3] %% RECAP: ANONYMOUS FUNCTIONS % Anonymous function allowed us to write very simple functions in one line: f = @(x) cos(pi*x) - exp(cos(x)); %% FUNCTIONS % For more complicated functions, or those with more than one output, we % typically write these in their own m-files. These then take the following % format: % function [out1, out2, ...] = function_name(in1, in2, ...) % FUNCTION_NAME . % [OUT1, OUT2, ...] = FUNCTION_NAME(IN1, IN2, ...) returns . % % Author name, Date. % % % % end edit myfunc.m %% Example f(2) f(3) myfunc(2) myfunc(3) % In particular, we emphasize again that Matlab _isn't typed_, this means that % any of the inputs can be a double, a string, a cell, etc., and that there is % no need to declare variables (as you would in C or FORTRAN). %% Example % Let's look at an example by writing a short code to solve a quadratic: edit functions/quadform.m %% % Let's execute it: quadform(2, -1, -1) % The script isn't in the same folder as the quadform code we just wrote, so I % can't acess it from here! %% PATH, ADDPATH, PATHTOOL % Matlab stores internally a 'path' which is a list of folders in which it will % look for functions. path %% addpath functions % 2*X^2 - X - 1 = 2 (X-1)(X + 0.5): quadform(2, -1, -1) %% pathtool %% NESTED FUNCTIONS % % Nested functions live somewhere between anonymous functions and m-files. They % are useful when short snippets of code are used in a number of places, and % you don't want to copy all the variables across to another m-file. % function y = function_name(x) % FUNCTION_NAME . % Y = FUNCTION_NAME(X) returns . % % Author name, Date. % % % % y1 = nested_function(x1); % % % % % function y = nested_function(x) % % % % end % end %% Example edit functions/quadform2.m %% % Let's execute it: quadform2(2, -1, -1) %% NARGIN() and NARGOUT() % % These commands tell you how many inputs or outputs were passed to a function. % They can be used in conditional statements to alter the behavior of the % function. %% VARARGIN() and VARARGOUT() % % If you don't know how many inputs or outputs you expect to a function, you can % declare them using VARARGIN() and VARARGOUT(): % % function varargout = function_name(varargin) % edit functions/quadform3.m %% % Let's execute it: x = quadform3(2, 1) %% x = quadform3(2, -1, -1) %% [x1, x2] = quadform3(2, -1, -1)