Difference between num2cell(1:4)' and {'1','2','3','4'}' ?
古いコメントを表示
Hi,
I am having an error on creating a table with 'RowNames' property.
truc=array2table([-0.013 -0.470 0.109
-0.013 -0.454 0.107
-0.012 -0.437 0.104
0.009 0.077 -0.088],'VariableNames',{'Scx','SczF','SczR'},'RowNames',num2cell(1:4)');
Main error is: The RowNames property must be a cell array, with each element containing one nonempty character vector.
>> num2cell([1 2 3 4])'
ans =
4×1 cell array
[1]
[2]
[3]
[4]
>> {'1','2','3','4'}'
deux =
4×1 cell array
'1'
'2'
'3'
'4'
In both case it is a cell array, but the content is different.
3 件のコメント
John D'Errico
2017 年 11 月 21 日
Is it true that the number 1 is equal to the character string that contains the character '1'?
Of course not. So why are you surprised they are not the same?
採用された回答
その他の回答 (1 件)
As the error message says, the cell content must be character string and Adam notes the difference between the two forms you wrote; the first is numeric values placed into a cell array, the second is the string value but you wrote manually..
To build the equivalent cellstr array for the purpose use
> cellstr(num2str([1:3].','%d'))
ans =
'1'
'2'
'3'
>>
or similar.
However I'd note there's not a lot of point in creating row names that are just ordinal values in sequence as you can address rows numerical simply by using the row number in array expression syntax.
ERRATUM Corrected the misplaced transpose operator discussed in following comments -- dpb
3 件のコメント
Laurent Davenne
2017 年 11 月 21 日
Guillaume
2017 年 11 月 21 日
Humm....
Format is messed up when numbers go over 10
>> cellstr(num2str(1:14,'%d')')
ans =
27×1 cell array
'1'
''
'2'
''
'3'
''
'4'
''
'5'
''
'6'
''
'7'
''
'8'
''
'9'
'1'
'0'
'1'
'1'
'1'
'2'
'1'
'3'
'1'
'4'
in fact I even need it to work for decimals
cellstr(num2str(3:0.5:34,'%d')')
I am quite lost with format spec... :(
Misplaced location of the .' transpose operator to build the column vector, my bad. At the trailing location it takes the horizontal row vector of characters
>> num2str(1:14,'%d')
ans =
1 2 3 4 5 6 7 8 91011121314
>>
and transposes it to a column vector; hence the blank lines. What is needed and was intended is to transpose the numeric vector to column form, then convert it--
>> num2str([1:14].','%2d')
ans =
1
2
3
4
5
6
7
8
9
10
11
12
13
14
>> cellstr(num2str([1:14].','%2d'))
ans =
' 1'
' 2'
' 3'
' 4'
' 5'
' 6'
' 7'
' 8'
' 9'
'10'
'11'
'12'
'13'
'14'
>>
There will be some purists who'll nag me about using the [] where only () are needed, and it is true in a very deeply nested loop you might see a little performance hit, but I simply like the visual representation sufficiently to accept the hit.
カテゴリ
ヘルプ センター および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!