Clear Filters
Clear Filters

How do I import this simple CSV? Should I use textscan or something else?

2 views (last 30 days)
I am struggling to import data in MATLAB. The following code creates a 1x11 cell array with cells containing 0x0 char or NaN arrays, clearly wrong.
filepath = 'easy.csv';
% First we scan the file to see how many rows of data it has.
rows = 3; columns = 3;
RepetitionNumber = rows*columns;
% We construct the format spec based on this number of rows and columns.
formatSpec = ['%*s %*s %*s %*s %q %q',repmat('%f',[1,RepetitionNumber])];
% We read the file using textscan.
fileID = fopen(filepath);
DVH = textscan(fileID,formatSpec,'Delimiter',{',' '/n'});

Accepted Answer

Guillaume
Guillaume on 22 Jan 2018
Edited: Guillaume on 22 Jan 2018
I'm not sure how this is different from your other question. Again, use readtable which tremendously simplifies everything:
dvh = readtable('easy.csv', 'ReadVariableNames', false)
  2 Comments
Daniel Bridges
Daniel Bridges on 22 Jan 2018
Indeed, I asked both questions working to accomplish the same task. The difference between these questions is that in the previous one I am also asking about how to write a flexible code that automatically accounts for differing number of data sets between CSV files, whereas this question asks only how to import one simple file using textscan. My thinking was that after learning how to use textscan I could proceed to learn how to probe files to determine their rows and columns (I was thinking to use a text search command to count the number of commas in one line, and then the number of commas in the entire file, etc ...) In other words, first succeed in using textscan in a simple case, and then move on to a more generalized case.
I must sleep now and return to this problem in about 12 hours. Thanks again for the suggestion.
Daniel Bridges
Daniel Bridges on 23 Jan 2018
Here is working code as a solution to the above problem.
filepath = 'easy.csv';
opts = detectImportOptions(filepath, 'NumHeaderLines', 1);
opts = setvartype(opts,opts.VariableNames, 'double');
opts.VariableNames(1)={'Dose'};
DVH = readtable(filepath,opts);
My next task is to learn how to parse the Volume variable names to strip the underscore and all characters after it.

Sign in to comment.

More Answers (0)

Categories

Find more on Large Files and Big Data 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!