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



Similar documents
Introduction to Matlab

MATLAB Programming. Problem 1: Sequential

2 Matlab Programming, IO, and strings

Introduction to Python

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

Simple File Input & Output

Chapter 7: Additional Topics

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

Chapter 2: Elements of Java

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

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.

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

Beginner s Matlab Tutorial

Decimal form. Fw.d Exponential form Ew.d Ew.dEe Scientific form ESw.d ESw.dEe Engineering form ENw.d ENw.dEe Lw. Horizontal

Getting started with the Stata

MATLAB: Strings and File IO

Appendix K Introduction to Microsoft Visual C++ 6.0

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

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

28 Simply Confirming Onsite

VHDL Test Bench Tutorial

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

Excel: Introduction to Formulas

MATLAB DFS. Interface Library. User Guide

Formatting Numbers with C++ Output Streams

MATLAB Tutorial. Chapter 6. Writing and calling functions

Lecture 2 Mathcad Basics

Advanced Tutorials. Numeric Data In SAS : Guidelines for Storage and Display Paul Gorrell, Social & Scientific Systems, Inc., Silver Spring, MD

Using SPSS, Chapter 2: Descriptive Statistics

How to Concatenate Cells in Microsoft Access

Content Author's Reference and Cookbook

AMATH 352 Lecture 3 MATLAB Tutorial Starting MATLAB Entering Variables

Introduction. Chapter 1

Importing and Exporting With SPSS for Windows 17 TUT 117

1 Topic. 2 Scilab. 2.1 What is Scilab?

A Program for PCB Estimation with Altium Designer

MATLAB Basics MATLAB numbers and numeric formats

Computational Mathematics with Python

FIRST STEPS WITH SCILAB

Informatica e Sistemi in Tempo Reale

LC-3 Assembly Language

13 File Output and Input

Simulation Tools. Python for MATLAB Users I. Claus Führer. Automn Claus Führer Simulation Tools Automn / 65

Version 1.5 Satlantic Inc.

Getting Started with R and RStudio 1

Introduction to Microsoft Excel 2007/2010

Data Storage. Chapter 3. Objectives. 3-1 Data Types. Data Inside the Computer. After studying this chapter, students should be able to:

Binary Adders: Half Adders and Full Adders

1 Description of The Simpletron

Euler s Method and Functions

grep, awk and sed three VERY useful command-line utilities Matt Probert, Uni of York grep = global regular expression print

Differences in Use between Calc and Excel

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

C++ Input/Output: Streams

IBM Unica emessage Version 8 Release 6 February 13, User's Guide

Using Casio Graphics Calculators

Secrets of printf. 1 Background. 2 Simple Printing. Professor Don Colton. Brigham Young University Hawaii. 2.1 Naturally Special Characters

Calculator Notes for the TI-Nspire and TI-Nspire CAS

Computational Mathematics with Python

Computational Mathematics with Python

Media Console Using Atlas Import Wizard

3.GETTING STARTED WITH ORACLE8i

1 Organizing time series in Matlab structures

Password Depot for ios

How to test and debug an ASP.NET application

This Unit: Floating Point Arithmetic. CIS 371 Computer Organization and Design. Readings. Floating Point (FP) Numbers

Evaluator s Guide. PC-Duo Enterprise HelpDesk v5.0. Copyright 2006 Vector Networks Ltd and MetaQuest Software Inc. All rights reserved.

Outline. hardware components programming environments. installing Python executing Python code. decimal and binary notations running Sage

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.

4 Other useful features on the course web page. 5 Accessing SAS

The Power Loader GUI

Figure 1: Graphical example of a mergesort 1.

3. (1.0 point) To ungroup worksheets, you can click a sheet of a sheet not in the group. a. index b. panel c. tab d. pane

This is great when speed is important and relatively few words are necessary, but Max would be a terrible language for writing a text editor.

Chapter 9 Creating Reports in Excel

Eventia Log Parsing Editor 1.0 Administration Guide

DOS Command Reference

Introduction to the TI Connect 4.0 software...1. Using TI DeviceExplorer...7. Compatibility with graphing calculators...9

ARIES Flat File Importer

Access Tutorial 2: Tables

Intermediate PowerPoint

Inteset Secure Lockdown ver. 2.0

Basics of I/O Streams and File I/O

NØGSG DMR Contact Manager

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

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

Bank Account 1 September 2015

Directions for the Well Allocation Deck Upload spreadsheet

2: Entering Data. Open SPSS and follow along as your read this description.

