display all elements in a nested cell array (with character entries)

狂风中的少年 提交于 2019-12-23 04:45:15

问题


I have the following:

a = 

{1x1 cell}    {1x1 cell}    {1x1 cell}    {1x1 cell} 

where:

a{:}

ans = 

'a'


ans = 

'a'


ans = 

'c'


ans = 

'a'

I want to have the characters: a a c a

Since I need the characters to print using fprintf

fprintf won't accept a{:}

If I do a{1}{:} will consider only the first character a

How to fix this? Thanks.


回答1:


If you only need the character vector 'aaca', you can use this:

a = {{'a'}, {'a'}, {'c'}, {'a'}};

a_CharVector = cellfun(@(x) char(x), a);

If you want the character vector 'a a c a ', you can use regexprep to add the spaces:

a_CharVectorWithSpaces = regexprep((cellfun(@(x) char(x), a)), '(.)', '$1 ');

To print a a c a with spaces and newline you can use this:

fprintf([ regexprep((cellfun(@(x) char(x), a)), '(.)', '$1 '), '\n' ]);

Edit: unnecessary anonymous function removed. @(x) is unnecessary in this case.

To get character vector 'aaca' this works:

a_CharVector = cellfun(@char, a);

And to get character vector 'a a c a ' you can use this:

a_CharVectorWithSpaces = regexprep((cellfun(@char, a)), '(.)', '$1 ');

To printf a a c a with newline:

fprintf([ regexprep((cellfun(@char, a)), '(.)', '$1 '), '\n' ]);


来源:https://stackoverflow.com/questions/10148955/display-all-elements-in-a-nested-cell-array-with-character-entries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!