%% MATLAB MINI-TUTORIAL % %% Starting MATLAB % From the menu or write "matlab&" in a shell window %% Quit MATLAB % Write "exit" at the prompt %% Help help linspace %% Building matrices % The basic datatype is a matrix a = rand(4) % Random matrix disp(a') b = a'*a % Matrix multiplication h=1/100; % Step length x=linspace(h,1-h,100); A=[2 1 1 2] % Not the same as a %% Variables % Matlab has built-in variables like pi, eps, and ans % and special matrices like rand, ones, zeros, eye pi eps ans eye(3) % Identity matrix %% Array sections: colon notation % a(:,1) % First column a(2,:) % Second row a(:,5)=ones(4,1) % Matrix of ones a(5,:)=zeros(1,5) % Matrix of zeros %% See more digits a format long a format short % Default %% For loops n=5; % Dimension of a for i=1:n a(i,i)=a(i,i)+100; end a %% While loops % What is computed here? To see which logical and other operators there % are, type "help >" for instance. s=1; term=1; k=0; while term > 1e-15 k=k+1; term=term/k; s=s+term; end %% Scripts % This file is a script: a file with code with the extension .m %% Functions % You can define your own functions: disp('My exp') disp(exp(2)-myexp(2)) %% Plotting % Try "help plot" to see what can be done x=linspace(0,1,100); y=exp(x); % The functions is evaluated with a vector as argument plot(x,y,'-') pause clf plot(x,y,'x') %% Plot two functions plot(x,y,'-',x,sin(x),'--') title('exp and sin') %% Mesh plots % Plot the elements of a matrix mesh(randn(100)) %% Mesh a function of two variables x=linspace(0,2*pi,100); [X,Y]=meshgrid(x,x); F=sin(X).*sin(Y); % Evaluate sin(x)*sin(y) over a square % .* is elementwise multiplication mesh(F) %% Matrix functions % Common matrix functions are standard functions in MATLAB n=4; A=rand(n) b=ones(n,1); x=A\b % Solve linear system Ax=b [Q,R]=qr(A) % QR decomposition A = Q*R [U,S,V]=svd(A) % Singular value decomposition A = U*S*V' [P,D]=eig(A) % Eigenvalue decomposition A*P=P*D %% Sparse matrices % Do not store zeros of most of the elements are zero speye(3) % Sparse identity matrix n=50; B=2*speye(n); for i=1:n-1 B(i,i+1)=-1; B(i+1,i)=-1; end B(1:4,1:4) spy(B) %% Matrix functions work also for sparse matrices c=ones(n,1); x=B\c; plot(x) %%