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

Slides:



Advertisements
Similar presentations
Matlab Intro Simple introduction to some basic Matlab syntax. Declaration of a variable [ ] Matrices or vectors Some special (useful) syntax. Control statements.
Advertisements

MATLAB – A Computational Methods By Rohit Khokher Department of Computer Science, Sharda University, Greater Noida, India MATLAB – A Computational Methods.
COMP 116: Introduction to Scientific Programming Lecture 37: Final Review.
M AT L AB Programming: scripts & functions. Scripts It is possible to achieve a lot simply by executing one command at a time on the command line (even.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
M AT L AB Reading & Writing Files. Low-level file input and output is very similar to that in 'C', but with inherent vectorization. Files are opened with.
Fprintf and other examples. Save command >> !ls >> a = 3; >> save afile a >> !ls afile.mat >> !dir Directory of C:\MATLAB6p5\work\save 11/21/ :30.
General Computer Science for Engineers CISC 106 Lecture 04 Roger Craig Computer and Information Sciences 9/11/2009.
Matlab Matlab is a powerful mathematical tool and this tutorial is intended to be an introduction to some of the functions that you might find useful.
Input/Output Functions Selim Aksoy Bilkent University Department of Computer Engineering
Input/Output Functions Selim Aksoy Bilkent University Department of Computer Engineering
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Chapter 9 Above: An early computer input/output device on the IBM 7030 (STRETCH)
Extending MATLAB Write your own scripts and/or functions Scripts and functions are plain text files with extension.m (m-files) To execute commands contained.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 21P. 1Winter Quarter MATLAB: Structures.
Chapter 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Mathcad Variable Names A string of characters (including numbers and some “special” characters (e.g. #, %, _, and a few more) Cannot start with a number.
Engineering Analysis ENG 3420 Fall 2009 Dan C. Marinescu Office: HEC 439 B Office hours: Tu-Th 11:00-12:00.
Slide deck by Dr. Greg Reese Miami University MATLAB An Introduction With Applications, 5 th Edition Dr. Amos Gilat The Ohio State University Chapter 4.
Analytical vs. Numerical Minimization Each experimental data point, l, has an error, ε l, associated with it ‣ Difference between the experimentally measured.
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
Matlab Programming, part 1 M-files It is generally more convenient to program in Matlab using m-files, ascii text files containing a set of Matlab commands.
Matlab Basics Tutorial. Vectors Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between.
Matlab Training Session 10: Loading Binary Data Course Website: Training Sessions.htm.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
1 Input / Output Input – reads/gets data for the program Output – the product, after processing Both can be: interactive I/O (while program is running)
ENG College of Engineering Engineering Education Innovation Center 1 Array Accessing and Strings in MATLAB Topics Covered: 1.Array addressing. 2.
Working with Arrays in MATLAB
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
COMP 116: Introduction to Scientific Programming Lecture 29: File I/O.
Analyzing Functions (4.16) y=f(x) MATLAB. Functional Analysis includes: Plotting and evaluating a function Finding extreme points Finding the roots (zeros.
EGR 115 Introduction to Computing for Engineers Formatted File Input / Output Wednesday 12 Nov 2014 EGR 115 Introduction to Computing for Engineers.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Files: By the end of this class you should be able to: Prepare for EXAM 1. create an ASCII file describe the nature of an ASCII text Use and describe string.
Recap Cubic Spline Interpolation Multidimensional Interpolation Curve Fitting Linear Regression Polynomial Regression The Polyval Function The Interactive.
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
Input Output Garbage In, Garbage Out. Outline Announcements: –Homework III: due Today. by 5, by Discuss on Friday. –Homework IV: on web, due following.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Strings Characters and Sentences 1.Overview 2.Creating Strings 3.Slicing Strings 4.Searching for substrings 1.
Introduction to Programming on MATLAB Ecological Modeling Course Sep 11th, 2006.
Input Output Garbage In, Garbage Out. Outline Announcements: –HWII solutions on web soon –Homework III: due Wednesday Advanced ASCII Binary Basics Cell-arrays.
Beginning Programming for Engineers Animation. Special matrix functions >> clear >> ones(2,3) >> zeros(3,5) >> ones(2) >> zeros(3) >> eye(4) >> magic(4)
Chapter 1 Computing Tools Variables, Scalars, and Arrays Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Input Output Garbage In, Garbage Out. Outline Announcements: –Homework III: due Wednesday Advanced ASCII Binary Basics Filesystem Fun.
Input/Output Functions. 2 MATLAB Basics: Data Files save filename var1 var2 … save homework.mat x y  binary save x.dat x – ascii  ascii load filename.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Input Output IO and datafiles Credits also to Prof Selim Aksoy (Bilkent University.
Reading and Writing Data Files
User-Written Functions
Introduction to MATLAB
Some Matlab Tips CSE 4309 – Machine Learning Vassilis Athitsos
Other Kinds of Arrays Chapter 11
Scripts & Functions Scripts and functions are contained in .m-files
MATLAB: Structures and File I/O
Lecture 13 Input/Output Files.
Matlab review Matlab is a numerical analysis system
String Manipulation Chapter 7 Attaway MATLAB 4E.
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Matlab Training Session 5: Importing Data
funCTIONs and Data Import/Export
Note on Indexing of Array Elements
Input/Output Functions
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Introduction to MATLAB
Input/Output Functions
Working with Arrays in MATLAB
Arrays.
Chapter 2 MATLAB Environment
Presentation transcript:

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 Don’t want to repeat time consuming calculations

Saving Variables Sometimes you might want to save some or all of your workspace MATLAB allows you to save variables from the console workspace

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

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

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

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

Input from a File Opening a file fid = fopen(filename, ‘r’); –fid = -1 means can’t open file Reading formatted data result = fscanf(fid, format); Reading a line line = fgetl(fid); % fgets keeps end-of-line char Closing a file fclose(fid);

Input from a File Block Properties Temp Press Vol >> fid = fopen(‘data.in’, ‘r’); >> fgetl(fid); >> T = scanf(fid,‘%g%g%d’) >> fclose(fid) data.in

Input from a File Block Properties Temp Press Vol >> fid = fopen(‘data.in’, ‘r’); >> fgetl(fid); >> T = scanf(fid,‘%g%g%d’) >> fclose(fid) data.in

Input from a File Block Properties Temp Press Vol data.in >> fid = fopen(‘data.in’, ‘r’); >> fgetl(fid); >> T = scanf(fid,‘%g%g%d’) >> fclose(fid)

Input from a File Block Properties Temp Press Vol data.in >> fid = fopen(‘data.in’, ‘r’); >> fgetl(fid); >> T = scanf(fid,‘%g%g%d’) >> fclose(fid) Read a real Read an integer

Input from a File Block Properties Temp Press Vol data.in >> fid = fopen(‘data.in’, ‘r’); >> fgetl(fid); >> T = scanf(fid,‘%g%g%d’) >> fclose(fid) Read a real Read an integer

Input from a File Block Properties Temp Press Vol data.in >> fid = fopen(‘data.in’, ‘r’); >> fgetl(fid); >> T = scanf(fid,‘%g%g%d’) >> fclose(fid) Read a real Read an integer

Input from a File Block Properties Temp Press Vol >> fid = fopen(‘data.in’, ‘r’); >> fgetl(fid); >> T = scanf(fid,‘%g%g%d’) >> fclose(fid) data.in Read a real Read an integer

Input from a File Block Properties Temp Press Vol >> fid = fopen(‘data.in’, ‘r’); >> fgetl(fid); >> T = scanf(fid,‘%g%g%d’) >> fclose(fid) data.in

Input from a File Block Properties Temp Press Vol T = 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

Output to a File Open a file also using fopen fid = fopen(filename, ‘w’); –‘w’ means write and create if necessary –replacing ‘w’ by ‘a’ means append (also creating) Writing formatted data fprintf(fid, format, data) Writing a line fprintf(fid, ‘…\n’, data) Use fclose to close a file and write it

Output to a File >> T = [ ; ; ; ]; >> 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)

Output to a File >> T = [ ; ; ; ]; >> 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

Output to a File Block Properties >> T = [ ; ; ; ]; >> 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

Output to a File Block Properties Temp Press Vol >> T = [ ; ; ; ]; >> 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

Output to a File Block Properties Temp Press Vol >> T = [ ; ; ; ]; >> 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)

Output to a File Block Properties Temp Press Vol >> T = [ ; ; ; ]; >> 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)

Output to a File Block Properties Temp Press Vol >> T = [ ; ; ; ]; >> 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

Output to a File Block Properties Temp Press Vol >> T = [ ; ; ; ]; >> 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

Output to a File Block Properties Temp Press Vol >> T = [ ; ; ; ]; >> 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

Output to a File Block Properties Temp Press Vol >> T = [ ; ; ; ]; >> 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

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)

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, blah else error([‘Could not open file ‘ filename]); end; These lines check if the file has been opened and writes an error if it was not

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) | Year Rainforest Location |