MACHINE INSTRUCTIONS AND PROGRAMS

Summary of important mathematical operations and formulas (from first tutorial):

Data Tool Platform SQL Development Tools

EXST SAS Lab Lab #4: Data input and dataset modifications

Using Format Manager For Creating Format Files

Transcription:

1 Introduction Lecture 4 Input and output The deliverable of a computer program is its output. Output may be in graphical form as in a two-dimensional function plot, or it may be in text form as in a table of data values. In addition we often need to provide a program with input data, either interactively from the console or from a disk file. We will cover graphics in future lectures. Here we look at various ways to input and output data to and from the console and disk files. 2 Basic input/output (I/O) Scilab/Matlab automatically displays the value of a variable when you type its name at the command line. For example -->x = 2.3; -->x x = 2.3 In a program, on the other hand, the appearance of a variable name does not produce printed output. Moreover, even with console I/O we may want more control over the output format. We also need a way for a program to display values and ask for input, either from the user or from a file. There are various ways to approach this. We start with the simplest. 2.1 The disp function Most basic console I/O can be implemented with two functions: disp and input. The disp function can be used to display the values of variables without the extra "ans = " prefix. For example -->[x,y] ans = 2.3 4.1 -->disp([x,y]) 2.3 4.1 This works from within a program also. You can also combine it with the string() function (num2str() in Matlab) and the string concatenate operation. This creates one long string as in the following -->disp(string(x)+' plus '+string(y)+' equals '+string(x+y)); 2.3 plus 4.1 equals 6.4 This is generally good enough for most basic program output.

Lecture 4: Input and output 2/9 2.2 The input function The input() function can be used to prompt the user for input. We will illustrate this with a few examples -->x = input('please enter the value of x :'); please enter the value of x :3.2 -->disp(x) 3.2 You can input arrays -->y = input('enter a 1-by-3 vector : ') enter a 1-by-3 vector : [1,2,3] y = 1. 2. 3. and strings -->fname = input('output file : ') output file : 'test.txt' fname = test.txt Here's a little snippet of code that prompts the user for an array of data and prints the average value. z = input('enter a 1-by-n array of numbers : '); disp('the average value is '+string(mean(z))); this produces enter a 1-by-n array of numbers : [1,2,3,4,5,6] the average value is 3.5 2.3 The save and load functions The save and load functions allow you to dump and recover any or all variables you have created. -->A = [1,2;3,4]; -->x = 1:5; -->s = 'hello there'; -->save('test.dat'); The save command saves all variable names and values, essentially your entire Scilab session. You can exit Scilab and in a later session use the load command to recove these saved values. -->load('test.dat') -->A A = 1. 2. 3. 4. -->x x = 1. 2. 3. 4. 5.

Lecture 4: Input and output 3/9 -->s s = hello there This works the same in Matlab, except the file name should not have an extension (for example 'test') as Matlab apps the.mat extension automatically. You can explicitly specify the variables you want to save/load as in -->save('ax.dat','a','x'); //Scilab >> save('ax','a','x'); %Matlab This saves only the variables A and x. To load one or more specific variables you do the following -->load('ax.dat','a'); //Scilab >> load('ax','a'); %Matlab 3 Formatted I/O Scilab/Matlab implement versions of the C fprintf and sprintf functions for formatted output. 3.1 mfprintf (Scilab) & fprintf (Matlab) The C fprintf function ( file print formatted ) allows you great flexibility for generating formatted output to the console or to a file. Scilab implements this as mfprintf while Matlab uses fprintf. We will illustrate the mfprintf function in Scilab. For Matlab, simply leave off the initial m. The calling sequence for mfprintf is mfprintf(fd,format,var_1,var_2,...,var_n); fd is a file descriptor and format is a string that specifies how you want the output formatted. var_1 through var_n are the variables you want displayed. In Scilab the number 6 is the file descriptor for the console. This is also stored in the protected variable %io(2). An example is -->fd = %io(2); -->x = 1.23; -->mfprintf(fd,'the value of x is %f\n',x); the value of x is 1.230000 In Matlab the screen corresponds to fd = 1. In the format string %f stands for a floating-point number, %e stands for an exponential-format number (scientific notation), %d for a decimal number (integer) and %s for a string. In the output these are replaced by the variable values. Here's another example x = 1.23; y = 4; z = %pi*1e10; str = 'testing one two three'; mfprintf(fd,'%f %d %e %s\n',x,y,z,str); 1.230000 4 3.141593e+010 testing one two three The \n symbol denotes a "new line." If you omit this then subsequent mfprintf commands will be apped to the same line. Consider the following.

