using and programming with matlab as an engineering tool [ part iii ]

63
Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Upload: peigi

Post on 22-Jan-2016

25 views

Category:

Documents


0 download

DESCRIPTION

Using and Programming with MATLAB as an Engineering Tool [ Part III ]. Lecture outline. Saving variables Basic file input/output Evaluating string commands Functions of functions. Saving Variables. Sometimes you might want to save some or all of your workspace. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Using and Programming with MATLAB as an Engineering

Tool[ Part III ]

Page 2: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Lecture outline

• Saving variables

• Basic file input/output

• Evaluating string commands

• Functions of functions

Page 3: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Saving Variables

• Sometimes you might want to save some or all of your workspace

Don’t want to repeat time consuming calculations

Page 4: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Saving Variables

• Sometimes you might want to save some or all of your workspace

• MATLAB allows you to save variables from the console workspace

Page 5: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Saving Variables

• Sometimes you might want to save some or all of your workspace

• MATLAB allows you to save variables from the console workspace

• You can load these variables whenever you need them

Page 6: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Saving Variables

• Sometimes you might want to save some or all of your workspace

• MATLAB allows you to save variables from the console workspace

• You can load these variables whenever you need them

Mat-files

Page 7: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Saving Variables

>> save• Saves the entire workspace to matlab.mat

>> save points.mat x y• Saves x and y in points.mat

>> save change dx dy dz• Saves dx, dy and dz in change.mat

>> save coord.dat x y z –ascii• Saves x, y and z in coord.dat in ASCII format

Page 8: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Loading Variables

>> load• Loads the variables in matlab.mat

>> load change• Loads the variables in change.mat

>> load coord.dat –ascii• Loads the variables in ASCII file coord.dat

>> load points x• Only loads x from points.mat

Page 9: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Input from a File• Opening a filefid = fopen(filename, ‘r’);

– fid = -1 means can’t open file

• Reading formatted dataresult = fscanf(fid, format);• Reading a lineline = fgetl(fid); % fgets keeps end-of-line char• Closing a filefclose(fid);

Page 10: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Input from a FileBlock Properties

Temp Press Vol

23.5 1.45 7

29.8 2.55 6

13.5 0.67 8

31.4 2.86 5

>> fid = fopen(‘data.in’, ‘r’);

>> fgetl(fid);

>> fgetl(fid);

>> T = scanf(fid,‘%g%g%d’)

>> fclose(fid)

data.in

Page 11: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Input from a FileBlock Properties

Temp Press Vol

23.5 1.45 7

29.8 2.55 6

13.5 0.67 8

31.4 2.86 5

>> fid = fopen(‘data.in’, ‘r’);

>> fgetl(fid);

>> fgetl(fid);

>> T = scanf(fid,‘%g%g%d’)

>> fclose(fid)

data.in

Page 12: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Input from a FileBlock Properties

Temp Press Vol

23.5 1.45 7

29.8 2.55 6

13.5 0.67 8

31.4 2.86 5

data.in>> fid = fopen(‘data.in’, ‘r’);

>> fgetl(fid);

>> fgetl(fid);

>> T = scanf(fid,‘%g%g%d’)

>> fclose(fid)

Page 13: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Input from a FileBlock Properties

Temp Press Vol

23.5 1.45 7

29.8 2.55 6

13.5 0.67 8

31.4 2.86 5

data.in>> fid = fopen(‘data.in’, ‘r’);

>> fgetl(fid);

>> fgetl(fid);

>> T = scanf(fid,‘%g%g%d’)

>> fclose(fid)

Read a real

Read an integer

Page 14: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Input from a FileBlock Properties

Temp Press Vol

23.5 1.45 7

29.8 2.55 6

13.5 0.67 8

31.4 2.86 5

data.in>> fid = fopen(‘data.in’, ‘r’);

>> fgetl(fid);

>> fgetl(fid);

>> T = scanf(fid,‘%g%g%d’)

>> fclose(fid)

Read a real

Read an integer

Page 15: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Input from a FileBlock Properties

Temp Press Vol

23.5 1.45 7

