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

조회 수: 7 (최근 30일)
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'});

채택된 답변

Guillaume
Guillaume 2018년 1월 22일
편집: Guillaume 2018년 1월 22일
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
Daniel Bridges
Daniel Bridges 2018년 1월 22일
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 2018년 1월 23일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by