Lecture 4: Input and output 4/9 mfprintf(fd,'the value of x is %f',x); mfprintf(fd,' and y is %f\n',y); produces the value of x is 1.230000 and y is 3.210000 Finally, if you want to control the precise format of the numerical output, the syntax for a floating point number is %m.nf where m is the total number of spaces (you need one for the decimal point and you might need one for the sign) and n is the number of decimal places. For example -->mfprintf(fd,'%4.2f\n',x); 1.23 -->mfprintf(fd,'%6.2f\n',x); 1.23 -->mfprintf(fd,'%6.3f\n',x); 1.230 For %d and %s formats you can use the syntax %md or %ms where m is the total number of spaces to be displayed. Note that if you don't allocate enough, the full value will be printed anyway. If you allocate "too much" then blank space will be added. In the following example we generate a formatted table of trig values. N = 4; x = linspace(0,%pi/2,n); y = sin(x); z = cos(x); mfprintf(fd,'\n'); //creates blank line at start mfprintf(fd, '%6s %6s %6s\n','x','sin','cos'); for i=1:n mfprintf(fd,'%6.3f %6.3f %6.3f\n',x(i),y(i),z(i)); Note the mfprintf(fd,'\n'); statement used to clear any previously "open" lines of output. The output is x sin cos 0.000 0.000 1.000 0.524 0.500 0.866 1.047 0.866 0.500 1.571 1.000 0.000 A couple more points. Consider the following. -->mfprintf(fd,'%3d\n',k); 5 -->mfprintf(fd,'%-3d\n',k); 5 -->mfprintf(fd,'%03d\n',k); 005 The format %-3d causes the output to be left aligned as opposed to the default right alignment. The format %03d causes the output to be right aligned but all remaining space to the left is filled with zeros.

Lecture 4: Input and output 5/9 In keeping with the vectorized nature of Scilab/Matlab, the mfprintf (and fprintf) function is also vectorized. For example -->x = 1:3 x = 1. 2. 3. -->mfprintf(fd,'%d %d %d\n',x) 1 2 3 Scilab/Matlab recognizes that x is an array. It fills in the 3 %d formats with x(1), x(2) and x(3). Now consider this A = [1,2;3,4]; -->mfprintf(fd,'%f %f\n',a) 1.000000 2.000000 3.000000 4.000000 mfprintf repeats itself for each row of matrix A. In addition to mfprintf there is a Scilab function mprintf that does not require the file descriptor argument and prints directly to the console. -->x = 2; -->mprintf('%f %f %f\n',x,x^2,x^3) 2.000000 4.000000 8.000000 The advantage of using mfprintf with fd = %io(2) for console output is that it is very simple to modify your code to output to a file. You merely need to assign the fd variable using the mopen command described below. 3.2 msprintf (Scilab) & sprintf (Matlab) The msprinf function (sprintf in Matlab) is similar to the mfprintf function except that instead of writing output to the console or a file, it writes it to a string that can be assigned to a variable. Consider the following -->k = 3; -->name = msprintf('file%03d.txt',k) name = file003.txt This has created a string with the value of k embedded. An example where this is very useful is in creating frames for an animation where k goes from 1 to N and each file output is a single frame. 3.3 Opening and closing files If we want output to go to a disk file instead of the console, we need to create and/or open a file, write to it, and close the file. Opening a file is done with the mopen command (fopen in Matlab). [fd,err] = mopen('test.txt','wt'); This opens the file test.txt for output in the current directory. If it doesn't exist it is created. If it does exist is it overwritten. The 'wt' notation indicates that we are opening this file for writing in text format. You can also write in binary format, but we won't cover that. 'at' designates a text file opened for apping. To open a text file for reading we use 'rt'.

