3

I was doing some operations in Strings.I have a string 'AGCT' in X.I saved it in a cell using the following command

y(1,1)={x};

Now it is stored in a single cell.Now i want to take each letter from the string separately.I want to take A first the G and so on. Cell array conversion is necessary in this case.So how to convert the cell content back to string again??

MSD
  • 109
  • 1
  • 2
  • 12
  • 1
    I would call it "accessing content stored in cells" rather than "converting cells to something else". related question: [Difference between accessing cell elements using {} and () (curly braces vs. parentheses)](http://stackoverflow.com/questions/9055015/difference-between-accessing-cell-elements-using-and-curly-braces-vs-par) – Eitan T Dec 09 '13 at 06:59

1 Answers1

5

You can get the string out of a cell with the curly braces ({}):

x='AGCT';
y(1) = {x};
y{1}
ans =    

AGCT

And you can string together indexing operators to get individual characters directly from the cell array. For example:

y{1}(2)
ans =

G

Also keep in mind that the char function can convert a cell array of strings into a 2D character array by vertically concatenating the strings while padding with white space as necessary:

S = char(C), when C is a cell array of strings, places each element of C into the rows of the character array S. Use CELLSTR to convert back.

This way you could convert your entire cell array into a 2D character array with just char(y), but I think you are looking for a way to do the indexing of individual characters directly from the cell array as above.

And speaking of cell array conversion, have a look at cellfun, which can be used to perform the same operation on each cell. For example, if you had a cell such as y = {'AGCT','CTGA'}; and you wanted the second character of each cell (a character array containing GT), you might be tempted to do y{:}(2), but this does not work (the first index must be a scalar). A solution is:

>> iBase = 2;
>> basei = cellfun(@(c)c(iBase),y)
basei =
GT
chappjc
  • 30,359
  • 6
  • 75
  • 132