convert values to string

2 次查看(过去 30 天)
Ingrid
Ingrid 2015-12-21
评论: Guillaume 2015-12-21
I have a vector with values to define groups (groupValue, in this case 1000x1 array with values from 1 to 5) I also have a cell array with strings for each of these values (labels, 5x1 cell array) I want to have a 1000x1 cell array with strings for the labels instead of values. How can I do this more efficiently i.e. without a for loop?
for kk = 1:nElements
groupLabels{kk} = labels{groupValue(kk)};
end

采纳的回答

Guillaume
Guillaume 2015-12-21
Simply,
groupLabels = labels(groupValue);
  2 个评论
Ingrid
Ingrid 2015-12-21
when I tried this directly (I first tried to do the assignment of the labels to the data directly with indexing larger than threshold values) and then it gave me warnings of improper assignments and dimensions that did not correspond. So I had no clue that in this form it was possible.
Guillaume
Guillaume 2015-12-21
Yes, for this to work groupValue must be integers between 1 and numel(labels). You could precede the above line with:
validateattributes(groupValue, {'numeric'}, {'positive', 'integer', '<=', numel(labels)}, '', 'groupValue'};

请先登录,再进行评论。

更多回答(2 个)

Geoff Hayes
Geoff Hayes 2015-12-21
Ingrid - if labels is your cell array of string labels and groupValue is your integer array of group values (or indices into labels) then perhaps you could try something like
groupLabels = labels(groupValue);

Renato Agurto
Renato Agurto 2015-12-21
hello. This should work
groupLabels = labels(groupValue);

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by