How can I read a string into a cell array?

2 views (last 30 days)
I want to read an ascii file into a cell array of strings, one cell per line of input text:
array = cell(10000);
iLine = 1;
fid1 = fopen('template.txt','r');
while ~feof(fid1)
line = fgetl(fid1);
array(iLine) = line;
iLine = iLine + 1
.
.
.
When I do the above, I get the following error: Conversion to cell from char is not possible.
I've read through answers both here and on the Web and tried many things. But I am a Matlab newbie and I think I am misunderstanding something fundamental about how to deal with strings. Any suggestions? Thanks.

Accepted Answer

per isakson
per isakson on 15 Apr 2013
Edited: per isakson on 15 Apr 2013
fgetl returns a string. Try
class( line )
line need to be converted to a cell array of strings:
array(iLine) = { line };
PS. Before other resources, search the Matlab on-line help.

More Answers (1)

Image Analyst
Image Analyst on 15 Apr 2013
Alternatively this will also work
array{iLine} = line;
This way basically says the "contents of" cell # iLine is a string. per's version does the same thing but in a slightly different way. It puts the string into a single cell and then makes that cell the element number iLine of the full cell array. It's somewhat confusing so let me try to make an analogy. A cell is like a bucket. You can throw anything you want into the bucket: a string, an integer, a double, an array, a structure, even another cell array. Now let's say you have an array of buckets - an array of cells or a "Cell Array". Each bucket can contain something different, or they mgiht all contain the same type of variable. Bucket 1 could contain a string while bucket 2 could contain an image (array of uint8's), while bucket 3 could be a int32. Or all buckets could contain strings of various lengths. It's totally flexible.
The braces should be read as "contents of", so in my way, I said the "contents of" bucket #iLine is a string. per's way says let's get a bucket (a cell) and put the string into it. Then let's take that bucket and make it bucket #iLine, replacing any bucket that was already there. He used parentheses which means it refers to the whole single bucket (the bucket plus the contents) while I used braces which refers to only the contents of the bucket. It's just a slight difference - a slightly different way of considering it. They are equivalent for the most part. I use both ways and I don't really think one way or the other is really preferred. You can use whatever way is easier for you to think about it. Maybe one way will be more intuitive for you than the other way, but again, they are equivalent.
I hope that explains cell arrays better for you.

Categories

Find more on Cell Arrays 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!