MATLAB: Structures and File I/O

Slides:



Advertisements
Similar presentations
Lecture 2 Introduction to C Programming
Advertisements

Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Introduction to C Programming
Shell Scripting Awk (part1) Awk Programming Language standard unix language that is geared for text processing and creating formatted reports but it.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 21P. 1Winter Quarter MATLAB: Structures.
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
C Programming n General Information on C n Data Types n Arithmetic Operators n Relational Operators n if, if-else, for, while by Kulapan Waranyuwat.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
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.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
Programming Fundamentals. The setw Manipulator setw changes the field width of output. The setw manipulator causes the number (or string) that follows.
1 An Introduction to R © 2009 Dan Nettleton. 2 Preliminaries Throughout these slides, red text indicates text that is typed at the R prompt or text that.
Expressions and Order of Operations Operators – There are the standard operators: add, subtract, divide, multiply – Note that * means multiply? (No times.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
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.
User-Written Functions
EEE 161 Applied Electromagnetics
Loops BIS1523 – Lecture 10.
Chapter 2 - Introduction to C Programming
2.5 Another Java Application: Adding Integers
IF statements.
Introduction to Scripting
Other Kinds of Arrays Chapter 11
Scripts & Functions Scripts and functions are contained in .m-files
Chapter 2 - Introduction to C Programming
Control Structures – Selection
11/10/2018.
Arrays, For loop While loop Do while loop
More Selections BIS1523 – Lecture 9.
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Topics Introduction to File Input and Output
Conditions and Ifs BIS1523 – Lecture 8.
Expressions Chapter 4 Copyright © 2008 W. W. Norton & Company.
Matlab review Matlab is a numerical analysis system
Chapter 2 - Introduction to C Programming
T. Jumana Abu Shmais – AOU - Riyadh
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Logical Operations In Matlab.
Chapter 2 - Introduction to C Programming
MATLAB Logical Expressions
Simulation And Modelling
INTRODUCTION TO MATLAB
HYPERTEXT PREPROCESSOR BY : UMA KAKKAR
Note on Indexing of Array Elements
Arrays Arrays A few types Structures of related data items
Chapter 2 - Introduction to C Programming
Matlab Basics.
Comparing Python and Java
Chap 7. Advanced Control Statements in Java
EECE.2160 ECE Application Programming
Topics Introduction to File Input and Output
Introduction to C Programming
Controlling Program Flow
Web Programming and Design
Presentation transcript:

MATLAB: Structures and File I/O Lecture 21 Instructor notes: Winter Quarter

MATLAB Relational Operators MATLAB supports six relational operators. Less Than < Less Than or Equal <= Greater Than > Greater Than or Equal >= Equal To == Not Equal To ~= Instructor notes: Matlab has six relational operators that are used in making comparisons just like in C/C++. It is probably a good thing to emphasize to the students that the relational operators in Matlab are the same as they are in C/C++ EXCEPT for “not equal to” which uses the ~ instead of the ! as part of the operator. Students should be reminded to pay close attention to which language they’re writing in on exams so that they do not mix the two. Winter Quarter

MATLAB Logical Operators MATLAB supports three logical operators. not ~ % highest precedence and & % next highest precedence or | % next highest precedence Instructor notes: In addition to the relational operators, Matlab has three logical operators, not, and, and or. A couple differences from C/C++ that are important. First, rather than using the ! for not as in C/C++, the ~ is used. Given the information on the previous slide, this is no surprise. The second difference is that in C/C++ when using logical operators && is a logical and operator and & is a bitwise operator, likewise || is a logical or operator and | is a bitwise operator. However, in Matlab, & and | are logical operators. Winter Quarter

MATLAB Selection Structures An if - elseif - else structure in MATLAB. Note that elseif is one word. if expression1 % is true % execute these commands elseif expression2 % is true else % the default end Instructor notes: Like C/C++ Matlab has an if-elseif-else structure for decision making or branching. There are a few differences between Matlab and C/C++. In Matlab, elseif is one word, rather than two, as it is in C/C++. Curly brackets are not used in Matlab at all, and the end of the if-elseif-else block is denoted with end. Just like in C/C++ expressions are evaluated to be true or false and when an expression evaluates to true, then the statements that correspond to that section of the block are executed. Parentheses are not required around the expression being evaluated. Winter Quarter

MATLAB Repetition Structures A for loop in MATLAB for x = array for x=1: 0.5 : 10 % execute these commands end A while loop in MATLAB while expression while x <= 10 % execute these commands Instructor notes: Again, as in C/C++ Matlab has looping structures. Matlab has a for loop that is very much like C/C++’s, but with some slight differences. Curly brackets are not needed in Matlab’s for loop. The counter variable is initialized at the beginning of the loop in an assignment statement. Colons are used to separate the initial value from the increment and end point, respectively. If no increment is specified, then it is assumed to be 1. The end statement marks the end of the while loop. The while loop in Matlab is also much like in C/C++, but with some differences. No curly brackets are needed in Matlab and the end of the loop is denoted with the end statement. Matlab does not have a do-while loop like C/C++. It might be a good idea to point out that often in Matlab loops that access arrays begin with 1 rather than 0 as they normally do in C/C++. This is because the first index in a Matlab array is 1 while the first index in a C/C++ array is 0. Winter Quarter

Scalar - Matrix Addition EDU» a=3; EDU» b=[1, 2, 3;4, 5, 6] b = 1 2 3 4 5 6 EDU» c= b+a % Add a to each element of b c = 7 8 9 Instructor notes: The next four slides deal with scalar-matrix math, addition, subtraction, multiplication, and division. In scalar-matrix math the scalar and each individual element of the matrix interact based on the operation being performed. So, if a scalar is being added to a matrix, that scalar will be added to each element in the matrix resulting in a matrix of the same dimensions with each element being modified by the sum of the element and the scalar. Remember, addition and multiplication are commutative, so the order of the operation does not matter. Subtraction and division are not commutative. Also, Matlab will not allow you to divide the scalar by the matrix. It will return an error message indicating that the matrix dimensions do not match. Winter Quarter

Scalar - Matrix Subtraction EDU» a=3; EDU» b=[1, 2, 3;4, 5, 6] b = 1 2 3 4 5 6 EDU» c = b - a %Subtract a from each element of b c = -2 -1 0 Instructor notes: Winter Quarter

Scalar - Matrix Multiplication EDU» a=3; EDU» b=[1, 2, 3;4, 5, 6] b = 1 2 3 4 5 6 EDU» c = a * b % Multiply each element of b by a c = 3 6 9 12 15 18 Instructor notes: c = b * a will produce the same results. Winter Quarter

Scalar - Matrix Division EDU» a=3; EDU» b=[1, 2, 3;4, 5, 6] b = 1 2 3 4 5 6 EDU» c = b / a % Divide each element of b by a c = 0.3333 0.6667 1.0000 1.3333 1.6667 2.0000 Instructor notes: c = a/b will produce an error message. Winter Quarter

Reading Data from Files The load command does not always succeed in reading an input file. It only works when all lines in the file have the same ASCII format. Files with header material do not qualify, nor do binary files. ASCII files that cannot be input with the load function can be opened and input with MATLAB functions that are similar to C language functions we have been using. The MATLAB functions include fopen, fgets, fscanf, and sscanf. Instructor notes: Previously we covered the load () command which can be used to read a data file into Matlab and place the data read in into a matrix of the same name as the file minus any extension. However, load () does not work with all files. It does not work with binary files and files that do not have a consistent format, such as those with header information at the top. Fortunately there are options that begin with the fopen () command and include other functions similar to C functions. Winter Quarter

outfile_id = fopen('filename','w'); Opening Data files The command to open a file for input is: infile_id = fopen('filename','r'); The command to open a file for output is: outfile_id = fopen('filename','w'); Instructor notes: Files can be opened for reading or writing, the mechanism is the same except that the second argument in the function is ‘r’ for reading and ‘w’ for writing. fopen () requires as its first argument the name of the file to be opened contained in single quotes. fopen () returns a file id that will be used to access the contents of the file once it has been opened. Winter Quarter

Inputing Data from Open Files After the file is opened for reading we can input one line at a time as a text string. The command to read one line from the file as a string is: line = fgets (infile_id); If the remainder of the data in the file all has the same format we can read the rest of the file and store it in an array with the command: myarray = fscanf(infile_id,... '%*s%*s%*s%f'); Instructor notes: Once a file has been opened for reading there are various functions available for reading data from files that offer varying degrees of control on how data is read from the file. The fgets () function allows an entire line to be read in at a time as a text string. The only argument that fgets () requires is an identifier to a file that was previously opened for reading using fopen (). The fgets () function is well suited for reading in lines of header information before using more specifically formatted reading of the desired data. The fscanf () function can be used to read individual data elements in a file and works very much like its C/C++ counterpart. fscanf () requires a file identifier to an opened file, and a format specifier string that tells fscanf () what type of data is being read on each line. The data read in by fscanf () will be placed in an array. Winter Quarter

Inputting Data from Open Files Data that has been read in as a string using fgets can be parsed using the function sscanf. The syntax to input a line and then extract and discard three columns from the string and save the fourth column of floating point data in an element in the array myarray would be: line = fgets(infile_id); myarray(k)=sscanf(line,'%*s%*s%*s%f'); Instructor notes: Although the fgets () function is nice for reading in an entire line at a time, it forces the line to be treated as a string and does not give us immediate access to the individual components of the string. Fortunately the string can be parsed using the sscanf () function to give us access to the individual elements of interest. The sscanf () function requires a string variable as its first argument, followed by a format specifier string that tells Matlab what types of variables to parse the string into. Winter Quarter

Note on Indexing of Array Elements Indexing in C/C++ float myarray[20]; int i; for (i = 0; i < 20; i++) { myarray[ i ] = 0.0; } Indexing in MATLAB % No declarations % are necessary for i = [1:20] myarray( i ) = 0.0; end Instructor notes: Some differences in indexing between C/C++ and Matlab include: (1) while C/C++ requires that variables be declared prior to use, Matlab does not require declarations. (2) Array indices in C/C++ start at zero, while array indices in Matlab start counting at 1. Winter Quarter

fprintf(outfile_id,'%s',line); fprintf(outfile_id,'%f%f\n',a,b); Printing Data to Files When a file has been opened for output, the command to output one line to the file as a string is: fprintf(outfile_id,'%s',line); Lines of other data can be output by inserting the appropriate format string and variable names. For example: fprintf(outfile_id,'%f%f\n',a,b); Instructor notes: Writing output to files is very much like it is in C/C++ using the fprintf () function. The fprintf () function takes an identifier to a file previously opened for writing as its first argument. This is followed by a format specifier string in single quotes to tell Matlab how to write the data to the file. The final argument given to fprintf () are the values or variables that are being written to the file. For each item indicated by the format specifier string, there must be a corresponding value or variable argument passed to fprintf (). Winter Quarter

and to print other data we might use: fprintf('%f %f\n', a , b) Printing to the Screen Data can also be printed to the screen with the fprintf function. To do so, we omit the file idenification (outfile_id). For instance, to print a line of text to the screen we could use: fprintf('%s',line) and to print other data we might use: fprintf('%f %f\n', a , b) Instructor notes: Just as data can be written to a file with control over the formatting, the data can be written to the screen in the command window, too. This is done by using the fprintf () function, but leaving out the file identifier argument. With no file identifier supplied, Matlab assumes that it should be writing to the screen. Entire lines of text can be written out as strings, as well as individual data points. Winter Quarter