问题
I have a cell array of numeric strings e.g.:
labels = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'}
I'm trying to add a string ('Label '
) to the beginning of each array element without using any kind of loop, as the array is massive and I need the code to run quickly. My other requirement is the space after the word 'Label'
must be maintained once I apply it to the two-digit elements in the array. The result I want is:
fullLabels = {'Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5',
'Label 6', 'Label 7', 'Label 8', 'Label 9', 'Label 10',
'Label 11', 'Label 12'}
I tried using strcat() like this:
fullLabels = strcat('Label ', labels);
This is fine for the single-digit array elements, but when it is applied to the two-digit array elements, the space after 'Label'
is removed to give:
fullLabels = {..., 'Label10', 'Label11', 'Label12'}
回答1:
strcat
trims trailing whitespace from all inputs prior to concatenation. You will want to manually concatenate the strings using []
.
fullLabels = cellfun(@(x)['Label ', x], labels, 'UniformOutput', false)
% 'Label 1'
% 'Label 2'
% 'Label 3'
% 'Label 4'
% 'Label 5'
% 'Label 6'
% 'Label 7'
% 'Label 8'
% 'Label 9'
% 'Label 10'
% 'Label 11'
% 'Label 12'
You could also use something like regexprep
to prepend the label. This replaces the first character of each label with itself (\1
) with 'Label '
appended to the front.
fullLabels = regexprep(labels, '^.', 'Label \1')
Update
@Dev-iL's answer mentioned using a cell array to pass a space to strcat
which I wasn't aware of. Rather than concatenating the space, we could also just stick 'Label '
inside the cell.
strcat({'Label '}, labels)
回答2:
Since strcat
only removes trailing spaces, if you manage to get your number strings to begin with a space (using the settings of whatever converts them from "proper numbers"), you will not see this problem:
labels = {' 1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9', ' 10', ' 11', ' 12'};
fullLabels = strcat('Label',labels);
Alternatively, as mentioned here, you can "fool" strcat
by surrounding the space with a cell:
fullLabels = strcat('Label', {' '}, labels);
来源:https://stackoverflow.com/questions/37998621/in-matlab-how-do-i-insert-a-string-at-beginning-of-of-each-string-in-a-cell-arra