How to Convert a Logical Vector to a Character Vector?

31 次查看(过去 30 天)
What is the shortest way to convert a logical vector to a character vector with two arbitrary names for true and false values?
A = [ 0 1 0 1 1 1 ];
B = [ ‘no’ ‘yes’ ‘no’ ‘yes’ yes’ yes’ ]

回答(2 个)

Stephen23
Stephen23 2016-8-17
编辑:Stephen23 2016-8-18
>> A = [0,1,0,1,1,1];
>> X = {'no','yes'};
>> B = X(1+A)
B = no yes no yes yes yes
Note about "Character Vector": MATLAB character arrays consist solely of characters: they are not like a "list" of strings (or character arrays) that many other languages use. This means that your output B is not really a "list" containing several strings, it is actually just one string:
>> ['no' 'yes' 'no' 'yes' 'yes' 'yes' ]
ans = noyesnoyesyesyes
This is because the [] square brackets are NOT a "list" operator (MATLAB does not have a list operator) but they are in fact a concatenation operator: thus in your example all of the strings are simply concatenated together to make one string. Note that character arrays (strings) and numeric arrays work in exactly the same way in this respect, there is no difference in how they can be concatenated, indexed, etc.
If you want something like a list of separate strings, then you can use a cell array to contain the strings: this is what my code uses.
  4 个评论
Stephen23
Stephen23 2021-3-2
Using the string data class (introduced R2016b/R2017a):
A = [0,1,0,1,1,1];
X = ["no","yes"];
B = X(1+A)
B = 1×6 string array
"no" "yes" "no" "yes" "yes" "yes"

请先登录,再进行评论。


Thorsten
Thorsten 2016-8-17
strrep(strrep(sprintf('%d ', A), '1', 'yes'), '0', 'no')

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by