Matlab CSV parsing error?
1 view (last 30 days)
Show older comments
So let me preface this by saying, I am very new to Matlab.
Attached, I have an 11 x 8 CSV file. My script is supposed to take the phrases in the cells, turn them into a Matlab Variable, and place them in different aspects of my GUI.
The part of my script that takes the CSV and parses it into a variable is:
FileID = fopen('lifeacceleratedinteractions.csv' , 'r');
Contents = textscan(FileID, '%s%s%s%s%s%s%s%s' , 'Delimiter' , '"');
global Contents
assignin('base' , 'Contents' , Contents);
fclose(FileID);
The issue that arises from this is there are gaps, and information in the wrong spot. Stephen pointed out that there were commas all over the place, and to try using '%q' instead of '%s', but that did not work.
I'm rewording in hopes that I do a better job of explaining my situation. I have also included the CSV I'm working with, the .fig and the .m files as well. The lines that start to deal with the CSV is at 111.
2 Comments
Stephen23
on 7 May 2016
Edited: Stephen23
on 7 May 2016
Note that it is much more reliable to pass variables rather than use assignin. Using assignin is slow and can have problems that are hard to debug. Passing variables properly is the neater, faster, and more reliable way to get variables from one workspace to another:
Answers (1)
Stephen23
on 7 May 2016
Edited: Stephen23
on 7 May 2016
The issue is that some of the strings seem to contain commas, which you are also using as column delimiters. Luckily for you the CSV file also seems to have been formatted correctly with quotation marks, so one solution is to simply use %q instead of %s in your textscan format string, which will keep quoted strings together, as the documentation clearly explains:
'%q%q%q%q%q%q%q%q%q%q%q'
or even better:
N = number of columns in CSV file
fmt = repmat('%q',1,N);
C = textscan(FileID, fmt, 'Delimiter',',');
If that does not resolve the issue then you should edit your question and upload the file using the paperclip button.
Note: you write that the CSV file "is an 8 x 11 array of phrases", but you only define eight '%s' in your format string: something is not correct here, as the format string defines the columns, so should have 11 %s tokens. (remember "8 x 11" means eight rows and eleven columns).
5 Comments
Stephen23
on 7 May 2016
Edited: Stephen23
on 7 May 2016
textscan works fine for me:
>> fmt = repmat('%q',1,8);
>> fid = fopen('lifeacceleratedinteractions.csv','rt');
>> C = textscan(fid,fmt,'Delimiter',',');
>> fclose(fid);
>> C = horzcat(C{:});
>> size(C) % check the size (rows x columns):
ans =
11 8
>> C{9,6} % show that textscan has kept quoted strings together:
ans =
Get gender specific toys, clothes, and accessories without knowing the baby's gender.
See Also
Categories
Find more on Data Import and Export in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!