Strcat multiple cell arrays not outputing expected output
조회 수: 5 (최근 30일)
이전 댓글 표시
Hello, below is the sample code that I am using to generate cell array of labels
labels = strcat(repmat({'sample'}, 100,1),{'_'}, num2cell([1:100]'));
And I expect to have 100x1 cell with following entries: sample_1; sample_2; sample_3; ... sample_99; sample_100;
However, when I execute the code in MATLAB R2015a, I get the following, which is very confusing...
>> strcat(repmat({'sample'}, 100,1),{'_'}, num2cell([1:100]'))
ans =
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample'
'sample_ '
[1x8 char]
'sample_'
'sample_'
[1x8 char]
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_'
'sample_ '
'sample_!'
'sample_"'
'sample_#'
'sample_$'
'sample_%'
'sample_&'
'sample_''
'sample_('
'sample_)'
'sample_*'
'sample_+'
'sample_,'
'sample_-'
'sample_.'
'sample_/'
'sample_0'
'sample_1'
'sample_2'
'sample_3'
'sample_4'
'sample_5'
'sample_6'
'sample_7'
'sample_8'
'sample_9'
'sample_:'
'sample_;'
'sample_<'
'sample_='
'sample_>'
'sample_?'
'sample_@'
'sample_A'
'sample_B'
'sample_C'
'sample_D'
'sample_E'
'sample_F'
'sample_G'
'sample_H'
'sample_I'
'sample_J'
'sample_K'
'sample_L'
'sample_M'
'sample_N'
'sample_O'
'sample_P'
'sample_Q'
'sample_R'
'sample_S'
'sample_T'
'sample_U'
'sample_V'
'sample_W'
'sample_X'
'sample_Y'
'sample_Z'
'sample_['
'sample_\'
'sample_]'
'sample_^'
'sample__'
'sample_`'
'sample_a'
'sample_b'
'sample_c'
'sample_d'
Could someone help explain this? I appreciate the help in advance!
댓글 수: 0
채택된 답변
Stephen23
2016년 6월 14일
편집: Stephen23
2016년 6월 14일
Explanation
strcat concatenates strings. However num2cell([1:100]') are not strings, they are numeric scalars in a cell array. Where is the string conversion? There isn't any! So strcat thinks that those numeric values are the characters' values, and returns the equivalent character corresponding to each value (some characters are not printable):
>> char(32:100)
ans = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd
Solution
To generate strings of those numeric values, try this:
tmp = arrayfun(@num2str,[1:100].','UniformOutput',false)
and also note that you do not need to use repmat or to put the strings 'sample' and '_' into cell arrays: this is a total waste of time and makes the intent of the code much harder to understand. Don't make code more complicated than it needs to be, just do this:
out = strcat('sample_',tmp)
Or you could get rid of the strcat altogether, and just do it using one arrayfun call:
arrayfun(@(n)sprintf('sample_%d',n), [1:100], 'UniformOutput',false)
댓글 수: 2
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!