Professional Documents
Culture Documents
4 Importing Data R1
4 Importing Data R1
12
34
5
48
16 32
load
• Now type in the same thing from test1.txt into
Excel and save the workbook as test1.xls
• type y = load(‘test1.xls’)
– What happens?
• Matlab would display an error
• Forcing the issue with Excel data by changing to
text file and then import. 12
34
52
48
16 32
load
• Works for simple and unstructured code
• Powerful and easy to use but limited
• Will likely force you to manually handle
simplifying data which is prone to error
• More complex functions are more flexible
File Handling
• f* functions are associated with file opening,
reading, manipulating, writing, …
• Basic Functions of Interest for opening and
reading generic files in Matlab
– fopen
– fclose
– fseek/ftell/frewind
– fscanf
– fgetl
fopen
• Opens a file object in Matlab that points to the
file of interest
• fid = fopen(‘filepath’)
– absolute directory + filename
• If file of interest it C:\Andrew\Project_1\file.dat
• >> fid = fopen(‘C:\Andrew\Project_1\file.dat’)
– relative path + filename
• If your Matlab path is set to c:\Andrew\Project_1
• >> fid = fopen(‘file.dat’)
• fid is an integer that represents the file
– Can open multiple files and Matlab will assign unique
fids
fclose
• When you are done with a file, it is a good idea
to close it especially if you are opening many
files
– >> fclose(fid)
What is a File?
• A specific organization of data
• In Matlab it is identified with a fid
• Location is specified with a pointer that can be
moved around
fid
Pointer
file_name
Moving the Pointer
• We already know how to assign a fid (fopen)
• To find where the file is pointing:
– >> x = ftell(fid)
• To point somewhere else
– >> fseek(fid,offset,origin)
– E.g., fseek(fid,10,0) %no need for an output
• Move pointer in file fid by offset relative to origin
– Origin can be beginning, current, end of file
– Offset is in bytes
– Output is ans = 0