Lecture 4: Input and output 6/9 [fd,err] = mopen('test.txt','rt'); The resulting file descriptor fd can be used to refer to the file and err is an error flag. It is zero or empty if the open process worked properly and non-zero otherwise. You will get an error if you try to open a file for reading that doesn't exist, or a file for writing in a directory where you don't have write permission. Good programing practice is to always include error checking. For example [fd,err] = mopen('test.txt','rt'); if (err) error('cannot open test.txt'); If there is an error opening 'test.txt' you will get a message and then Scilab will exit using the error() function. It is very important to always close a file when you have finished reading or writing. This is done with the mclose(fd) command (fclose(fd) in Matlab). Here's an example A = [1,2;3,4]; [fd,err] = mopen('a.txt','wt'); if (err) error('cannot open file'); mfprintf(fd,'%f %f\n',a); This creates the file A.txt which contains the following. 1.000000 2.000000 3.000000 4.000000 A common source of errors when trying to open a file for reading is that the file does not exist. A way to test for this is using the isfile() command. In the following example a file named 'test.txt' exists the current directory but a file named 'test2.txt' does not. -->isfile('test.txt') ans = T -->isfile('test2.txt') ans = F We might use this as follows name = 'test.txt'; if (isfile(name)) [fd,err] = mopen(name,'rt'); if (err) mfprintf(%io(2),'cannot open file %s\n',name); else mfprintf(%io(2),'file %s is now open\n',name); else mfprintf(%io(2),'file %s does not exist\n',name);

Lecture 4: Input and output 7/9 This produces the output file test.txt is now open whereas changing the first line to name = 'test2.txt'; gives us the message file test2.txt does not exist 3.4 mfscanf (Scilab) and fscanf (Matlab) The mfscanf function is a modification of the C fscanf function and allows you to perform formatted input from a file. Suppose we use a text editor to create a text file named data.txt that contains 1 2 3 4 5 6 We can read these numbers into a vector x as follows (note that for compactness we are not including error checking for the mopen command). [fd,err] = mopen('data.txt','rt'); [n,x] = mfscanf(6,fd,'%d'); disp(x'); 1. 2. 3. 4. 5. 6. Variable n indicates the number of successful reads. It is -1 if the of file was reached before all desired data were read. The 6 tells mfscanf to read six times in the %d format. These are assigned as the elements of x. Here a variation [fd,err] = mopen('data.txt','rt'); [n,x] = mfscanf(3,fd,'%d'); [n,y] = mfscanf(3,fd,'%d'); -->x' ans = 1. 2. 3. -->y' ans = 4. 5. 6. This reads 3 numbers and assigns them to x, then another 3 numbers are read and assigned to y. In Matlab the ordering is slightly different [fd,err] = fopen('data.txt','rt'); [n,x] = fscanf(fd,'%d',3); [n,y] = fscanf(fd,'%d',3); fclose(fd); Here another example in Scilab. This time the file data.txt looks like this east 2 23.75 west 4-94.5 south 1 8.2 north 3-7.9

Lecture 4: Input and output 8/9 The following commands [fd,err] = mopen('data.txt','rt'); [n,s,d,x] = mfscanf(4,fd,'%s %d %f'); fill the arrays s, d and x with the corresponding string, decimal and floating point entries -->s' ans =!east west south north! -->d' ans = 2. 4. 1. 3. -->x' ans = 23.75-94.5 8.1999998-7.9000001 4 meof (Scilab) and feof (Matlab) Suppose we have a file named 'test.txt' which has the following contents 1 3 2 4 What do we do if we know the file contains some numbers but we don't know how many? One way to read all the available numbers in the file is to read them one at a time followed by a check for an -of-file condition using the meof function (feof in Matlab). This returns a non-zero value if the last input operation reached the of the file. Here's an example of how we can use this in a program. [fd,err] = mopen('test.txt','rt'); i = 1; //use i for an array index while (~meof(fd)) //while we haven't reach the of the file x(i) = mfscanf(fd,'%f'); //read the next number i = i+1; //increment the array index disp(x'); This produces the output 1. 2. 3. 4. We open the file and then as long as we have not reached the -of-file condition we read a single number into an element of an array x, increment the array index i and try again. This reads in the values 1, 2, 3 and 4 then stops when the of the file is reached. One thing to notice is that Scilab ignores the white space in the file (spaces, tabs and line-feed characters) and only looks for printable characters. There are many other input/output functions. In the Scilab Help Browser see the sections titled Files : Input/Output functions Input/Output functions

Lecture 4: Input and output 9/9 5 Spreadsheet support Scilab/Matlab can read and write data in spreadsheet format. We will only consider spreadsheets with numeric data and using comma-delimited text format (csv files). Suppose the spreadsheet ss.csv looks like The actual file in a text editor looks like this 1,2,3 4,5,6 In Scilab we read this file using -->M = csvread('ss.csv') M = 1. 2. 3. 4. 5. 6. To write a csv file we use the command csvwrite(m,'new.csv'); It is possible to specify a separator other than a comma and to read and write strings. See the Spreadsheet section of the help menu for more information.