Tutorial in Matlab

From Statipedia

Jump to: navigation, search

From a Unix shell one can just type 'matlab' as a command on any computer that has it, and start to type interactive statements such as those below. One could also put them in a file with the .m extension to run them from within matlab with 'run file.m' or from the shell with 'matlab < file.m' This tutorial covers very little but you can see something of the language.

%  The percent sign begins comments.
%  The statements below can be typed interactively one per line to get
% clear responses from Matlab.  No need to type the comment part at the
% end of the lines.  Make sure to use upper and lower case in the
% same was as in the statements shown.

A=[1 2;3 4]   % defines matrix A as a 2x2 with first line [1 2]
B=A'          % transpose
B=A+A         % sum, element by element
Ainv=inv(A)   % takes inverse of a matrix
A*Ainv        % calculates and prints the result of a matrix multiplication
B=[A;A]       % stacked so B has twice as many rows as A
B=[A A]       % the A's are side by side.  B has twice as many columns as A.
B=A(1,1)      % B is a scalar now, the upper left element of A
B=A'*A        % matrix multiplication
B=A(:,1)      % B is set to first row of A
B=A.*A        % element by element multiplication
B=B./A        % element by element division
A=zeros(3,3)  % special definition of a matrix of zeros
B=ones(3,1)   % defines a matrix of ones
A=eye(5)      % defines identity matrix
B=A(1:2,1:3)  % takes part of matrix
more on       % may not be needed; prevents help screen from scrolling off
help *        % shows sample of the help available

Source: Chris Taber, Econ D83 at Northwestern 1996-7, Matlab tutorial handout

Personal tools