Cell array strings storage
显示 更早的评论
Two questions regarding cell arrays and strings:
1. When I enter a cell array that contains strings through the workspace, sometimes the strings appear in the cells as 'string' (with an apostrophe) and other times the strings appear as they are, without the apostrophe. I couldn't find a rule what happens when, or what is the differenece between these cases.
Is there an explanation for this?
2. When I initialize an array of strings in such a way that the strings appear in the workspace cell array with an apostrophe, and then try to access an element using array{1}, I get:
ans =
cell
'a'
to prevent the "cell" from appearing, I need to double access it (as if it is a cell inside a cell):
array{1}{1}
How can I initialize this in such a way that I can access that string directly without the double {}{}?
Thanks
3 个评论
There should be no reason to have a cell array of string, since a string (array) is the modern replacement of a cell array of char arrays.
Can you give an example of two cell arrays that display differently?
Adam
2018-7-25
You would need to show the code you are using to produce this. Cell arrays contain exactly what you tell them to, no more nor less, so it is down to how you define the code that will determine whether you get cells inside cells or chars. I'm not sure what you mean by strings appearing 'as they are' though. From your context I assume you use string to refer to a char array rather than an actual Matlab string, but chars in a cell array will naturally have the quotes e.g.
>> A = { 'a' }
A =
1×1 cell array
{'a'}
>> A{1}
ans =
'a'
Guillaume
2018-7-25
Yes you are right, every occurrence of the word "string" in my original post was supposed to be "char array".
Anyway, here is some code:
array = {'a', 'b', 'c'};
here, array{1} == 'a'
but then in this case: array2 = cellfun(@(x) regexp(x, '.*', 'match'), array)
you have to do array2{1}{1} to get that same 'a'
采纳的回答
更多回答(1 个)
With older MATLAB versions the rule was very simple: all arrays were displayed without the outermost array brackets/parentheses (and only showing the contents for the first nesting and only scalar numeric inside cells):
Char array:
>> 'abc' % -> remove ''
ans =
abc
>> {'abc'} % -> remove {}
ans =
'abc'
>> {{'abc'}} % -> remove {}
ans =
{1x1 cell}
Scalar numeric:
>> 1 % -> remove [] (implicit)
ans =
1
>> {1} % -> remove {}
ans =
[1]
>> {{1}} % -> remove {}
ans =
{1x1 cell}
Numeric array:
>> 1:3
ans =
1 2 3
>> {1:3}
ans =
[1x3 double]
>> {{1:3}}
ans =
{1x1 cell}
At some point recently this seems to have changed for cell arrays...
类别
在 帮助中心 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!