![]() Next you need to supply a conversion specifier which in this case is '%f %f %f %*s %*s' The first argument to textscan is just this file ID, fid. So, you open your file using fopen and give it a file ID (which in this example is fid). ![]() The first thing to notice is that, unlike csvread and importdata, you have to explicitly open and close your file when using the textscan command. Let’s de-construct the above set of commands. If the importdata command is a chauffeur then textscan is a Ferrari and I don’t know about you but I’d much rather be driving my own Ferrari than being chauffeured around (John Cook over at The Endeavour has more to say on Ferraris and Chauffeurs). Let’s get the array of doubles out of the cell > data=data The result is a one-element cell array that contains an array of doubles. Here’s the incantation for importing messy_data.txt fid=fopen('messy_data.txt') ĭata = textscan(fid,'%f %f %f %*s %*s','HeaderLines',2,'Delimiter',',','CollectOutput',1) When the going gets tough, the tough use textscan. Let’s bring out the big-guns! Using textscan to import csv files in MATLAB Unfortunately, it also contains some cruft that makes life more difficult for us. This is the kind of file encountered by Walking Randomly reader ‘reen’ and it contains exactly the same numerical values as the previous two examples. How do we handle a file like messy_data.txt though? header 1 ![]() The result above is a two element structure array and our numerical values are contained in a field called data. Not to worry, we can just use the more capable importdata command instead > quiteclean = importdata('quite_clean.txt') Trouble reading number from file (row 1, field 1) => This This is all too much for the csvread command > data=csvread('quite_clean.txt') This is identical to the previous example apart from the fact that it contains two header lines These are some data that I made using my hand-crafted code Take the file quite_clean.txt for instance. One of the most common problems faced by MATLABing data importers is that of header lines. In the real world, however, your data is rarely this nice and clean. The following, very simple command, is all that you need > veryclean = csvread('very_clean.txt') For example, say you wanted to import the file very_clean.txt which contains the following data 1031,-948,-76 Reading comma separated value (csv) files into MATLAB is trivial as long as the csv file you are trying to import is trivial.
0 Comments
Leave a Reply. |