MATLAB: Strings and File IO



Similar documents
MATLAB: Structures and Cell Arrays

GUI Input and Output. Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University

2 Matlab Programming, IO, and strings

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Recognizing PL/SQL Lexical Units. Copyright 2007, Oracle. All rights reserved.

Sources: On the Web: Slides will be available on:

Storing Measurement Data

MATLAB Programming. Problem 1: Sequential

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Passing 1D arrays to functions.

Data Storage: Each time you create a variable in memory, a certain amount of memory is allocated for that variable based on its data type (or class).

Informatica e Sistemi in Tempo Reale

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Introduction to Python

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

This section describes how LabVIEW stores data in memory for controls, indicators, wires, and other objects.

Introduction to Python

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

2. The Open dialog box appears and you select Text Files (*.prn,*.txt,*.csv) from the drop-down list in the lower right-hand corner.

In order to print off elements as columns, use the \n command. The format commands will be used over and over until all the elements are printed.

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Microsoft Access 3: Understanding and Creating Queries

Answers to Review Questions Chapter 7

Lecture 4. Input and output. Scilab/Matlab automatically displays the value of a variable when you type its name at the command line.

MS Access: Advanced Tables and Queries. Lesson Notes Author: Pamela Schmidt

Introduction. Chapter 1

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Introduction to Java

C Strings and Pointers

Exercise 1: Python Language Basics

Chapter 2 Introduction to Java programming

Outline Basic concepts of Python language

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Beginner s Matlab Tutorial

CSCE 110 Programming I Basics of Python: Variables, Expressions, and Input/Output

Python Lists and Loops

Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

The programming language C. sws1 1

The University of Chicago Booth School of Business Tools for Business Analysis: Excel and Matlab Winter, 2012.

Python Programming: An Introduction to Computer Science

Intro to Embedded SQL Programming for ILE RPG Developers

5 Arrays and Pointers

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

C++ Language Tutorial

CAPIX Job Scheduler User Guide

Admin Guide Product version: Product date: November, Technical Administration Guide. General

Lab 2: MS ACCESS Tables

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Microsoft Access 2010

Variables, Constants, and Data Types

20 Using Scripts. (Programming without Parts) 20-1

Lexical Analysis and Scanning. Honors Compilers Feb 5 th 2001 Robert Dewar

Finding XSS in Real World

LabVIEW Day 6: Saving Files and Making Sub vis

Beyond the Mouse A Short Course on Programming

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Chapter 3. if 2 a i then location: = i. Page 40

Python Loops and String Manipulation

Introduction to Data Structures

Physical Design. Meeting the needs of the users is the gold standard against which we measure our success in creating a database.

Java Crash Course Part I

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

AMATH 352 Lecture 3 MATLAB Tutorial Starting MATLAB Entering Variables

MATLAB Functions. function [Out_1,Out_2,,Out_N] = function_name(in_1,in_2,,in_m)

1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier.

Numeral Systems. The number twenty-five can be represented in many ways: Decimal system (base 10): 25 Roman numerals:

Number Representation

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Database 2 Lecture I. Alessandro Artale

Using Files as Input/Output in Java 5.0 Applications

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Module 816. File Management in C. M. Campbell 1993 Deakin University

Introduction to Java. CS 3: Computer Programming in Java

Instructions for Using Excel as a Grade Book

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

2+2 Just type and press enter and the answer comes up ans = 4

FrontStream CRM Import Guide Page 2

14:440:127 Introduction to Computers for Engineers. Notes for Lecture 06

Solving Systems of Linear Equations Using Matrices

Setting up Auto Import/Export for Version 7

Java Basics: Data Types, Variables, and Loops

CS 1133, LAB 2: FUNCTIONS AND TESTING

MATLAB Basics MATLAB numbers and numeric formats

public static void main(string[] args) { System.out.println("hello, world"); } }

Chapter 2: Elements of Java

Base Conversion written by Cathy Saxton

SIF Validation Tool. Wages Protection System Qatar Central Bank& Ministry of Labour And Social Affairs. End User Guide

Using C# for Graphics and GUIs Handout #2

Transcription:

MATLAB: Strings and File IO Kipp Martin University of Chicago Booth School of Business February 9, 2012

The M-files The following files are used in this lecture. filein.txt fileio.m

Outline Strings File Input-Output

Strings In MATLAB everything is an array We can have an array of numbers (doubles) We can have an array of strings In this module we first look at strings.

Strings In MATLAB you can also work with strings. A string is a sequence of characters. The sequence can be digits, letters, symbols, and spaces enclosed by single quotation marks. Examples of string variables are x = abcd123 y = ae _ bx%$#( In MATLAB everything is an array so what have we created? >> whos Name Size Bytes Class x 1x7 14 char y 1x12 24 char Each character takes two bytes.

Strings Since a string is an array, you can access parts of the string just like you would any other array. For example >> y(5:7) ans = _ b >> x(1, 3) ans = c >> x(1,:) ans = abcd123

Strings It is also possible to define matrices where each row is a string. >> student_record =char( Name:, Joe Schmoe, Quiz 1 Score, 96 ) student_record = Name: Joe Schmoe Quiz 1 Score 96 >> whos student_record Name Size Bytes Class student_record 4x12 96 char Why 4 by 12? Where does the 12 come from?