29.8 2.55 6

13.5 0.67 8

31.4 2.86 5

data.in>> fid = fopen(‘data.in’, ‘r’);

>> fgetl(fid);

>> fgetl(fid);

>> T = scanf(fid,‘%g%g%d’)

>> fclose(fid)

Read a real

Read an integer

Page 16: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Input from a FileBlock Properties

Temp Press Vol

23.5 1.45 7

29.8 2.55 6

13.5 0.67 8

31.4 2.86 5

>> fid = fopen(‘data.in’, ‘r’);

>> fgetl(fid);

>> fgetl(fid);

>> T = scanf(fid,‘%g%g%d’)

>> fclose(fid)

data.in

Read a real

Read an integer

Page 17: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Input from a FileBlock Properties

Temp Press Vol

23.5 1.45 7

29.8 2.55 6

13.5 0.67 8

31.4 2.86 5

>> fid = fopen(‘data.in’, ‘r’);

>> fgetl(fid);

>> fgetl(fid);

>> T = scanf(fid,‘%g%g%d’)

>> fclose(fid)

data.in

Page 18: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Input from a FileBlock Properties

Temp Press Vol

23.5 1.45 7

29.8 2.55 6

13.5 0.67 8

31.4 2.86 5

T =

23.5000 1.4500 7.0000 29.8000 2.5500 6.0000 13.5000 0.6700 8.0000 31.4000 2.8600 5.0000

data.in

Need to manipulate T into matrix form

T = zeros(4, 3);for i = 1:4, T(i, :) = fscanf(fid, … ‘%g%g%d’, 3);end

Read three values

Page 19: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Output to a File

• Open a file also using fopenfid = fopen(filename, ‘w’);

– ‘w’ means write and create if necessary– replacing ‘w’ by ‘a’ means append (also creating)

• Writing formatted datafprintf(fid, format, data)• Writing a linefprintf(fid, ‘…\n’, data)• Use fclose to close a file and write it

Page 20: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Output to a File>> T = [ 23.5 1.45 7;

29.8 2.55 6;

13.5 0.67 8;

31.4 2.86 5];

>> fid = fopen(‘data.out’, ‘w’);

>> fprintf(fid, ‘Block Properties\n’);

>> fprintf(fid, ‘Temp Press Vol\n’);

>> fprintf(fid, …

‘ %3.1f %3.2f %d\n’, T’);

>> fclose(fid)

Page 21: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Output to a File>> T = [ 23.5 1.45 7;

29.8 2.55 6;

13.5 0.67 8;

31.4 2.86 5];

>> fid = fopen(‘data.out’, ‘w’);

>> fprintf(fid, ‘Block Properties\n’);

>> fprintf(fid, ‘Temp Press Vol\n’);

>> fprintf(fid, …

‘ %3.1f %3.2f %d\n’, T’);

>> fclose(fid)

data.out

Page 22: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Output to a FileBlock Properties >> T = [ 23.5 1.45 7;

29.8 2.55 6;

13.5 0.67 8;

31.4 2.86 5];

>> fid = fopen(‘data.out’, ‘w’);

>> fprintf(fid, ‘Block Properties\n’);

>> fprintf(fid, ‘Temp Press Vol\n’);

>> fprintf(fid, …

‘ %3.1f %3.2f %d\n’, T’);

>> fclose(fid)

data.out

Page 23: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Output to a FileBlock Properties

Temp Press Vol

>> T = [ 23.5 1.45 7;

29.8 2.55 6;

13.5 0.67 8;

31.4 2.86 5];

>> fid = fopen(‘data.out’, ‘w’);

>> fprintf(fid, ‘Block Properties\n’);

>> fprintf(fid, ‘Temp Press Vol\n’);

>> fprintf(fid, …

‘ %3.1f %3.2f %d\n’, T’);

>> fclose(fid)

data.out

Moves columnwise

Page 24: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Output to a FileBlock Properties

Temp Press Vol

>> T = [ 23.5 1.45 7;

29.8 2.55 6;

13.5 0.67 8;

31.4 2.86 5];

>> fid = fopen(‘data.out’, ‘w’);

