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??

1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.