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

2 Ansichten (letzte 30 Tage)
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'});

Akzeptierte Antwort

Guillaume
Guillaume am 22 Jan. 2018
Bearbeitet: Guillaume am 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 Kommentare
Daniel Bridges
Daniel Bridges am 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 am 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by