MATLAB User-defined functions, Data Input/Output. Edited by Péter Vass

Similar documents
Working with Excel Files. a = round(rand(5,3)*100) xlswrite('rand.xlsx',a) b = xlsread('rand.xlsx')

Beyond the Mouse A Short Course on Programming

Using files. Computer Programming for Engineers (2014 Spring)

ES 117. Formatted Input/Output Operations

CSE 123. Lecture 9. Formatted. Input/Output Operations

Fö 6: Filhantering. DN1212 Numeriska metoder och grundläggande programmering. Pawel Herman. KTH/CB

Chapter 11 Input/Output (I/O) Functions

Importing and Exporting Data

12-Reading Data text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie

Scalars and Variables

Lecture 7. MATLAB and Numerical Analysis (4)

MATLAB. Data and File Management

5. MATLAB I/O 1. Beyond the Mouse GEOS 436/636 Jeff Freymueller, Sep 26, The Uncomfortable Truths Well, hop://xkcd.com/568 (April 13, 2009)

Using the fprintf command to save output to a file.

UNIT IV-2. The I/O library functions can be classified into two broad categories:

ENG Introduction to Engineering

An Introductory Tutorial on Matlab

Access to Delimited Text Files

Matlab Programming Arrays and Scripts 1 2

PROGRAMMING WITH MATLAB WEEK 13

Lecture 5: Strings, Printing, and File I/O

13-Writing Data text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie

Singular Value Decomposition (SVD) 1

C Basics And Concepts Input And Output

SECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB

Chapter 9. Above: An early computer input/output device on the IBM 7030 (STRETCH)

There is also a more in-depth GUI called the Curve Fitting Toolbox. To run this toolbox, type the command

1 Data Exploration: The 2016 Summer Olympics

Programming in Mathematics. Mili I. Shah

Strings and I/O functions

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

School Of Electrical, Computer & Telecommunications Engineering UOW. Training Lab. Introduction to MATLAB. Version: 1.1

1 >> Lecture 6 2 >> 3 >> -- User-Controlled Input and Output 4 >> Zheng-Liang Lu 367 / 400

Worksheet 6. Input and Output

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

MATLAB INTRODUCTION. Matlab can be used interactively as a super hand calculator, or, more powerfully, run using scripts (i.e., programs).

Computational Methods of Scientific Programming

ENGR 1181 MATLAB 05: Input and Output

MATLAB Introduction to MATLAB Programming

Standard C Library Functions

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

EGR 102 Introduction to Engineering Modeling. Lab 05A Managing Data

Introduction to file management

Programming 1. Script files. help cd Example:

Matlab. Carlo Tomasi. Since images are matrices of numbers, many vision algorithms are naturally implemented

Getting To Know Matlab

fopen() fclose() fgetc() fputc() fread() fwrite()

C File System File Functions EXPERIMENT 1.2

Course Title: C Programming Full Marks: Course no: CSC110 Pass Marks: Nature of course: Theory + Lab Credit hours: 3

Matlab Input/Output. Goal of this section Learn user-controlled Input Output Read/write data files (optional) Input/output 5-

A Guide to Using Some Basic MATLAB Functions

Quick MATLAB Syntax Guide

Introduction to Matlab

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

