How can I get my output to come out in a string?

1 view (last 30 days)
I am currently using the following code:
x = cellfun(@num2str, num2cell(a), 'UniformOutput', true)
where
a= 'apple'
The code that I have now separates each character so it comes out to look like:
{{'a' 'p' 'p' 'l' 'e'}}
I want x to come out in a string such that it looks like:
{{'apple'}}
How can I change my code to make the output appear like this?
  1 Comment
Stephen23
Stephen23 on 3 Dec 2014
Edited: Stephen23 on 3 Dec 2014
Placing a string within two cell nested cell arrays is a little strange. Can you explain why this is needed, or how it will be used later? It may be that these arrays are not even necessary, and we could help you simplify your code by removing one/both of those cell arrays.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 3 Dec 2014
Edited: Stephen23 on 3 Dec 2014
This works for me:
a = 'apple';
output = {{a}};
You want it to "look like" {{'apple'}}, but as soon as your string 'apple' gets parsed by num2cell, it comes out as separate characters (in a cell array):
>> num2cell('apple')
ans =
'a' 'p' 'p' 'l' 'e'
Unless you join these characters back together again, then there in nothing in your code that will magically make one word out of them again. Also, applying num2str on a string produces exactly the same string as its input, which means that the entire cellfun does absolutely nothing of significance... So what is the intention of your code?
Do you want the string '{{apple}}' ? This can be achieved by a simple sprintf call:
output = sprintf('{{%s}}',a);
Or if you need those single quotes too to give '{{'apple'}}':
output = sprintf('{{''%s''}}',a);

More Answers (1)

Image Analyst
Image Analyst on 3 Dec 2014
Why do you want a cell within a cell. That's overlay complicated. Just stick "a" inside a cell but not within another cell:
a='apple'; % a is a string.
myCell = {a} % Stick string a inside a cell.
celldisp(myCell) % Display it.

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!