Compact Summary of MATLAB language (MATrix LABoratory) A mixture of Fortran and C This compact summary assumes you know either Fortran or C and can program in at least one of those languages. MATLAB is an interpreter, not a compiler. Multiple files may be used in a single execution and files are interpreted as needed when the files are in the current workspace. Files have an extension ".m" Files are plain ASCII text and may be edited within MATLAB or created and edited using your favorite editor. For experimentation, you can type statements into the command window and they are interpreted as you type them. Execute a file in the current workspace using: run filename-without-.m Each line is a statement. The percent character, %, makes the rest of the line a comment. Ending a statement with a semicolon prevents printing of that statement during interpreting. Multiple statements may be on one line when separated by semicolons. To continue a line, end it with three periods. Variables must start with a letter and may include upper case, lower case, digits and underscore. Case sensitive. All variables are arrays of some size and dimension. A single number is a one element one dimensional array. Variables are not declared. Unless otherwise specified all variables are IEEE Standard 754 64-bit floating point. Complex numbers are a pair of 64-bit floating point values. Key words listed below are not allowed as variables. Functions and commands should not be used as variables, yet, if used, can be "recovered" using the 'clear' command or 'builtin' function. A few of the many functions and commands are listed below. Key Words: (all lower case) break case catch continue else elseif end for function global if otherwise persistent return switch try while A few commands to avoid as variables clear format dir regexp close import load pack save There are hundreds of functions, here are some you might recognize: sin cos tan asin acos atan atan2 exp log log2 sinh cosh tanh asinh acosh atanh sign abs fix log10 round floor ceil sum prod length rem mod eval feval and or not xor any all find eig max ode23 bitand bitor bitcmp bitxor exists isempty inv ode45 input disp fprintf There are some special names for values: See more constants below, such as pi 3.14159... When following a number with no intervening space: i sqrt(-1) or i unused and exp(i*t) j same as i In functions: nargin is number of arguments the caller provided nargout is number of outputs the called requested In try - catch: lasterr is the cause of the error (If you define and use any special names or functions, you may get the builtin definition back with clear pi ) Expressions are built in the normal way from variables and operators. The standard convention for parenthesis applies. Subscripts use the parenthesis as in Fortran rather than brackets as in C. Because variables may be arrays of any size and dimension, be careful. The operators in precedence order are: (precedence number first) 1 ( ) Grouping parentheses including function calls 2 .' Transpose, period apostrophe with no intervening space 2 .^ Power, element by element, 2 .^ n pow(2,n) in C, 2**n in Fortran 2 ' Complex Conjugate Transpose 2 ^ Matrix to a power, repeated matrix multiplication 3 + Unary Plus 3 - Unary Minus 3 ~ Logical Complement, tilde, ( result is 1 or 0 ) 4 .* Multiplication, element by element 4 ./ Right Division, element by element 4 .\ Left Division, element by element 4 * Matrix Multiplication 4 / Matrix right division 4 \ Matrix left division matrix \ vector solve simultaneous equations 5 + Addition 5 - Subtraction 6 : Colon Operator a:b sequence from a to b step 1, a:b:c c is step 7 < Less Than, element by element, result 1 or 0 7 <= Less Than or Equal, element by element, result 1 or 0 7 > Greater Than, element by element, result 1 or 0 7 >= Greater Than or Equal, element by element, result 1 or 0 7 == Equal, element by element, result 1 or 0 (a new matrix if matrices compared) 7 ~= Not Equal, element by element, result 1 or 0 8 & And, element by element, result 1 or 0 9 | Or, element by element, result 1 or 0 10 && Short Circuit And 11 || Short Circuit Or 11 xor Returns 1 for every element nonzero in only one array, else 0 Concatenation of strings: ['some' ' integer=' int2str(n) ', x=' num2str(x,'%6.3f')] Constants: numbers 123 123. .123 12.3 12.34e-10 12.34e10 12.34e+10 0 0.0 1.0+2.0i string 'abc' (actually a one dimensional array of characters as numbers) string s = '(a+b).*c' can be used later as eval(s) constants: pi 3.14159... eps 2 .^ -52 inf IEEE Inf nan IEEE not a number realmax Largest number realmin Smallest number Assignment statements: a = 1 % 1.0 in C, 1.0D0 in Fortran a = [1 2 3] % three element row vector a = [1, 2, 3] % same three element row vector a = [1; 2; 3] % three element column vector a = [[1 2 3]; [4 5 6]] % two row, three column matrix Iteration statements: for i = 1:10 % for(i=1; i<=10; i++) in C, do i = 1,10 in Fortran % any number of statements end for i = 0: Pi/8: Pi % for(i=0.0; i<=Pi; i=i+Pi/8.0) in C do i = 0, Pi, Pi/8.0 in Fortran % any number of statements end while a < b % any number of statements end continue % causes next iteration break % causes exit from iteration Conditional statements: if ad % any number of statements elseif e == f % any number of statements else % any number of statements end switch expression case 0 % any number of statements case 1 % any number of statements case 9 % any number of statements otherwise % any number of statements end % no 'break' needed as in "C" try % any number of statements catch % any number of statements end Functions: function variable = function_name(argument(s)) % comments that will be printed upon help function_name % the function may be in a file function_name.m % the function may be viewed type function_name % the function, in a file, may be executed run function_name % or just function_name %any number of statements, nargin and nargout available variable = ... % compute returned variables return % optional, may be used anywhere, default at end end % optional except when this is a nested function % warning! variables defined in outer function are all % available in nested functions. Use of a parameter % name that is the same as a global variable is bad. Vector of functions and use: fun = [@sin; @cos; @log] k = some_expression x = argument_value feval(fun(k), x) Input and output statements Cause a postscript file to be generated for your plot: print a_name.ps % check out other formats in help for print k = input('Enter a number: ') file_name = input('Enter file name: ', 's') % no apostrophy from user Any statement that is interpreted that does not end with a semicolon will print something. The format for printing is controlled by: format short format short e format short g format long format long e format long g format bank % ddd.dd format rat % rational 7/3 format hex format compact % eliminates blank lines disp('any string') % prints without the "ans=" disp(x) % prints without the "x=" use sprintf or fprintf to do your own formatting sprintf(' normal "C" format', variables) % prints ans=%f and your stuff fprintf(' normal "C" format', variables); % prints on screen like printf fid = fopen('your.file', 'w'); fprintf(fid, ' normal "C" format', variables); % writes to your.file ... fclose(fid); % write to file, no output on screen diary output_filename % non graphic output to screen written to file ... diary off % this keeps appending to file when run again Special characters: \a beep \b backspace \e escape \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \o octal \x hexadecimal and, all the LaTeX characters \leq \pi {\itt} etc Colon Operator: ":" 1:5 is a vector 1 2 3 4 5 1:2:10 is a vector 1 3 5 7 9 0:pi/8:pi is a vector 0.0 pi/8 pi/4 ... 100:-2:90 is a vector 100 98 96 94 92 90 t=(0:3)' % transpose gives column 0 1 2 3 Matrix definitions and functions A = zeros(10) a vector of 10 zeros A = zeros(10,12) a 10 row 12 column matrix of zeros A = zeros(nx, ny, nz, nt) a four dimensional matrix of zeros A = ones(nx, ny) a nx by ny matrix of ones A = rand(3, 5, 7) a 3D matrix of uniformly distributed random A = randn(5, ny) a matrix of normally distributed random numbers A = eye(n) an n by n identity matrix B = inv(A) B is the matrix inverse of A d = det(A) d is determinant of A L = eig(A) L is eigenvalues [V,L] = eig(a) V are eigenvectors, L is eigenvalues X = A\Y find x A X = Y solve simultaneous equations [r,c] = size(A) number of rows and columns of 2D matrix A d = size(A,n) the size of the nth dimension of matrix A Sample code to read a file (processing of input line left to programmer) Simple case, one vector of numbers fid = fopen('your.file', 'r'); [v count] = fscanf(fid, '%f', v); fclose(fid); % v now has 1:count values or, if format processing is needed: fid = fopen('your.file', 'r'); while ~feof(fid) line = fget(fid); if feof(fid) break % no more input end if if isempty(line) | strncmp(line, '#', 1) continue % ignore blank lines and comments end % process line (your code here) end fclose(fid); Conversion from "C" to Matlab: copy the file xxx.c to xxx.m and do all editing in xxx.m Do the global substitute (replace) in the following order: */ to nothing /* to % [ to ( ] to ) )( to , comma " to ' apostrophe printf( to fprintf(fid, then add fid=fopen('xxx.out', 'w'); sprintf('results in file xxx.out') strip all declarations to variable = constant; It will save deleting characters to substitute (replace) int to nothing double to nothing float to nothing char to nothing double a[20][30]; becomes a = zeros(20,30); same for all types and number of dimensions static int nx=11; becomes nx=11; #define nx 11 becomes nx=11; I prefer to do each case individually, yet ultimately } to end { to nothing Statements require some change: if(a