Strings 8 We can address student record like any other matrix of numbers. >> student_record(2, [1:2, 10]) ans = Joe What! How did we get Joe? What will student_record(2, [1, 2, 5]) give?

Strings 9 Now what about something like: x = [ Hello ; Goodbye ] What will happen? As an alternative to the char function you can use the strvact function (it will automatically pad). >> x = strvcat( Hello, Goodbye ) x = Hello Goodbye >> whos Name Size Bytes Class x 2x7 28 char

Strings Here are some useful string functions in MATLAB. The strcmp function. This function will compare two strings and return a true if they are equal. False if not. Very useful in if statements. >> x =strcmp( hello, goodbye ) x = 0 >> y = strcmp( abc, abc ) y = 1

Strings The strcat function. This function is the equivalent of the & operator in VBA for strings. This function allows us to concatenate strings. >> x = William ; >> y = strcat(x, Barret, Travis ) y = William Barret Travis

Strings 12 We may wish to convert string data to numbers. Use str2num. >> x = 17.45 ; >> y = str2num(x) y = 17.4500 >> whos Name Size Bytes Class x 1x5 10 char y 1x1 8 double

Strings 13 We may wish doubles to strings. Use num2str. >> x = 77.11; >> y = num2str( x) y = 77.11 >> whos Name Size Bytes Class x 1x1 8 double y 1x5 10 char

File Input-Output It is pretty easy to read from and write to text files using MATLAB. See Chapter 4 of Gilat. Let s start with reading a file. Consider the file filein.txt Hi 1.77 Goodbye 34 a b, c, d HiAgain 1 54 3 4 17 16.6 77.7 7 9 10 11.4 27.2 11.9 Read the above file with fileio.m

File Input-Output First open the file. In VBA we had testfile = "C:\temp\data.txt" Open testfile For Input As #1 In MATLAB we have: fid = fopen( filein.txt ); I am assuming filein.txt is in the MATLAB path.

Read the first line: File Input-Output Hi 1.77 Goodbye 34 Use the code: v1 = fscanf(fid, %s, 1) v2 = fscanf(fid, %f, 1) v3 = fscanf(fid, %s, 1) v4 = fscanf(fid, %f, 1) Use the %s to read a string We read the first string until we hit the white space delimiter. The 1 is telling to read one string Use the %f to read a floating point number

File Input-Output Read the second line using the comma as a delimiter: a b, c, d Use the code v5 = fscanf(fid, %[^,], 1) fscanf(fid, %[,], 1) ; %trash the comma v6 = fscanf(fid, %[^,], 1) fscanf(fid, %[,], 1) ; %trash the comma v7 = fscanf(fid, %s, 1) I want to preserve the white space between a and b Use %[^,] to read all characters until a comma is found. Burn off the commas with %[,]

File Input-Output 18 Read the third line: HiAgain Use the code fgetl(fid); v8 = fscanf(fid, %s, 1) I use the fgetl(fid); to make sure I have read any control characters before going to the next line

File Input-Output Now read the fourth line 1 54 3 4 with the code x = fscanf(fid, %f %f %f %f, 4) What is x?

File Input-Output 20 Now read the all of the remaining numbers 17 16.6 77.7 7 9 10 11.4 27.2 11.9 using the code: k = 1; while ~feof(fid); A(k ) = fscanf(fid, %f, 1); k = k + 1; end;

File Input-Output Create a Structure From a File: Consider the following data set (studentdata.txt) Tom,Jones,57 Bill,Uehling,100 Mary,Honda,95 Kathy,Murigami,67 Bill,Jones,99 Jill,Doe,83 Mark,Anderson,56 Jody,Ruebush,99 Alice,Tyx,89 Mary,Chin,100 Richard,Valens,77 Tom,Choi,80 Dave,Sweeney,45 Download this file at the data link.

File Input-Output In-class Exercise: Read the file (studentdata.txt) and create a structure, studentstruct, that has the following properties: FirstName LastName Quiz1 Question: Instead of writing code to read a file, why not A = load( studentdata.txt ) and let MATLAB do the work?

File Input-Output Now let s write the input file we worked with. First open a file with write permission. fid = fopen( fileout.txt, w ); If you replace the w with a data will be appended to the end of the file. Write the first line. fprintf(fid, Hi %-5.2f Goodbye %i\n, 1.77, 34) We use \n to move the file pointer to a new line The %-5.2f and %i get replaced by 1.77 and 34, respectively. (the minus inf -5.2f causes left justification

File Input-Output Write the next two lines of text. fprintf(fid, a b, c, d\n ) fprintf(fid, HiAgain\n ) Next print the line of integers. fprintf(fid, %i %i %i %i\n, 1, 54, 3, 4)

File Input-Output Write the line of seven real numbers and then a new line. for i=1:7 fprintf(fid, %-5.1f, A( i)) end fprintf(fid, \n ) and then the last line fprintf(fid, %-5.1f %-5.1f \n, 27.2, 11.9)

File Input-Output Note that when we printed, we specified the file id (in this case fid) fprintf(fid, %-5.1f %-5.1f \n, 27.2, 11.9) You can also print directly to the screen fprintf( Print Directly to the screen\n ) Note that the file id is missing. If you do not care about formatting you can also print to the screen with the disp() function.