>> fprintf(fid, ‘Block Properties\n’);

>> fprintf(fid, ‘Temp Press Vol\n’);

>> fprintf(fid, …

‘ %3.1f %3.2f %d\n’, T’);

>> fclose(fid)

data.out

Width 3 chars, 1 dp

Width 3 chars, 2 dp

integer (no width)

Page 25: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Output to a FileBlock Properties

Temp Press Vol

23.5 1.45 7

>> T = [ 23.5 1.45 7;

29.8 2.55 6;

13.5 0.67 8;

31.4 2.86 5];

>> fid = fopen(‘data.out’, ‘w’);

>> fprintf(fid, ‘Block Properties\n’);

>> fprintf(fid, ‘Temp Press Vol\n’);

>> fprintf(fid, …

‘ %3.1f %3.2f %d\n’, T’);

>> fclose(fid)

data.out

Width 3 chars, 1 dp

Width 3 chars, 2 dp

integer (no width)

Page 26: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Output to a FileBlock Properties

Temp Press Vol

23.5 1.45 7

29.8 2.55 6

>> T = [ 23.5 1.45 7;

29.8 2.55 6;

13.5 0.67 8;

31.4 2.86 5];

>> fid = fopen(‘data.out’, ‘w’);

>> fprintf(fid, ‘Block Properties\n’);

>> fprintf(fid, ‘Temp Press Vol\n’);

>> fprintf(fid, …

‘ %3.1f %3.2f %d\n’, T’);

>> fclose(fid)

data.out

Page 27: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Output to a FileBlock Properties

Temp Press Vol

23.5 1.45 7

29.8 2.55 6

13.5 0.67 8

>> T = [ 23.5 1.45 7;

29.8 2.55 6;

13.5 0.67 8;

31.4 2.86 5];

>> fid = fopen(‘data.out’, ‘w’);

>> fprintf(fid, ‘Block Properties\n’);

>> fprintf(fid, ‘Temp Press Vol\n’);

>> fprintf(fid, …

‘ %3.1f %3.2f %d\n’, T’);

>> fclose(fid)

data.out

Page 28: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Output to a FileBlock Properties

Temp Press Vol

23.5 1.45 7

29.8 2.55 6

13.5 0.67 8

31.4 2.86 5

>> T = [ 23.5 1.45 7;

29.8 2.55 6;

13.5 0.67 8;

31.4 2.86 5];

>> fid = fopen(‘data.out’, ‘w’);

>> fprintf(fid, ‘Block Properties\n’);

>> fprintf(fid, ‘Temp Press Vol\n’);

>> fprintf(fid, …

‘ %3.1f %3.2f %d\n’, T’);

>> fclose(fid)

data.out

Page 29: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Output to a FileBlock Properties

Temp Press Vol

23.5 1.45 7

29.8 2.55 6

13.5 0.67 8

31.4 2.86 5

>> T = [ 23.5 1.45 7;

29.8 2.55 6;

13.5 0.67 8;

31.4 2.86 5];

>> fid = fopen(‘data.out’, ‘w’);

>> fprintf(fid, ‘Block Properties\n’);

>> fprintf(fid, ‘Temp Press Vol\n’);

>> fprintf(fid, …

‘ %3.1f %3.2f %d\n’, T’);

>> fclose(fid)

data.out

Page 30: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Lab 6 Example (p. 128)

function [names, years, rain] = getrain(filename, numnames, numyears)

• This line defines a function with inputs– the file’s name (a string)

– the number of names to read (an integer)

– the number of years to read (an integer)

• and outputs– the names (a cell vector)

– the years (a integer vector)

– the rain (a real matrix)

Page 31: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Lab 6 Example (p. 128)

fid = fopen(filename, ‘r’);

• This line opens the file (as read only) and assigns a file identifier

if fid ~= -1,

blah, blah, blahelse

error([‘Could not open file ‘ filename]);end;

• These lines check if the file has been opened and writes an error if it was not

Page 32: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Lab 6 Example (p. 128)fgetl(fid);

• This line reads a line from the file– The table heading an column heading, e.g.,

