How to go from a char that is a CSV to a cell array

16 ビュー (過去 30 日間)
Will Kinsman
Will Kinsman 2016 年 3 月 1 日
回答済み: Jos (10584) 2016 年 3 月 1 日
Hello all,
I have a char variable that is essentially a CSV file, however all attempts to turn it into a cell array (through simple means) have failed. Lets say my char variable looks like:
inputchar = 'name,bob,joe,paul
age,12,43,15'
(note there is a \n after paul) I would like my output to simply be a cell array to appear as:
outputcellarray = {'name','bob','joe','paul';
'age',12,43,15}
While I am aware of csvread, since I am trying to read from a char variable instead of a CSV file, I am having trouble. Any suggestions or simple workarounds other than writing an entire function to do this?
Thanks so much for the help everyone! Will

採用された回答

Jos (10584)
Jos (10584) 2016 年 3 月 1 日
Are you sure you want to store your data like this, i.e., all in a single cell array? Take a look at textscan to read you cvs file. Otherwise this might do the trick:
inputchar = 'name,bob,joe,paul\nage,12,43,15'
X = strrep(inputchar,'\n',',') % get rid of the line break
C = strread(X,'%s','delimiter',',') % read everything as a string
C = reshape(C,[],2).' % reshape in right format
V = str2double(C) % convert numbers
tf = ~isnan(V) % find these numbers
C(tf) = num2cell(V(tf)) % put them in place. Voila!

その他の回答 (1 件)

Will Kinsman
Will Kinsman 2016 年 3 月 1 日
After messing around a little bit it seems to me that the simplest solution may to be:
outputcellarray = readtext(inputchar,,,,'textsource')
this is a file on the file exchange that appears to be pretty lightweight and will allow me to do what I am trying to here.

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by