Presentation is loading. Please wait.

Presentation is loading. Please wait.

MATLAB: Structures and File I/O

Similar presentations


Presentation on theme: "MATLAB: Structures and File I/O"— Presentation transcript:

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

2 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

3 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

4 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

5 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

6 Scalar - Matrix Addition
EDU» a=3; EDU» b=[1, 2, 3;4, 5, 6] b = EDU» c= b+a % Add a to each element of b c = 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

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

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

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

10 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

11 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

12 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

13 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

14 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

15 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

16 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


Download ppt "MATLAB: Structures and File I/O"

Similar presentations


Ads by Google