MATH 152 MATLAB Tutorial 4 MATLAB Scripts and Resistor Networks Learning Goals . Create, save and run MATLAB scripts · Create large matrices using MATLAB functions eye, diag and ones · Solve large systems of equations representing loop currents in resistor networks 1 MATLAB Scripts A MATLAB script is a text file which contains MATLAB commands. A script is saved with the file extension .m. Execute all commands in a script using the "Run" button in editor menu. For example, let's create a script called vector_angle.m which computes the angle between vectors v and w: v . w = |||||||cos0 = 0= arccos V. V · W W Click "New Script" in the menu bar and type the following commands in the file: v = [1,0,1,2]; W = [3,1,-1,4]; theta = acos(dot (v, w) / (norm (v) *norm (w) ) ) Click "Save" in the editor menu and save the script as vector_angle.m. Click "Run" in the editor menu to execute all the commands in the file: >> vector_angle theta = 0.6670 Now we can edit and rerun the script to quickly get new results. For example, edit the script with v = [1, 0,1,-2] and then run again to find: 1
vector_angle theta = 2.061679005084208 2 Special Matrices There are several MATLAB functions for creating special matrices. For example, the function eye (n) creates the identity matrix of size n: >> I = eye (3) I = 1 0 0 1 0 0 0 0 1 The function diag (v) creates a matrix with the entries of v along the diagonal: >> diag([1 2 3]) ans = 1 0 0 2 0 0 0 0 3 The command diag (v, 1) creates a matrix with the entries of v above the diagonal: 2
>> diag([1 2 3],1) ans = 0 1 0 0 0 0 0 0 0 0 0 2 0 0 3 0 And diag(v, -1) creates a matrix with the entries of v below the diagonal: >> diag([1 2 3],-1) ans = 0 0 1 0 0 2 0 0 3 0 0 0 0 0 0 0 The function ones (n) creates a square matrix of ones of size n: ones (2) ans = 1 1 1 1 The function ones ( [n, m] ) creates a matrix of ones of size [n, m] : >> ones ( [1,4]) ans = 1 1 1 1 Combine these functions to create a large tridiagonal matrix: 3