Matlab Introduction. Dr. Antonio A. Trani Professor Dept. of Civil and Environmental Engineering. Virginia Tech (copyright A.A.

CSI 402 Lecture 2 (More on Files) 2 1 / 20

Matlab programming, plotting and data handling

Introduction to MATLAB Workshop

Spring 2010 Instructor: Michele Merler.

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

UNIT- 2. Binary File

Basic Plotting. All plotting commands have similar interface: Most commonly used plotting commands include the following.

Matlab I: Getting Started

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

Desktop Command window

MATLAB 7 Data Import and Export

File (1A) Young Won Lim 11/25/16

CSCI 171 Chapter Outlines

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

Low-Level File I/O. 1. Open a file. 2. Read or write data into the file. 3. Close the file. Zheng-Liang Lu 1 / 14

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Standard File Pointers

Intermediate Programming, Spring 2017*

Lecture 9: File Processing. Quazi Rahman

Introduction to MATLAB

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

CSCE C. Lab 10 - File I/O. Dr. Chris Bourke

Structure Arrays. An Example. Structures (v. 1.1) Structures -- GE /6/2011. Copyright C. S. Tritt, Ph.D. 1. C. S. Tritt, Ph.D.

FDP on Electronic Design Tools - Fundamentals of MATLAB 12/12/2017. A hands-on training session on. Fundamentals of MATLAB

System Software Experiment 1 Lecture 7

EE458 - Embedded Systems Lecture 4 Embedded Devel.

STAT 391 Handout 1 Making Plots with Matlab Mar 26, 2006

MATLAB. Input/Output. CS101 lec

SBT 645 Introduction to Scientific Computing in Sports Science #6

EE168 Handout #6 Winter Useful MATLAB Tips

What is KNIME? workflows nodes standard data mining, data analysis data manipulation

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING UNIT-1

Engineering program development 7. Edited by Péter Vass

V.S.B ENGINEERING COLLEGE DEPARTMENT OF INFORMATION TECHNOLOGY I IT-II Semester. Sl.No Subject Name Page No. 1 Programming & Data Structures-I 2

ENG120. Misc. Topics

C mini reference. 5 Binary numbers 12

Chemical Engineering 541

CS PROGRAMMING & ATA STRUCTURES I. UNIT I Part - A

Chapter 3: Programming with MATLAB

CSI 402 Lecture 2 Working with Files (Text and Binary)

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

Starting Matlab. MATLAB Laboratory 09/09/10 Lecture. Command Window. Drives/Directories. Go to.

PART 2 DEVELOPING M-FILES

Lab of COMP 406. MATLAB: Quick Start. Lab tutor : Gene Yu Zhao Mailbox: or Lab 1: 11th Sep, 2013

CS1132 Spring 2016 Assignment 2 Due Apr 20th

Transcription:

MATLAB User-defined functions, Data Input/Output Edited by Péter Vass

User-defined functions Although, MATLAB provides a wide range of built-in functions it may often be necessary to create and use an own, user-defined function. Similarly to a script, a user-defined function is stored in a file of.m extension. It can be created in the script editor window. The name of the file must be the same as the name of the function. Unlike a script, a function can accept input parameters (or arguments) and return output parameters. A function operates on variables within its own local workspace. The local workspace is independent of the base workspace of the MATLAB command line. This is the reason why a function cannot reach the variables of the base workspace during its running.

User-defined functions A function definition has two main parts: header, body. The information about the name and parameters of the function is specified in the header of the function. The body of the function contains the sequence of instructions by which a specific problem can be solved. The general format of a function definition: function [out1,out2,..., outn] = funcname(in1,in2,in3,..., inm) instructions After defining and saving the function, it can be called either in the command line or a script. Moreover, it can also be called in the body of another user-defined function. So, more complex functions can be implemented by the utilization of simpler ones.

User-defined functions Example Let us write a simple, user-defined functions for computing the root mean square error (RMSE) and mean absolute error (MAE) between two input vectors of the same size. function [rmse, mae]=calcerrors(x, y) %The function computes the RMSE and MAE between two input % vectors of the same time rmse=sqrt(sum((x-y).^2)/length(x)); mae=sum(abs(x-y))/length(x);

User-defined functions Example of calling the function >> t=0:0.1:5; >> u=exp(-t).*cos(2*pi*t); >> plot(t,u) >> noise=0.05*randn(size(t)); >> un=u+noise; >> hold on; >> plot(t,un,'r'); >> [err1, err2]=calcerrors(u,un)

MATLAB provides three different techniques to read data from files and save data into files: using the load and save commands, using other commands for loading and saving plain ASCII files, using low-level input/ output functions for other file formats. Load and save commands The save command is used for saving all the variables of the base (command line) workspace into a file. The filename must be specified after the save command: >>save filename MATLAB creates a binary file of.mat extension in the current folder (the general format of.mat files is described in the documentation).

The variables stored in a MATLAB binary format file can be read in by using the load command: >>load filename If not all the variables are needed to save or load, the names of the required variables must be listed after the name of the file in the command line. >>save filename var1 var2.. varn >>load filename var1 var 2 This type of data input and output is suggested when the actual MATLAB workflow has to be finished temporarily, but later it is planned to continue with the variables created in the previous MATLAB session. The file of MATLAB binary format, however, cannot be processed by other software environments (e.g. spreadsheet or word-processing software).

Loading and saving plain ASCII files The MATLAB provides some useful built-in functions by which tabular format data sets can be saved in plain ASCII coded files and data can also be loaded in the workspace from such files. >>csvwrite('filename.ext', M) writes the matrix M into the file specified between single quotes. The numbers are separated by commas and arranged in a tabular format. >>M = csvread('filename.ext') reads the data from a comma-separated file whose name and extension are specified between single quotes. The file can only contain numeric values in a tabular format. The data are loaded in the matrix M.

>>M = csvread('filename.ext', R, C) reads the data from a comma-separated file starting at row R and column C. The numbering of rows and columns starts with 0. This way of calling csvread can be useful when the first row in the file is a header. >>dlmwrite('filename.ext',m,'dlm') writes the matrix M into the file specified between single quotes. The numbers are separated by using the character dlm as the delimiter of data columns. A frequently applied delimiter: horizontal tabulator '\t'

>>M= dlmread('filename.ext','dlm') reads the data from the file specified between single quotes. The file can only contain numeric values in a tabular format, and the numbers are separated by using the character dlm as the delimiter of data columns. The data are loaded in the matrix M. >>M= dlmread('filename.ext','dlm', R, C) reads the data from the file starting at row R and column C. The numbering of rows and columns starts with 0.

Examples >> data=[t',u',un']; >> size(data) >>save data >> csvwrite('datacsv.csv',data) >> M=csvread('datacsv.csv'); >> dlmwrite('datatab.txt',data,'\t'); >> N=dlmread('datatab.txt','\t');

Loading data from MS Excel spreadsheet xlsread >> help xlsread Writing data into MS Excel spreadsheet xlswrite >> help xlsread Examples >> xlswrite('dataxls.xls',data); >> XLS=xlsread('dataxls.xls');

Low-level input/ output functions The so-called low level input/output functions provide the most flexible way of file input and output. However, their proper application for reading or writing files requires the detailed knowledge of their documentation and some programming skill. File opening and closing: fclose fopen Unformatted I/O: fread fwrite Formatted I/O: fgetl fprintf fgets fscanf File positioning: feof fseek ferror ftell frewind String conversion: sprintf sscanf

Example of the script file writedata.m % open a file for writing fid = fopen('datafile.txt','w'); % writing a header and a unit line fprintf(fid,'time noiseless noisy\n'); fprintf(fid,'[s] [mv] [mv]\n'); % print values in column order % three values of float-type appear on each row of the file fprintf(fid,'%f %f %f\n', data'); fclose(fid);

Example of the script file readdata.m % open a file for reading fid = fopen('datafile.txt'); % reading the header header=fgetl(fid); %reading the unit line units=fgetl(fid); % Read the values in column order, and transpose to match the %appearance of the file DATA=fscanf(fid,'%f',[3, inf])'; fclose(fid);