c = ‘ ’;while c ~= ‘|’, c = fscanf(fid, ‘%c’, 1);end;

• These lines initialise a character c to be a space, then keep reading a new character from the file until a | is found

Rainfall (in) | YearRainforest Location | 1998 1999 2000 2001 2002

Page 33: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Lab 6 Example (p. 128)years = fscanf(fid, ‘%d’, numyears);

• This line reads the years following the | from the filefgetl(fid);

fgetl(fid);

• These lines read the remainder of the heading line and the table separator

Rainforest Location | 1998 1999 2000 2001 2002

----------------------------------------------

Page 34: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Lab 6 Example (p. 128)for n = 1:numnames,

Read a row from the fileend;

• These lines read numnames rows from the table using a for loop

names = cellstr(namematrix);

• This line creates a cell vector from a charatcer matrix (more later)

fclose(fid);

• This line closes the file

Page 35: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Lab 6 Example (p. 128)name = ‘’;c = ‘ ’;while c ~= ‘|’, c = fscanf(fid, ‘%c’, 1); if c ~= ‘|’, name = [name c]; end;end;namematrix(n, :) = name;

• These lines read a name from the table by reading characters and adding them to name, then setting the appropriate row of the namematrix

Zaire | 76 84 95 92 107

Page 36: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Lab 6 Example (p. 128)rain(n, :) = fscanf(fid, ‘%g’, numyears)’;

• This line reads the rainfall data for the given number of years and saves them in the rainfall matrix

fgetl(fid);

• This line reads the rest of the line and discards it

Zaire | 76 84 95 92 107India | 95 73 81 67 55

Page 37: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Lab 6 Example (p. 128)• What is a cell vector (or a cell matrix for that matter)?!names = cellstr(namematrix);

• Matlab stores information in matrices, each row must have the same number of columns

• What about a list of names, where the names have different lengths?

• We can use a matrix and fill the remaining columns with spaces (e.g., namematrix)

• Or we can use a cell vector or matrix structure where each entry may be a different size (e.g., names)

Page 38: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Cells

• No real details here (use help cell)

• Work similar to matrices and vectors except use {} instead of [], e.g.,

names{3} is the third name in names• What about names = cellstr(namematrix); ?

– Takes the charater matrix and turns it into a cell vector (removing leading and trailing whitespace)

Page 39: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

The sprintf function

string = sprintf(format, data);• Write formatted variables into a string

>> [‘Give the integer ‘ sprintf(‘%d’, 6) …

‘ a real format ‘ sprintf(‘%3.2f’, 6)]

ans =

Give the integer 6 a real format 6.00

Concatenated stringint2str

Page 40: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

The eval function

eval(string);• Evaluates the string as a commandeval(‘x = 5 * 6 / 2’) equivalent >> x = 5 * 6 / 2• Many uses, e. g., batch commands

for run = 1:10, outfile = [‘result’ int2str(run)]; % Do some calculations eval([‘save ‘ outfile])end

Creates files result1result2...

result10

Page 41: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

The feval function

value = feval(name, inputs);

• Evalutes the function call with the given inputs, i. e., value = name(inputs);

function y = mypoly(x)y = x.^2 + 2 * x + 1;return;

>> y = feval(‘mypoly’, 1)

y =

4

Page 42: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Using feval

• Calculate the forward difference

of a functionh