Lab 6 Example (p. 128) years = fscanf(fid, ‘%d’, numyears); This line reads the years following the | from the file fgetl(fid); These lines read the remainder of the heading line and the table separator Rainforest Location |

Lab 6 Example (p. 128) for n = 1:numnames, Read a row from the file end; 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

Lab 6 Example (p. 128) name = ‘’; c = ‘ ’; while c ~= ‘|’, c = fscanf(fid, ‘%c’, 1); if c ~= ‘|’, name = [name c]; 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 |

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 | India |

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 )

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)

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 string int2str

The eval function eval(string); Evaluates the string as a command eval(‘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 result1 result2. result10

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

Using feval Calculate the forward difference of a function function df = fordiff(func, x, h) df = (feval(func, x + h) – feval(func, x)) / h; return;

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:

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:

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:

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: fminfind minima of a function fzerofind zeros of a function fplotplot a function quadintegral of a function ode23solves ordinary differential equations ode45solves ordinary differential equations

Example of Function-functions Plot the function y=x 3 -x

Example of Function-functions Function: function y=cubic(x) y=x.^3-x; return; Plot the function y=x 3 -x

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=x 3 -x

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=x 3 -x Vector of closely spaced x values to give smooth curve

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=x 3 -x Vector of closely spaced x values to give smooth curve

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=x 3 -x Vector of closely spaced x values to give smooth curve Restricted in how we can define cubic by the guidelines given by fplot

Using Function-functions to Solve an Ordinary Differential Equation Example:An object dropping under the influence of gravity and air friction:

Using Function-functions to Solve an Ordinary Differential Equation Example:An object dropping under the influence of gravity and air friction: dV dt = G - fV

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 dV dt = G - fV

Using Function-functions to Solve an Ordinary Differential Equation Set up a function to compute the derivative, dV/dt:

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;

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:

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

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

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

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

Next Week… Simple Plots (Revised) Getting more out of your plots Drawing multiple plots