# II.

1

Programming in MATLAB
Figure A2-1 MATLAB Desktop

and then hit enter. Next, let’s write a short MATLAB program. A MATLAB program is called an M-file because it’s a file in your computer and the “M” stands for MATLAB. Let’s create am M-file named test.m. To create the M-file, type edit test.m and hit enter. Now type in the following program: clear W = 100; theta = pi/6; F = W*sin(theta) Save and close the M-file and then go back to the command window. To run this program type test1

MATLAB is a popular programming language that was developed for technical computing. This section shows you how to use MATLAB. You’ll be given three representative MATLAB computer programs. As you look through the three programs, you’ll see what syntax is used. The first program shows how to graph. The second program shows how to use arrays. The third program shows how to create functions.

and hit enter. The program will display F = 50.00 in the command window. To see which variables are defined in the workspace, type who and hit enter. The variables F, W, and theta will be listed. To see what programs you have in your current directory, type what

Getting Started
When you start MATLAB, the MATLAB desktop shown in Fig. A2 – 1 appears. Let’s begin by using the command window in the desktop. In the command window, type W = 100 and hit enter. Notice that MATAB responds by printing the result of the command that you typed in. Next, type theta = pi/6; and hit enter. This time, MATLAB did not print the result of the command because of the semicolon you placed at the end of the instruction. Next type F = W*sin(theta) and hit enter. In the command window you can write instructions using any of the normal algebraic operations plus the other hundreds of MATLAB operations. To erase what’s in the command window, type clc and then hit enter. To clear the values of all of the variables in the workspace, type clear
1

and hit enter. You’ll only see test1.m listed because it’s the only program you’ve created so far. You’re now ready to look over the three computer programs shown in Tables 1, 2, and 3. These programs can serve as templates to refer to in the future when you’re creating M-files.

Graphing
The first template graphs the cosine function and the sine function. Create the M-file named tgraph.m and type in Table 1. Notice that the values of the cosine function and the sine function are created using a loop that begins with the for statement and ends with the end statement. Now, save and close tgraph.m, go to the command window, type in tgraph

and hit return. A figure window with the graphs of the cosine function and the sine function will appear. Notice that graphing has a lot of optional features. You have the option to label your axes, create a title for the graph, set the range of the horizontal and vertical axes, put in a grid, graph more than one function in the same graphing window, etc. Before proceeding, you may want to take a moment and experiment with the program to try out its different features.

2

% % % % % % % % % % % % % % % % %

tgraph.m This m-file is a template for creating graphs of functions. It contains many of the commands that are commonly used in graphing. In this template, the graphs of the sine function and the cosine function are created in one figure window. This template shows: several ways of plotting how to create a grid in a figure window how to label axes how to create a title for a figure window how to create a legend when more than one plot is drawn in a figure window

clear for i = 1:361:1

%for i = 1:361 theta(i) = (i-1)*2*pi/360; f(i) = sin(theta(i)); p(i) = cos(theta(i)); end figure grid on axis([0 7 -1 1]) hold %plot(theta,f) %plot(f) plot(theta,f,'r') plot(theta,p,'g') %plot(theta,p,'--') %plot(theta,p,':') %plot(theta,p,'r.') title('force and position') xlabel('t-axis') ylabel('force or positon') legend('force','position')

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %

Optional Feature. This sets all values to zero. This is the beginning of a loop. The index i increases from 1 to 361 in increments of 1 each time through the loop. More compact ways of doing loops is shown in the template called tarray. The default increment is 1. theta is an array. theta varies from 0 to 2*pi radians. f is an array. The i-th entry of f is the sine function evaluated at the i-th value of theta. p is an array. The i-th entry of p is the cosine function evaluated at the i-th value of theta. This is the end of the loop. This opens a new figure window. Optional Feature. This creates a grid on your graph. Optional Feature. This specifies the axis limits ([theta-min theta-max f-min f-max]). Optional Feature. This holds the figure window for more graphs. This plots the array f versus theta (in radians). This plots the array f versus the index (from 1 to 361). This plots the array f versus theta in red. The 'r' indicates the color red. This plots the array p versus theta in green. The 'g' indicates the color green. This plots the array p versus theta in large dashes. This plots the array p versus theta in small dashes. This plots the array p versus theta in red in small red dots (zoom in to see them). Optional Feature. This creates a title for the figure window. Optional Feature. This creates a label for the horizontal axis. Optional Feature. This creates a label for the vertical axis. Optional Feature. This creates a legend for the first and second graphs in the figure window.

Table 1: Template for Graphing

3

Arrays
Next, look over the second template shown in Table 2. This program determines the force reactions acting on the bar shown in Fig. A2 – 2. The reactions are found by solving a set of three linear algebraic equations. The unknowns in this problem are

⎛ F ⎞ ⎟ ⎜ x = ⎜NA⎟, ⎜N ⎟ ⎝ B⎠
where F is the friction force at A, NA is the normal force at A, and NB is the normal force at B. Create the M-file named tarray.m and type in Table 2. Notice how the program defines elements of vectors and matrices (arrays). Also notice how these arrays are manipulated using vector algebra. In this program, a set of linear algebraic equations of the form Ax = b is solved by first calculating A-1 and then by calculating the solution x = A-1b. Next, save and close tarray.m, go to the command window, type tarray and hit return. The command window diplays b, A, and the solution x. You’ll see that F = 31.6987 lb, NA = 68.3013 lb, and NB = 44.8288 lb.

4

% % tarray.m % % This m-file is a template for creating arrays. It contains many of the % commands that are commonly used for arrays. % % In this template, a set of linear algebraic equations is solved. % % This template shows: % % - several ways to input a vector % - how to transpose a vector and a matrix % - how to invert a matrix % - how to swap a column in a vector with another column vector % - how to multiply vectors and matrices % - how to perform a for-end loop more efficiently % clear W = 100; L = 2; theta = pi/4; beta = pi/6; b = [W,0,W*L/2*cos(beta)]' % An array is defined by enclosing the elements in % brackets, separating them by commas. % This creates a row vector. The prime following the % right bracket transposes the row vector, making it a % column vector. % % b = [W;0;W*L/2*cos(beta)] % This is another way to define a column vector. Each row % (the rows are one element long) is separated by a % semicolon. A = [0,1,cos(theta);1,0,-sin(theta);0,0,L*cos(theta-beta)] %A matrix is defined by % listing its elements row by row. Each % row is separated by a semicolon. ainv = inv(A); % inv inverts a matrix. % detofA = det(A) % det takes the determinant of a matrix. % Atranspose = A' % a prime after a matrix transposes the matrix. % A(:,2) = [10,10,10]' % Using the colon, the second row of A is replaced with % the column vector [10,10,10]'. x = ainv*b % multiplication/addition of vectors and matrices uses % the same syntax that is used for scalars. %time1 = [0:1:2*pi] % Instead of using a for-end loop. The following syntax %can be used. This instruction creates a row vector of % values starting from 0, stepping in increments of % 1,ending just before 2pi. The loop is created using the % brackets. %time2 = [0:2*pi] % The default increment is 1. %c = cos(time1) % Creates a row vector called c. The array is created % using the parentheses, inside which the array time1 % appears.

Table 2: Template for Arrays

5

To try out a few other vector operations, type in clear a = [1, 2, 3] b = [2, 3, 4] and then type in each of the following quantities and hit enter: a*b’ dot(a,b’) a’*b cross(a,b) dot(a,b) cross(a’,b’)

Notice that the dot function does not distinguish between column vectors and row vectors but that the other operations do.

Functions
The third and final template shows you how to create functions. This will help you become more efficient in programming. Create the M-file called tfunction.m and type in Table 3. The M-file tfunction.m turns the force reactions in the second template into a function of beta and theta. In the command window, type in [F,NA]=tfunction(pi/6,pi/4) and hit enter. The reactions F and NA are displayed.

6

function [F,NA] = tfunction(beta,theta) % % tfunction.m % % This m-file is a template for a function. % % In this template, the function tfunction finds the friction force F and the normal % force NA. % The inputs to the function are the variables beta (the angle of the bar) and theta % (the angle of the incline). These two inputs are in radians. % The outputs to the function are F and NA. % Notice the syntax for the function. The output variables are surrounded by brackets, % the input variables are surrounded by parentheses, and the name of the function is % the same as the name of the file. % % This template shows: % % - the syntax for a function % W = 100; L = 2; b = [W,0,W*L/2*cos(beta)]'; A = [0,1,cos(theta);1,0,-sin(theta);0,0,L*cos(theta-beta)]; ainv = inv(A); x = ainv*b; F = x(1); NA = x(2);

Table 3: Template for Functions

The M-file tfunction.m can also be called from within another program. So can the M-files test1 and test2. To illustrate this, create the M-file named test2.m and type in Table 4. This program determines the critical angle beta of the bar for which the bar remains in static equilibrium but below which the bar slides (See Fig. A2 – 2). The program test2.m calls the function tfunction.m in a loop, sweeping over a range of values of beta between 0 and theta. Each time the function is called, the program compares the value of the friction force with the maximum allowable level of friction, Fmax = µNA, to see if it’s been exceeded. To run test2.m, go to the command window, type in test2 and hit enter. The command window displays betacritical = 26.55, which is the critical angle beta in degrees, and a figure window appears showing two graphs. One graph is of the friction force F versus beta and the second graph is of the maximum friction force (above which the bar slides) versus beta.

Figure A2 – 2: A bar rests on a rough surface at one end and on a smooth inclined surface at the other end.

7

clear mu = 0.5; theta = pi/4; error = 100; betamax = 0; for i = 1:101 beta = (i-1)*theta/100; [F,NA]=tfunction(beta,theta); x(i) = beta*180/pi;

% % % % %

The function tfunction is called. Notice that x in test2.m is different than x in tfunction.m. Quantities are not passed between programs.

y(i) = F; FMAX(i)=mu*NA; er = abs(F-FMAX(i)); if er <= error error = er; betacritical = beta*180/pi; else end end betacritical % The critical value of beta is displayed. hold grid on xlabel('beta (degrees)') ylabel('F (lb), F_M_A_X (lb) (in red)') % The "_" creates a susscript. plot(x,y) plot(x,FMAX,'r') % This is an if-else-end statement. % Betacritical is taken to be the value of % beta (in degrees) for which % the difference between F and % FMAX (in magnitude) is the smallest.

Table 4: Test2.m

Finally, note the functions in MATLAB like cos(x), inv(A), etc., are no different that the function tfunction that you just created. Type in help tfunction and hit enter. The comments that you placed at the beginning of the M-file tfunction will appear in the command window, just like any of the other MATLAB commands that are built-in. This concludes the tutorial. The purpose of the tutorial was to give you only the most basic tools – just to get started. To become more proficient in MATLAB, try out the help menu, the start button, experiment with the MATLAB features and the other MATLAB tools.

Key Terms
Arrays, Command Window, Functions, MATLAB Desktop, M-file, Workspace Graphing,

8

Key Commands
clc, clear, edit, what, who

Problems
A2 – 1 A W = 50 lb block rests on a rough surface when the friction force F acting on the block is less than µN, in which N denotes the normal force acting on the block by the surface and µ = 0.5 is the static friction coefficient. When F exceeds 0.5N, the block begins to slide. The friction force F and the normal force N depend on the incline angle θ by F = 50cosθ and N = 50sinθ. Plot the functions F(θ) and µN(θ) on the same graph letting θ range between 0 and 90○. Determine from the graph the largest angle θmax for which the block remains at rest. Answer: θmax = 26.6○ (Note that θmax can also be found analytically.)

Review Questions
1. What is the MATLAB desktop? 2. Describe the purpose of a semicolon placed at the end of an instruction. 3. What command erases what’s in the command window? 4. What command clears all of the variables in the workspace? 5. Describe the purpose of the commands who and what.

A2 – 2 A triangular truss is acted upon by a P = 500 lb load, as shown. The load causes a tensile force of FAB = P/sinθ in member AB and a compressive force of FAC = Pcosθ /sinθ in member AC. Plot FAB + FAC versus θ. For what angle θ is FAB + FAC minimal? Answer: θmin = 60○ (Note that θmin can also be found analytically.)

9

A2 – 3 A L = 15 foot inextensible cord is tensioned by a spring having a spring constant of k = 1000 pounds per foot and an unstretched length of a = 0.25 feet. A W = 20 pound weight hangs from point A, as shown. After some analysis, the tension T in the cord (in pounds), the angle θ of the spring, and the stretch u of the spring were found to be related to each other by the three equations a = (a + u ) cos θ , W = ku sin θ , T = ku cos θ . It was determined from these equations that the angle θ of the spring is constrained by the equation 0 = f(θ) = a – [a + W/(ksinθ)]cosθ To find the angle θ, plot f(θ) over the range of θ between 0 and 90○ and locate from the graph where f(θ) = 0. Then, find the tension T in the cord and the stretch u in the spring. Answer: θ = 30.321○, T = 34.2 pounds, u = 0.475 inches.

A2 – 5 A bridge is supported by cables that are suspended from a circular arch, as shown. The number of cables is 2n + 1. The cables are tensioned to equal tensions T. After some analysis, in order to support a 100 kilo-pound weight, it has been determined that the tension in the cables is
T= 1+ 2 W

k =1

n

sin kθ [cos kθ − 1 /(n + 1)] 2 + sin 2 (kθ )

where θ =

. Graph the tension T versus n for a range of 2(n + 1) n between 1 and 10. Answer: T = 34.3, 23.1, 17.7, 14.4, 12.2 ,10.5, 9.27, 8.29, 7.50, 6.84 kilo - poun

π

A2 – 4 After analyzing the triangular truss given in problem A2 – 2, it was determined that the unknown internal forces FAB and FAC and the unknown reactions at B and C, denoted by RBx, RBy, and RCx, are related to each other by the five equations
− F AB cos θ + F AC = 0, F AB sin θ = 500 F AB cos θ + R Bx = 0, − F AB sin θ + R By = 0, − F AC + RCx = 0

in which θ = 60○. Placing the unknowns in the column vector x = [FAB FAC RBx RBy RCx]T, write these equations in matrix-vector form as Ax = b. Then write a short program, find A-1 and then x = A-1b. Answer: FAB = 577 lb, FAC = 289 lb, RBx = -289 lb, RBy = 500 lb, RCx = 289 lb.

10

A2 – 6 A stone ornamental bridge being considered as a gateway to a European city combines Greek and gothic elements. The cables are not just ornamental. They also pull together beam A and pillars B. The cables are tensioned to the same tension to pull down on the beam with a force of 2,500 pounds. The number of cables is 2n. After some analysis, it has been determined that the tension in the cables is
T= 2H 2500

k =1

n

k L2 [2 − k /( n + 1)] 2 + H 2 [k /( n + 1)] 2

where L = 7 feet and H = 25 feet. Graph the tension T versus n for a range of n between 5 and 10. Answer: T = 361, 303, 261, 229, 205, 185 pounds.

11