How do you separate the contents of one cell into separate columns?

13 Ansichten (letzte 30 Tage)
alex pixler
alex pixler am 8 Jun. 2016
Bearbeitet: Stephen23 am 8 Jun. 2016
I have char-type data of both numbers and words, delimited by spaces, in a cell array of size 207x1. I want to separate the contents of the data in the first column into separate columns based on the space delimiter. Essentially, I want to perform an Excel "Text to Columns" function. My code looks like this:
fid = fopen('file.txt','r');
i = 1;
tline = fgetl(fid);
A{i,1} = tline;
while ischar(tline)
i = i+1;
tline = fgetl(fid);
A{i,1} = tline;
end
fclose(fid);
It produces cells that look like this:
'1553 word T 0 0 15 2 2 15328 0 0 1.00005 0'
I'm unsure if it matters, but I'm using R2013b.
  3 Kommentare
alex pixler
alex pixler am 8 Jun. 2016
textscan returns a 9762x1 cell for me when I try:
C = textscan(fid,'%s','Delimiter',' ');
Stephen23
Stephen23 am 8 Jun. 2016
Bearbeitet: Stephen23 am 8 Jun. 2016
Sure, but that is not the right way to use textscan for a file with columns. If you upload your data file then we can show you how to use textscan properly to read your file. By using a loop you are making this waaaay too complicated.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Guillaume
Guillaume am 8 Jun. 2016
The simplest way is probably to use the 'split' option of regexp:
splitcells = regexp(yourcellarray, '\s+', 'split')
And assuming that all rows have the same number of columns you can then convert the cell array of cell array into a 2d cell array with:
splitcells = vertcat(splitcells{:})
  3 Kommentare
Adam Still
Adam Still am 8 Jun. 2016
>> cellstr(some characters)
As an aside, have you tried tableread? I encountered a problem similar to this trying to read data from excel and I found it was more friendly for me. Not sure if it suits your needs. ~Adam
Guillaume
Guillaume am 8 Jun. 2016
If you're using the code you've posted to fill A, then all cells are already strings (unless A was not empty to start with).
To make sure that A is empty to start with replace the:
A{i,1} = tline;
before the loop (not inside the loop) by
A = {tline}; %initialise cell array with the first line.
But as Stephen said you're probably better off with textscan.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by