Some introductory slides on this, together with 3 exercises. (answers)
- There are
- data stored in variables (*)
- functions which operate on the variables(**)
- (*) variables are usually 1. matrices, 2. cell arrays, or 3. structures.
Here is an example "script" (set of Matlab commands in a file) showing how to create these basic data types:
full list of data types (for reference)
The values in a matrix are of the same numeric type. The most common numeric types are 'double', 'uint8', and 'logical'.
- 'double' is the default numeric type. it stores a 64-bit precision floating-point number.
- 'uint8' is an unsigned integer with 8-bit precision (0 to 255). jpeg images read with imread() come in this format.
- 'logical' can only be 0 or 1. These values arise as a result of a conditional test, e.g. (2==0) evaluates to logical 0.
Another useful type is 'char', which is used to make strings
- Strings begin and end with a single-quote (' = apostrophe). A double quote (") to delimit a string results in an error.
- To put a single quote in a string use two single quotes in a row (''). (not a blackslash escape)
- matlab does not have string interpolation. To put a number in a string, it's best to use sprintf(). One can also use the weaker num2string().
- (**) functions are top-level (no namespace, io.file.open etc.).
Which functions you can call depends on your matlab "path". (that is, matlab will search for a file somewhere in a directory entered in your path which implements the function).
Here is an example function: egfunc.m
Also note that you can count the input arguments with "nargin", and accept a variable number of arguments using "varargin".
Here is an example function using those two: mymessage.m
Large sets of functions are often grouped together into "toolboxes". You don't need to do anything special to access a file from a toolbox. Sometimes - other people have posted just the function you are looking for on "matlab central"; though beginners will probably find everything they need inside Matlab's massive library or one of the standard toolboxes.
- Indexing (accessing some elements) of a matrix is very important in matlab.
Here is a script showing how to index: egindex.m
- Finding sums, means, etc. along various dimensions of a matrix is very useful in matlab:
Here is a script showing how to do that: eguseful.m
- Control flow: if, while, and for statements.
Here is a script which shows some basic control flow: egcontrol.m
NOTE: In Matlab, it is often more efficient to not use loops, and to cast operations in matrix format (operating on entire rows, columns, or matrices at a time).
- Plotting figures is very important in matlab.
- Here is a list of more functions you may want to use, type "help [functionname]" at the Matlab prompt to explore these.
imread, imwrite, imshow, imagesc, colormap, conv2, conv
dir, system, clear, save, whos, profile
ttest, ttest2, kstest, kstest2, binomcdf, normcdf, normpdf
- Finally, you can refer to these to learn: