Loading in 5 sec....

MEGN 536 – Computational Biomechanics MATLAB: Getting StartedPowerPoint Presentation

MEGN 536 – Computational Biomechanics MATLAB: Getting Started

- 89 Views
- Uploaded on

Download Presentation
## PowerPoint Slideshow about ' MEGN 536 – Computational Biomechanics MATLAB: Getting Started' - indiya

**An Image/Link below is provided (as is) to download presentation**

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript

### MEGN 536 – Computational BiomechanicsMATLAB: Getting Started

### More Advanced Topics: Scripts, User-Defined Functions, Conditionals, Loops, Files

Prof. Anthony J. Petrella

Computational Biomechanics Group

MATLAB Window

variables in workspace

and their values

Current directory contents

Workspace tab

(active here)

Command line

History

MATLAB Help

- To obtain help with any known MATLAB command just type…
>> help command_name

- To search the help files just select MATLAB Help from the top level menu, hit the F1 key, or type…
>> doc

Scalar Arithmetic Operations

Symbol Operation MATLAB form

^ exponentiation:aba^b

* multiplication:aba*b

/ right division:a/b a/b

\ left division:b/a a\b

+ addition:a + ba + b

- subtraction:a - ba - b

Entering Commands and Expressions

- MATLAB retains your previous keystrokes.
- Use the up-arrow key to scroll back back through the commands.
- Press the key once to see the previous entry, and so on.
- Use the down-arrow key to scroll forward. Edit a line using the left- and right-arrow keys the Backspace key, and the Delete key.
- Press the Enter key to execute the command.

Special Variables and Constants

Command Description

ans Temporary variable containing the most recent answer.

eps Specifies the accuracy of floating point precision.

i,j The imaginary unit Ö-1.

Inf Infinity.

NaN Indicates an undefined numerical result.

pi The number p.

Order of Precedence

Precedence Operation

First Parentheses, evaluated starting with the innermost pair.

Second Exponentiation, evaluated from left to right.

Third Multiplication and division with equal precedence, evaluated from left to right.

Fourth Addition and subtraction with equal precedence, evaluated from left to right.

Examples of Precedence

>> 8 + 3*5

ans =

23

>> 8 + (3*5)

ans =

23

>>(8 + 3)*5

ans =

55

>>4^212 8/4*2

ans =

0

>>4^212 8/(4*2)

ans =

3

Examples of Precedence (continued)

>> 3*4^2 + 5

ans =

53

>>(3*4)^2 + 5

ans =

149

>>27^(1/3) + 32^(0.2)

ans =

5

>>27^(1/3) + 32^0.2

ans =

5

>>27^1/3 + 32^0.2

ans =

11

Commands for managing the work session

Command Description

clc Clears the Command window.

clear Removes all variables from memory.

clear v1 v2Removes the variables v1 and v2 from memory.

exist(‘var’) Determines if a file or variable exists having the name ‘var’.

quit Stops MATLAB.

Commands for managing the work session (continued)

Command Description

who Lists the variables currently in memory.

whos Lists the current variables and sizes, and indicates if they have imaginary parts.

: Colon; generates an array having regularly spaced elements.

, Comma; separates elements of an array.

; Semicolon; suppresses screen printing; also denotes a new row in an array.

... Ellipsis; continues a line.

Practice…

- Find the circumference and area of a circleof radius = 2.5 mm
- Find the surface area and volume of a sphereof radius 17.2 mm
- Use help to learn the difference between the built-in MATLAB functions cos()and cosd()

How to Create Arrays

- You can use the colon (:) operator together with the comma and semicolon to create arrays
- Colon – create a sequence of numbers in a row
- Comma – separate listed elements of a single row, can also use an empty space
- Semicolon – separates rows

>> p = [1:3;4,5,6;7 8 9]

p =

1 2 3

4 5 6

7 8 9

>> r = [5:5:35;35:-5:5]

r =

5 10 15 20 25 30 35

35 30 25 20 15 10 5

Array Functions

- You can find the size of an array with the size() function
- You can find the length of a vector with the length() function
- Read the help entries for each of these functions
>>p = [5:5:35;35:-5:5];

>>size(p)

ans =

2 7

>>r = [4,5 6];

>>length(r)

ans =

3

Concatenation

- You can easily create an array by concatenating two or more existing arrays
>> p = ones(3,1)

p =

1

1

1

>> q = zeros(3,1)

q =

0

0

0

>> s = [p q q p]

s =

1 0 0 1

1 0 0 1

1 0 0 1

Array Index

- You may refer to a single element of an array by using the array index corresponding to the row and column where the number is located in the array
>>w = [5:5:35;35:-5:5]

ans =

5 10 15 20 25 30 35

35 30 25 20 15 10 5

>>w(2,3)

ans =

25

- If the array is a vector, you need only specify the column number since there is only a single row and the row number is assumed to be 1
>>u = [6 7 8 9 0];

>>u(2)

ans =

7

Array Addressing

- You can refer to ranges of elements in an array by using the standard index format
elements = array(rows,columns)

- Example
>>w = [2:2:10;10:-2:2];

w =

2 4 6 8 10

10 8 6 4 2

>>w(1:2,3:4)

ans =

6 8

6 4

try this >>w(:,5)

Array Addressing

- Other examples of how to address an arbitrary selection of rows & columns from an array
>> r = [5:5:35;35:-5:5]

r =

5 10 15 20 25 30 35

35 30 25 20 15 10 5

>> r(:,2:5)

ans =

10 15 20 25

30 25 20 15

>> r(:,[2,5])

ans =

10 25

30 15

Example – Linear Indexing

- What happens when a single index is used to address elements of a matrix?
>> r

r =

5 10 15 20 25 30 35

35 30 25 20 15 10 5

>> r(2)

ans =

35

>> r(5)

ans =

15

>> r([2 7 13])

ans =

35 20 35

Assignment

- You can store the results of a calculation in a specified location in an array
for i = 1:10,

s(i,1) = sqrt(5*i);

end

>> s =

2.2361

3.1623

3.8730

4.4721

5.0000

5.4772

5.9161

6.3246

6.7082

7.0711

Note: the semicolon causesscreen output to be suppressed!

Only after the loop completes is the output specifically requested by typing the variable name

You can execute commands in MATLAB in two ways: Conditionals, Loops, Files

- In the interactive mode, in which all commands are entered directly in the Command Window, or…
- By running a MATLAB commands stored in a script file. This type of file contains MATLAB commands, so running it is equivalent to typing all the commands—one at a time—at the Command Window prompt. You can run the file by typing its name at the command line.

What happens when you type Conditionals, Loops, Filesfunc_name()

- MATLAB first checks to see if func_name() is a variable and if so, displays its value.
- If not, MATLAB then checks to see if func_name() is one of its own commands, and executes it if it is.
- If not, MATLAB then looks in the current directory for a file named func_name.m and executes func_name() if it finds it.
- If not, MATLAB then searches the directories in its search path, in order, for func_name.m and then executes it if found.

The MATLAB Script Editor / Debugger Conditionals, Loops, Files

save & execute

comments

MATLAB

commands

Keep in mind when using script files: Conditionals, Loops, Files

- The name of a script file must begin with a letter, and may include digits and the underscore character, up to 31 characters
- Do not give a script file the same name as a variable
- Do not give a script file the same name as a MATLAB command or function; you can check to see if a command, function or file name already exists by using the exist() command

MATLAB User-Defined Functions Conditionals, Loops, Files

function [output variables] =

function_name (input variables)

- Note: [output variables]is NOT an array
- You may use multiple output variables separated by commas, but each will be output individually
- Example:

Function Definition

function [p,q]=two_out(x,y)

p = 17*x^2/y;

q = y*x/17*x;

Working Session

>> [s,t] = two_out(3,5)

s =

30.6000

t =

2.6471

MATLAB Plotting Conditionals, Loops, Files

>> x = [0:pi/10:2*pi];

>> y = sin(x);

>> plot(x,y,'g.-','MarkerSize',15,'LineWidth',2)

>> title('Example Plot of y = sin(x)');

>> xlabel('x (units)');

>> ylabel('y = sin(x)')

Plot Layout with Conditionals, Loops, Filessubplot()

>> x = [0:pi/10:2*pi];

>> y1 = sin(x); y2 = cos(x);

>> subplot(2,1,1)

>> plot(x,y1,'g.-','MarkerSize',15,'LineWidth',2)

>> xlabel('x (units)');

>> ylabel('y_1 = sin(x)')

>> subplot(2,1,2)

>> plot(x,y2,'g.-','MarkerSize',15,'LineWidth',2)

>> xlabel('x (units)');

>> ylabel('y_2 = cos(x)')

Conditional Statements Conditionals, Loops, Files

if x < 3

color = ‘r’;

elseif x < 7

color = ‘b’;

elseif x < 11

color = ‘c’;

else

color = ‘m’;

end

if x < 3

color = ‘r’;

else

if x < 7

color = ‘b’;

else

if x < 11

color = ‘c’;

else

color = ‘m’;

end

end

end

for Conditionals, Loops, Files Loops

- Standard structure…
for loop variable = min:inc:max

statements

end

- Basic example…
for k = 5:10:35

x = k^2

end

Note: if inc is not specified,it defaults to unity

k = 5, 15, 25, 35

x = 25, 225, 625, 1225

Importing Data from a Text File Conditionals, Loops, Files

- Using the load command…
>> load subject_data.dat;

>> s = load(‘subject_data.dat’);

Reads ASCII data in columns

Creates array named subject_data.dat

Reads ASCII data in columns

Creates array named s

Importing Data from a Text File (cont.) Conditionals, Loops, Files

- Using the dlmread command…
>> RESULT = DLMREAD(FILENAME,DELIMITER,R,C);

Reads delimited ASCII data starting at row R and column C

Creates array named RESULT

Importing Data from an Excel File Conditionals, Loops, Files

[num,txt] = xlsread(‘excel_filename.xls’)

- numeric data put into num variable
- text data put into txt variable

Saving Data to ASCII File Conditionals, Loops, Files

- Using the save command…
>> save filenamevar1 var2… –ASCII –tabs;

For example…

>> B = [2 6; 5 7; 8 4];

>> save array_B.dat B –ASCII –tabs;

Saves array B in the ASCII file array_B.dat

Columns of B become tab-delimited columns of array_B.dat

Saving Data to Binary File Conditionals, Loops, Files

- Using the save command…
>> save filenamevar1 var2…

For example…

>> B = [2 6; 5 7; 8 4];

>> save array_B B

Saves array B in the binary file array_B.mat

Advantage: binary files load faster than ascii

Download Presentation

Connecting to Server..