xfhxf )()(

function df = fordiff(func, x, h)

df = (feval(func, x + h) – feval(func, x)) / h;

return;

Page 43: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Passing Functions as Variables to Functions

• MATLAB has a collection of useful built in functions that require a function name be passed as an argument

• Function-functions

• Examples:

Page 44: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Passing Functions as Variables to Functions

• MATLAB has a collection of useful built in functions that require a function name be passed as an argument

• Function-functions

• Examples:

Page 45: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Passing Functions as Variables to Functions

• MATLAB has a collection of useful built in functions that require a function name be passed as an argument

• Function-functions

• Examples:

Page 46: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Passing Functions as Variables to Functions

• MATLAB has a collection of useful built in functions that require a function name be passed as an argument

• Function-functions

• Examples:fmin find minima of a functionfzero find zeros of a functionfplot plot a functionquad integral of a function

ode23 solves ordinary differential equations

ode45 solves ordinary differential equations

Page 47: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Example of Function-functionsPlot the function y=x3-x

Page 48: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Example of Function-functions

Function:function y=cubic(x) y=x.^3-x;return;

Plot the function y=x3-x

Page 49: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Example of Function-functions

x=0:0.01:1;y=cubic(x);plot(x,y);

One way:Function:function y=cubic(x) y=x.^3-x;return;

Plot the function y=x3-x

Page 50: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Example of Function-functions

x=0:0.01:1;y=cubic(x);plot(x,y);

One way:Function:function y=cubic(x) y=x.^3-x;return;

Plot the function y=x3-xVector of closely spaced x values to give smooth curve

Page 51: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Example of Function-functions

x=0:0.01:1;y=cubic(x);plot(x,y);

One way:Function:function y=cubic(x) y=x.^3-x;return;

fplot(‘cubic’,[0 1]);

Alternate:

Plot the function y=x3-xVector of closely spaced x values to give smooth curve

Page 52: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Example of Function-functions

x=0:0.01:1;y=cubic(x);plot(x,y);

One way:Function:function y=cubic(x) y=x.^3-x;return;

fplot(‘cubic’,[0 1]);

Alternate:

Plot the function y=x3-xVector of closely spaced x values to give smooth curve

Restricted in how we can define cubic by the guidelines given by fplot

Page 53: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Using Function-functions to Solve an Ordinary Differential

Equation

Example:An object dropping under the influence of gravity and air friction:

Page 54: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Using Function-functions to Solve an Ordinary Differential

Equation

Example:An object dropping under the influence of gravity and air friction:

dVdt

= G - fV

Page 55: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Using Function-functions to Solve an Ordinary Differential

Equation

Example:An object dropping under the influence of gravity and air friction:

G=9.81 m/s² and f=0.001/s

dVdt

= G - fV

Page 56: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Using Function-functions to Solve an Ordinary Differential

Equation

Set up a function to compute the derivative, dV/dt:

Page 57: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Using Function-functions to Solve an Ordinary Differential

Equation

Set up a function to compute the derivative, dV/dt:

function Vprime=drop(t,V) G = 9.81; f = 0.001; Vprime = G-f*V;return;

Page 58: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Using Function-functions to Solve an Ordinary Differential

Equation

Find and plot the velocity from time 0 seconds to 10 seconds with an initial velocity of 0 m/s:

Page 59: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Using Function-functions to Solve an Ordinary Differential

Equation

Find and plot the velocity from time 0 seconds to 10 seconds with an initial velocity of 0 m/s:

Timespan = [0 10];V0 = 0;[allt,allV]=ode23(‘drop’,timespan,V0);Plot(allt,allV);

range of time – start, end

Page 60: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Using Function-functions to Solve an Ordinary Differential

Equation

Find and plot the velocity from time 0 seconds to 10 seconds with an initial velocity of 0 m/s:

Timespan = [0 10];V0 = 0;[allt,allV]=ode23(‘drop’,timespan,V0);Plot(allt,allV);

initial value of V

Page 61: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Using Function-functions to Solve an Ordinary Differential

Equation

Find and plot the velocity from time 0 seconds to 10 seconds with an initial velocity of 0 m/s:

timespan = [0 10];V0 = 0;[allt,allV]=ode23(‘drop’,timespan,V0);Plot(allt,allV);

Call to MATLAB ODE function

Page 62: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Using Function-functions to Solve an Ordinary Differential

Equation

Find and plot the velocity from time 0 seconds to 10 seconds with an initial velocity of 0 m/s:

timespan = [0 10];V0 = 0;[allt,allV]=ode23(‘drop’,timespan,V0);plot(allt,allV); results are plotted

Page 63: Using and Programming with MATLAB as an Engineering Tool [ Part III ]

Next Week…

• Simple Plots (Revised)

• Getting more out of your plots

• Drawing multiple plots