reading data from csv files with `textscan` in MATLAB - matlab
[Edited:] I have a file data2007a.csv and I copied and pasted (using TextEdit in MacBook) the first consecutive few lines to a new file datatest1.csv for testing:
Nomenclature,ReporterISO3,ProductCode,ReporterName,PartnerISO3,PartnerName,Year,TradeFlowName,TradeFlowCode,TradeValue in 1000 USD
S3,ABW,0,Aruba,ANT,Netherlands Antilles,2007,Export,6,448.91
S3,ABW,0,Aruba,ATG,Antigua and Barbuda,2007,Export,6,0.312
S3,ABW,0,Aruba,CHN,China,2007,Export,6,24.715
S3,ABW,0,Aruba,COL,Colombia,2007,Export,6,95.885
S3,ABW,0,Aruba,DOM,Dominican Republic,2007,Export,6,11.432
I wanted to use textscan to read it into MATLAB with only columns 2,3,5 (starting from the second row) and I wrote the following code
clc,clear all
fid = fopen('datatest1.csv');
data = textscan(fid,'%*s %s %d %*s %s %*[^\n]',...
'Delimiter',',',...
'HeaderLines',1);
fclose(fid);
But I ended up with only the second row of columns 2,3 and 5:
I then keep the first row in data2007a.csv and selected several others to saved as datatest2.csv:
Nomenclature,ReporterISO3,ProductCode,ReporterName,PartnerISO3,PartnerName,Year,TradeFlowName,TradeFlowCode,TradeValue in 1000 USD
S3,ABW,1,Aruba,USA,United States,2007,Export,6,1.392
S3,ABW,1,Aruba,VEN,Venezuela,2007,Export,6,5633.157
S3,ABW,2,Aruba,ANT,Netherlands Antilles,2007,Export,6,310.734
S3,ABW,2,Aruba,USA,United States,2007,Export,6,342.42
S3,ABW,2,Aruba,VEN,Venezuela,2007,Export,6,63.722
S3,AGO,0,Angola,DEU,Germany,2007,Export,6,105.334
S3,AGO,0,Angola,ESP,Spain,2007,Export,6,8533.125
And I wrote:
clc,clear all
fid = fopen('datatest2.csv');
data = textscan(fid,'%*s %s %d %*s %s %*[^\n]',...
'Delimiter',',',...
'HeaderLines',1);
fclose(fid);
data{1}
It gives exactly what I wanted:
When I use the same code for my original data file data2007a.csv, it goes as in the first case.
What is going wrong and how can I fix it?
[Added:] If one replicates my experiments1, one can find that both cases work and the problem does not exist! I really don't know what is going on.
1 For "replicate" I mean copy-and-paste the data given above and save it as two new files, say, datatest4a.csv and datatest4b.csv. I used visdiff('datatest1.csv', 'datatest4a.csv') to compare two files and it returned:
Given how you fixed it, I think this is an end-of-line character issue. This sometimes comes up when moving text files between Windows and Unix based systems, as they use different conventions.
When you add %*[^\n] to the end of a textscan format, as you have here. it means to skip everything to the end of line. But if it expects a specific end of line character, and can't find one, it will skip everything to the end of the file. This would explain why you get one row correctly read and then nothing else.
If you don't specify what the end of line character is, Matlab appears to default to... something... in this not very clear specification in the help:
The default end-of-line sequence is \n, \r, or \r\n, depending on the contents of your file.
One way to try and cure this without having to create a new file would be to add this 'EndOfLine', '\r\n' to your textscan call:
If you specify '\r\n', then textscan treats any of \r, \n, and the
combination of the two (\r\n) as end-of-line characters.
This will hopefully handle most standard(ish) EOL conventions. It is likely that copy-pasting and saving with a different bit of software than was originally used to create the file changed the end of line characters such that Matlab was able to recognise them.
Related
Table imported into Matlab from CSV, variable name prefixed by "x___"
I have a bunch of automatically-generated CSV files with headers, which I'd like to import into Matlab 2016a as a table. I used code such as T = readtable('d:\test.csv', 'readvariablenames', true); However, even though the name of the CSV's first column is "runNr", the first column in the Matlab table gets named "x___runNr" This clearly has something to do with the CSV files being in a slightly format different from that expected by Matlab. For instance, it could be that my CSVs have a Byte Order Mark in the beginning. Still, I am not sure what to do to fix this, since I cannot change the format of the CSVs. Readtable, on the other hand, gives me the output format I am most comfortable with. Upon calling readtable, the following warning is issued: "Warning: Variable names were modified to make them valid MATLAB identifiers. " However, some of my CSVs (perhaps produced by a different version of the software that outputs them) are still read OK, and for those CSVs the same warning is displayed, thus the warning alone is not indicative of the problem.
I think I found the source of the problem: Like you have suspected, the encoding of your CSV file is "UTF-8-BOM" (I saw it using Notepad++). The UTF-8 representation of the BOM is the (hexadecimal) byte sequence 0xEF,0xBB,0xBF MATLAB R2019a knows to ignore the first 3 bytes, but R2016a is "confused" by the 3 characters, and add x___ prefix to runNr. A workaround, is create a temporary file with out the first 3 characters: f = fopen('test.csv', 'r'); A = fread(f, '*uint8'); fclose(f); if all(A(1:3) == hex2dec(['EF'; 'BB'; 'BF'])) f = fopen('tmp.csv', 'w'); fwrite(f, A(4:end)); %Skip first 3 characters. fclose(f); T = readtable('tmp.csv', 'readvariablenames', true); else T = readtable('test.csv', 'readvariablenames', true); end There might be more efficient solutions (like simply removing the x___).
How to avoid the repeated paragraghs of long txt files being ignored for importdata in matlab
I am trying to import all double from a txt file, which has this form #25x1 string #9999x2 double . . . #(repeat ten times) However, when I am trying to use import Wizard, only the first 25x1 string 9999x2 double. was successfully loaded, the other 9 were simply ignored How may I import all the data? (Does importdata has a maximum length or something?) Thanks
It's nothing to do with maximum length, importdata is just not set up for the sort of data file you describe. From the help file: For ASCII files and spreadsheets, importdata expects to find numeric data in a rectangular form (that is, like a matrix). Text headers can appear above or to the left of the numeric data, as follows: Column headers or file description text at the top of the file, above the numeric data. Row headers to the left of the numeric data. So what is happening is that the first section of your file, which does match the format importdata expects, is being read, and the rest ignored. Instead of importdata, you'll need to use textscan, in particular, this style: C = textscan(fileID,formatSpec,N) fileID is returned from fopen. formatspec tells textscan what to expect, and N how many times to repeat it. As long as fileID remains open, repeated calls to textscan continue to read the file from wherever the last read action stopped - rather than going back to the start of the file. So we can do this: fileID = fopen('myfile.txt'); repeats = 10; for n = 1:repeats % read one string, 25 times C{n,1} = textscan(fileID,'%s',25); % read two floats, 9999 times C{n,2} = textscan(fileID,'%f %f',9999); end You can then extract your numerical data out of the cell array (if you need it in one block you may want to try using 'CollectOutput',1 as an option).
How to get the number of columns of a csv file?
I have a huge csv file that I want to load with matlab. However, I'm only interested in specific columns that I know the name. As a first step, I would like to just check how many columns the csv file has. How can I do that with matlab?
As Jonesy and erelender suggest, I would think this will do it: fid=fopen(filename); tline = fgetl(fid); fclose(fid); length(find(tline==','))+1 Since you don't seem to know what kind of carriage return character (or character encoding?) is being used then I would suggest progressively sampling your file until you encounter a recognizable CR character. One way to do this is to loop over something like A = fscanf(fileID, ['%' num2str(N) 'c'], sizeA); where N is the number of characters to read. At each iteration test A for presence of carriage return characters, stop if one is encountered. Once you know where the carriage return is just repeat with the right N and perform the length(find...) operation, or alternately accumulate the number of commas at each iteration. You may want to check that your file is being read along rows (is it always?), check a few samples to make sure it is.
1-) Read the first line of file 2-) Count the number of commas, or seperator characters if it is not comma 3-) Add 1 to the count and the result is the number of columns in the file.
If the csv has only numeric value you can use: M=csvread('file_name.csv'); [row,col]=size(M);
Formatting fprintf
I have a bit of Matlab code and I am trying to export some string and create a tab-delimitted text file from it. I think fprintf performs similarly in C (if not please edit my tag). I believe my issue is with my format string. Basically I have 7 strings that I want separated by tabs and then a newline character. please note that "fid" is a full path. I am looping this in a for loop so lines are being appended each pass and the file is built. ImgData = strcat(ImgData, fid, '\t', imgNumber, '\t', N_std,'\t',S,'\t',N,'\t',SNR,'\t',SNR_dB,'\n'); DataOut = fopen(strcat('Image_F', folderNumber, '_Data.txt'), 'w'); fprintf(DataOut,'%s\t %s\t %s\t %s\t %s\t %s\t %s\n',ImgData); You may be curious on how this exports. This formats like fid\tI#\tN_std\tS\tN\tSNR\tSNR_dB\n in the txt file. As you can tell this isn't tab-delimitted which my major issue. I am having some trouble with the format string. Does anyone know how to reformat it so it prints the tabs and newline?
You're creating a string in ImgData that you then pass as input to fprintf. This reads ImgData into the first %s of the format string, and then adds at least one tab at the end. What you should do instead is write something like: `fprintf(DataOut,'%s\t%i\n',imgName,imgNumber)` which assumes that imgName is a string and imgNumber an integer number. Note that I pass two placeholders (with the %-sign) and two input variables to fprintf. Use %6.2f print floating point numbers with a total of 6 characters, including 2 after the comma, for SNR, for example. For easier development, you can drop the first input argument to fprintf, in which case it will print to command line.
MATLAB: How do you insert a line of text at the beginning of a file?
I have a file full of ascii data. How would I append a string to the first line of the file? I cannot find that sort of functionality using fopen (it seems to only append at the end and nothing else.)
The following is a pure MATLAB solution: % write first line dlmwrite('output.txt', 'string 1st line', 'delimiter', '') % append rest of file dlmwrite('output.txt', fileread('input.txt'), '-append', 'delimiter', '') % overwrite on original file movefile('output.txt', 'input.txt')
Option 1: I would suggest calling some system commands from within MATLAB. One possibility on Windows is to write your new line of text to its own file and then use the DOS for command to concatenate the two files. Here's what the call would look like in MATLAB: !for %f in ("file1.txt", "file2.txt") do type "%f" >> "new.txt" I used the ! (bang) operator to invoke the command from within MATLAB. The command above sequentially pipes the contents of "file1.txt" and "file2.txt" to the file "new.txt". Keep in mind that you will probably have to end the first file with a new line character to get things to append correctly. Another alternative to the above command would be: !for %f in ("file2.txt") do type "%f" >> "file1.txt" which appends the contents of "file2.txt" to "file1.txt", resulting in "file1.txt" containing the concatenated text instead of creating a new file. If you have your file names in strings, you can create the command as a string and use the SYSTEM command instead of the ! operator. For example: a = 'file1.txt'; b = 'file2.txt'; system(['for %f in ("' b '") do type "%f" >> "' a '"']); Option 2: One MATLAB only solution, in addition to Amro's, is: dlmwrite('file.txt',['first line' 13 10 fileread('file.txt')],'delimiter',''); This uses FILEREAD to read the text file contents into a string, concatenates the new line you want to add (along with the ASCII codes for a carriage return and a line feed/new line), then overwrites the original file using DLMWRITE. I get the feeling Option #1 might perform faster than this pure MATLAB solution for huge text files, but I don't know that for sure. ;)
How about using the frewind(fid) function to take the pointer to the beginning of the file? I had a similar requirement and tried frewind() followed by the necessary fprintf() statement. But, warning: It will overwrite on whichever is the 1st line. Since in my case, I was the one writing the file, I put a dummy data at the starting of the file and then at the end, let that be overwritten after the operations specified above. BTW, even I am facing one problem with this solution, that, depending on the length(/size) of the dummy data and actual data, the program either leaves part of the dummy data on the same line, or bring my new data to the 2nd line.. Any tip in this regards is highly appreciated.