%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Tutorial.M (Introduction to Matlab) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BEFORE CONTINUING IT IS GOOD TO OPEN ANOTHER .M FILE SO THAT YOU CAN SAVE YOUR % WORK. LET US CALL THIS FILE 'MY_PROBLEM1.M' % %*********************************************************** % 1. Matlab basics %********************************************************** % Matlab is an interpreting programming language that supports all % basic operations and functions like other programming languages % (e.g. if then else structure, for loop, while loop, case-switch structure, % break, try, catch, return, ...) a=10 if (a==4) b=a^2 elseif (a~=10) b=a else b=-a end % For loop for i=1:2:10 i end % While loop j=13; while j>0 j=j-1 end % % EXERCISE 1: % Modify the previous 'WHILE' loop to list all numbers from j to 20; % Write down the solution % % Examine switch command by typing help switch % Matlab supports help system through help window, or through help statement from the % command prompt (e.g. help case) % There is also a lookfor statement, when we are not sure what is the exact name of % the statement or the function. Lookfor searches for specified word through description % of all available Matlab functions % e.g. "lookfor write" gives all functions that contains the word write in their % description % % familiarize yourself with the Matlab help window. Browse through help topics. % EXERCISE 2: % Explain in one-two sentences the functions from matlap/general, matlab/ops, matlab/elfun % matlab/lang and matlab/elmat folders in help % % In addition, Matlab has integrated powerful functons for elementary matrix % manipulation and numerical linear algebra, elementary and specialized math % functions, 2D and 3D graphic, interpolation, polynomials, Fourier transforms, % sparse matrices, ..... % Unlike other languages it DOES NOT make executable code. Insted, it interprets % comands of functions written in the script or inside the another funstion. % Function has a specific syntax and should be called. % It can have more than one input and output arguments. % Normally, arguments are transfered by value. It is possible to submit arguments % by reference (as common attributes for caller and the function), but you'll % never need this... % 'operations' is an example of a matlab function you downloaded a = 5 b = 4 [sum_ab, product_ab] = operations(a, b) % Try to put the semicolumn at the end: [sum_ab, product_ab] = operations(a, b); % What is the difference? % % EXERCISE 3: % open the file 'operations.m' and modify it so that its has the third % output square_a. Remember, you should save the modified file before you call it % from the Matlab prompt % % write down the solution in your report (you can print out the modified function) % %********************************************************* % 2. Matrix operations %********************************************************* A = [1 2 3 4 5 6 7 8 9 10 11 12] B = [1 3 5 7 11 13 17 19 23 29 31 37] % Another way to represent matrix C = [1 2 3 4; 5 6 7 8; 9 10 11 12] % Some operations D = A + B E = A * C F = C * B F1 = diag(inv(sqrt(F))) % % EXERCISE 4: % Explain what does variable F1 represent? % G = B./ A % What did we do? % Two ways to do the same thing G_transpose = G' G_transpose = transpose(G) % Matlab is very powerful in matrix computation. % DO NOT USE for loop for computing with matrices. THERE IS ALWAYS % FASTER WAY TO WORK WITH VECTORS OR MATRICES % % EXERCISE 5: % examine the 'size', 'sum', 'mean', and 'std' commands % Explain them with one sentence % % Example of using 'size' [num_rows, num_cols] = size(A) num_rows = size(A,1) num_cols = size(A,2) % Example of using 'sum' sum(A) % sumation performed by first index (sums of columns!) sum (A,1) % The same sum(A,2) %sumation performed by the second index (sum of rows) sum(sum(A)) %sum all elements in the matrix % It is important to understand the manipulation with vectors and matrices A1 = A(:,3) % separate one COLUMN (Attribute) A2 = A(2,:) % separate one ROW (Data Example) A3 = A(:,[1 3]) % separate columns 1 and 3 A4 = A([1 3],1:3) % WHAT DID WE DO?? % Special matrix functions diagonal_matrix=diag([1 2 3 4]) all_zeros=zeros(3,4) all_ones=ones(4,2) identity_matrix=eye(4) % Very useful command whos % BASIC STATISTIC mean_A_column = mean(A) % Mean for columns mean_A_row = mean(A,2) % Mean for rows std_A_column = std(A) % Standard devaition of columns std_A_row = std(A,[],2) % Standard deviation of rows ([] MUST be here) % EXERCISE 6: % explain the result of the following three lines: A1=mean(A(:,2)) A2=mean(A(1,:)) A3=mean(A')' % Generate a matrix of random numbers between 0 and 1 R = rand(4,3) % % EXERCISE 7: Write the code that solves the following: % % Generate a matrix R1 of random numbers of dimension 20x5. % Calculate the mean of column 3. Calculate the mean of row 6. % Calculate the mean of the first 15 elements of column 4. % %********************************************************* % 3. Input/output %********************************************************* % How top read number form keybord x=input('Input for computation'); y=x^2; %This will not be printed z=x^3 %this WILL be printed % How top read strings form keybord new_string=input('Input a string','s'); latest_string=['You entered ', new_string] % How to save results. LOOK WHAT HAPPENS IN YOUR FOLDER % To save specified variables into specified file in ascii form save file_E.txt E -ASCII % ADVICE: BEST IF USED TO SAVE ONLY ONE VARIABLE % Check what happens when saving more then one save file_EAB.txt E A B -ASCII %'To save specified variables into specified file in binary (matlab-specific) form' % Default extension is .mat save file_ABC A B C % To save ALL variables, write only a file name. All variables in scope % will be saved save file_all % How to clear variable A clear A whos % there is no variable A now clear all % delete all variables in scope. whos % everything is deleted % How to load files % From .mat file load file_all whos % From ASCII file. clear all % clear all first load file_E.txt % CHECK WHAT HAPPENED by typing 'whos'!! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 4. Graphic %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Example: t=0:0.1:5; x=sin(pi*t)+0.1*t; y=cos(pi*t)-0.2*t; % Examine the resulting figures f(1)=figure % WHAT DID WE DO?? EXAMINE THE COMMAND 'figure' plot(x) f(2) = figure plot(t,x) f(3)=figure plot(t(1:20),x(1:20),'.') f(4) = figure plot(x,y); % Close all figures close(f) % How to put more plots on one figure: plot(x,y) hold on plot(x,y, 'r*'); % plots blue stars instead of line %pause figure; z=2*t; plot3(x,y,z,'m-d'); % shows magenta diamonds in addition to line % Plotting x and y axes as well as graph title and legend A=[1 2 3 4 5 7 9]; B=[12 13 14 14 11 10 8]; plot(A,B); %both arguments are vectors of the same length pause C=B-4; hold on; %retained old graph, new graph is added plot(A,C,'*-r'); %this line is read and has stars and lines pause xlabel('Month') ylabel('Power consumption') title('This is demo graph') %title legend('New York','Philadelphia') %label of the graph % Method for plotting matrices figure; %opens new plot C=eye(10,10); imagesc(C); title('The way to plot matrices') % Other nice graphic functions imagesc, surf, meshgrid, ..... % TRY HELP for these commands [X Y]=meshgrid(-pi:pi/10:pi,-pi:pi/10:pi); %grid to compute function in even intervals Z=sin(2*X).*cos(3*Y); surf(X,Y,Z); %Plots 3D function pause imagesc(Z);colorbar % EXERCISE 8: % type 'demo' and go through matrics and visualization parts % Explain what you learned in demo in few sentences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 5. Some useful functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% a = rand(10,5) a1 = sort(a) % SORT each colun separately a2 = sort(a,2) % SORT each row separately % VERY USEFUL FUNCTION: 'find' % FIND all rows (examples) where the values in % second columen are greater than 5 q = find(a(:,2) > 0.5) % Use histogram: b = rand(50,1); hist(b,20); % Histogram in 20 bins % histogram is expected to be fairly flat b = rand(5000,1); % generate more data figure hist(b,20); % Histogram in 20 bins % CAN YOU CONCLUDE WHAT IS THE DIFFERENCE IN THE SHAPE OF THE TWO HISTOGRAMS?? % EXERCISE 9: WHAT IS THE NAME OF COMMAND THAT % a) lists all current variables in the workspace % b) deletes all variables in the workspace % c) randomly generates normally distributed numbers return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%