Mathlab Tutorial
Standard Matrices:
>>rand(3)
>>rand(3,5)
>>hilb(3)
>>magic(3)
>>eye(3)
>>zeros(3)
>>ones(3)
>>[1, 2, 3; 4, 5, 6; 7, 8, 9]
Variables:
>>pi
>>eps
>>who <!--Note: used to display active variables-->
>>ans <!--Note: used to display the last output-->
>>clear x <!--Note: used to clear variables; x is the variable name-->
Functions:
>>a = magic(3)
>>a' <!--Note: transpose of a-->
>>min(a)
>>max(a)
>>a.*b <!--Note: entry by entry multiplication rather than matrix multiplication-->
>>triu(a)
>>tril(a)
>>diag(a)
>>size(a)
>>sin(a)
>>exp(a)
>>log(a)
>>abs(a)
>>round(a)
>>fix(a)
>>ceil(a)
>>floor(a)
>>sum(a)
>>prod(a)
Relations and Logical Operations (1 = true and 0 = false)
>>a & b <!--and-->
>>a | b <!--or-->
>>~a <!--not-->
>>a==b
>>a<=b
>>a>=b
>>any(a) <!--Note: determines if the matrix has at least one nonzero entry-->
>>all(a) <!--Note: determines if the matrix has all nonzero entries-->
Uses of the Colon:
>>y=-2:1 <!--Note: creates a matrix with values from -2 to 1-->
>>y=-2:.5:1 <!--Note: creates a matrix with values from -2 to 1 with .5 intervals-->
>>x(2, :) <!--Note: displays elements in row 2-->
>>x(:, 3) <!--Note: displays elements in column 3-->
>>x(1:2, 2:3) <!--Note: displays elements in rows 1 and 2 from columns 2 to 3-->
>>x(:, [1 3]) <!--Note: displays all row elements in columns 1 and 3-->
Other Features:
>>casesen <!--Note: toggles case sensitivity on and off -->
>>format long <!--Note: display 16 digits -->
>>format short <!--Note: display only 5 digits -->
>>a; <!--Note: semicolon is used to skip the display of the matrix -->
>>save filename <!--Note: saves variable in a file called filename.mat -->
Programming in Mathlab:
1. Create a program file: myfile.m
2. To run the program file: >>myfile
3. Assignment program: mod.m
function r=mod(a,d)
% r=mod(a,d). If a and d are integers, then % r is the integer remainder of a after % division by d. If a and b are integer matrices, % then r is the matrix of remainders after division % by corresponding entries. Compare with REM. r=a-d.*floor(a./d); To use the program: >>mod(a,b) 4. Branching program: function b=even(n) % b=even(n). If n is an even integer, then b=1 % otherwise, b=0. if mod(n,2)==0, b=1; else b=0; end 5. For loop program: function c=add(a,b) % c=add(a,b). This is the function which adds % the matrices a and b. It duplicates the MATLAB % function a+b. [m,n]=size(a); [k,l]=size(b); if m~=k | n~=l, r='ERROR using add: matrices are not the same size'; return, end c=zeros(m,n); for i=1:m, for j=1:n, c(i,j)=a(i,j)+b(i,j); end end 6. While loop program: function l=twolog(n) % l=twolog(n). l is the floor of the base 2 % logarithm of n. l=0; m=2; while m<=n l=l+1; m=2*m; end 7. Recursion program: function y=twoexp(n) % y=twoexp(n). This is a recursive program for computing % y=2^n. The program halts only if n is a nonnegative integer. if n==0, y=1; else y=2*twoexp(n-1); end