Fall 2014 MAT 375 Numerical Methods Introduction to Programming using MATLAB
Some useful links 1 The MOST useful link: www.google.com 2 MathWorks Webcite: www.mathworks.com/help/matlab/ 3 Wikibooks on Matlab Programming: www.en.wikibooks.org/wiki/matlabprogramming 4 Matlab tips: www.matlabtips.com 5 Wikiversity: Introduction to Programming: www.en.wikiversity.org/wiki/introductiontoprogramming
1 Variables 2 Vectors and Matrices 3 Control Flow: Loops 4 Control Flow: Conditionals 5 Functions 6 Graphics - Plot
In CS variable is never unknown, but rather it is explicitly defined, can change it s value throughout the program named location in memory where data can be stored (must be unique in memory) Example: area = pi * r * r; % not just math equation % text after % is comments, it is not part of the code, computer doesn t execute it Instruction to the computer to fetch the values from two memory locations, which are called pi and r, multiply those values together and then store the result in the memory location called area. It does not define a mathematical function; rather it defines a strict set of instructions that the computer will follow when running this line of code.
Another example: X = X + 1; % makes no sense as math expression??!! CS: retrieve the value of X, add one, and store the result back in X. Code: >> X = 7; % set the value of variable X equal to 7 X = X + 1; % add X and 1 and write to the memory location called X % here >> is prompt to input % display value of X X = 8
variable has a data type or class (image from MathWorks) Default class in Matlab is double. So if you write myfirstvariable=3 it is of type double
1 Variables 2 Vectors and Matrices 3 Control Flow: Loops 4 Control Flow: Conditionals 5 Functions 6 Graphics - Plot
MATLAB = MATrixLABoratory: matrices and vectors are specific for Matlab Row-vector: >> row = [0 1 4 5] row = 0 1 4 5 Column-vector: >> column = [1; 2; 3] column = Matrix: >> matrix = [1 2 3; 4 5 6] 1 2 3 %All rows must have the same number of columns! matrix = 1 2 3 4 5 6
Matrix of zeros: Matrix of ones: >> A = zeros(n) % returns n-by-n matrix of zeros >> A = ones(n) % returns n-by-n matrix of ones Length of array: >> v = [1 2 3 4]; >> length(v) ans = 4 Size of matrix: >> A = [1 2 3; 4 5 6]; >> size(a) ans = 2 3
Elements: >> vec = [7 8 9 10]; >> vec(3) ans = 9 >> A(2, 3) % Extract the element in row 2, column 3 ans = 6 Other ways to define vectors >> B = 1 : 3 B = 1 2 3 >> C = 0 : 0.1 : 1 C = 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Two most important Matlab commands help - lists all primary help topics in the Command Window. help <name> displays the help text for the functionality specified by name doc - opens the Help browser, if it is not already running, or brings the window to the top when it is already open. doc <functionname> displays the reference page for the MATLAB function functionname in the Help browser
Operations with matrices: A+B, A-B, A*B - add, subtract, multiply matrices B/A - right division: x = B/A is the solution to the equation xa = B. Matrices A and B must have the same number of columns A\ B - left division x = A\B is the solution to the equation Ax = B (solution to the linear system). Matrices A and B must have the same number of rows det(a) - determinante of matrix inv(a) - inverse of matrix A Examples : >> newvector = v + vec newvector = [8 10 12 14] %[1 2 3 4] + [7 8 9 10] >> verynewvector = newvector + 3 verynewvector = [11 13 15 17] %[8 + 3 10 + 3 12 + 3 14 + 3]
Element-wise operations with matrices: A. B - element-by-element product of A and B A. /B - the matrix with elements A(i,j)/B(i,j). Examples : >> A = [1 0 2; 3 1 4] A = 1 0 2 3 1 4 >> 3. A ans = 3 0 6 9 3 12
1 Variables 2 Vectors and Matrices 3 Control Flow: Loops 4 Control Flow: Conditionals 5 Functions 6 Graphics - Plot
REMARK: Statement: element of programming laguage, states some action to be carried out. Does not return results and is executed solely for their side effects. Examples: A = A+5; return; length(x); Expression: always returns a result and often does not have side effects at all. Examples: x==5 - returns TRUE if x is 5, and FALSE otherwise
FOR statement Executes code a specified number of times using an iterator Syntax: for <iterator> = <startvalue>:<increment>:<endvalue> <statements> end Question: What does this code do? >> n = 6; res = 1; for ii = 1:n res = res*ii; end
WHILE statement Executes code until a certain condition evaluates to false or zero Syntax: while <condition> <statements> end!!! Change conditions within the loop Example: >> counter = 1; sum = 0; while counter < 10 sum = sum + counter; counter = counter + 1; end
1 Variables 2 Vectors and Matrices 3 Control Flow: Loops 4 Control Flow: Conditionals 5 Functions 6 Graphics - Plot
IF statement IF statement - execute code when the logical test (expression) returns a true value (anything but 0). An else statement following an if statement is executed if the same expression is false (0) if <expression> <statements> % execute if <expression> returns TRUE (anything but 0) elseif <expression2> <statements> % execute if <expression> returns FALSE (0) and %<expression2> returns TRUE else <statements> end
Example: >> x = -7; if x == 0 elseif x < 0 else end abs = 0; abs = -x; abs = x;
SWITCH statement Perform one of several possible sets of operations, depending on the value of a single variable switch <variable> case <value1> <statements(1)> case <value2> <statements(2)>... otherwise <statements> end
Example: >> grade = A ; switch (grade) case A disp( Excellent! ); % displaying text case B disp( Well done ); case C disp( You passed ); case D disp( You somewhat passed ); case F disp( Better try it again ); otherwide disp( Something s fishy with the grade ); end
1 Variables 2 Vectors and Matrices 3 Control Flow: Loops 4 Control Flow: Conditionals 5 Functions 6 Graphics - Plot
2 types of m-file: Script - runs in the current workspace. If you call a script from the command line (base workspace) the script will use and manipulate the variables of the base workspace. Can be very messy with bunch of loops, etc. Function - wholly contained in themselves. It possesses its own workspace keeping workspaces separate. Syntax: function [<out1>, <out2>,... ]= <FuncName>(<in1>,<in2>,... ) <statements> end Save the function code in a text file with a.m extension. The name of the file should match the name of the first function in the file.
Example: function [m,s] = stat(x) n = length(x); m = sum(x)/n; s = sqrt(sum((x-m).ˆ2/n)); end Call function: values = [12.7, 45.4, 98.9, 26.6, 53.1]; [ave,stdev] = stat(values) Results: ave = 47.3400 stdev = 29.4124 NOTE: Operations we were talking about before, like length(vector), size(matrix) are standard predefined functions in Matlab
1 Variables 2 Vectors and Matrices 3 Control Flow: Loops 4 Control Flow: Conditionals 5 Functions 6 Graphics - Plot
Syntax: 2-D line plot of the data in Y versus the corresponding values in X plot(x,y) plot(x,y,linespec) Example: x = [0:0.001:10]; % Create x vector y = sin(x); plot(x, y) %Plot title( Sine wave from 0 to 10 ) %Set the title of the current axis ylabel( sin(x) ) % Set the label for the y-axis xlabel( x ) %set the label for the x-axis % xlabel( alpha ) > alpha % xlbel( \alpha ) > symbolic alpha
Two graphs on the same figure with different attributes: x = [1 2 4 8]; % Create x vector y = [1 2 1.95 3.79]; z = [1 1.73 2.02 3.84] plot(x, y, m ) %Plot in dashed line with magenta color hold on; %Plot next graph on same figure plot(x, z, -.b ) %Plot in dashdot line with blue color hold off; title( Two graphs ); ylabel( y vs. z ); xlabel( x ); saveas(gcf, twographs, png ); %Save current figure handle as file twographs.png close(gcf); %Close current figure handle
What s next? Matlab Seminar Tuesday, September 30 4:00pm-7:30pm CSB auditorium