Effacer les filtres
Effacer les filtres

How to Convert a Logical Vector to a Character Vector?

31 vues (au cours des 30 derniers jours)
Rightia Rollmann
Rightia Rollmann le 17 Août 2016
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’ ]

Réponses (2)

Stephen23
Stephen23 le 17 Août 2016
Modifié(e) : Stephen23 le 18 Août 2016
>> 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 commentaires
Stephen23
Stephen23 le 2 Mar 2021
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"
Giridhar sai pavan kumar Konduru
you are amazing

Connectez-vous pour commenter.


Thorsten
Thorsten le 17 Août 2016
strrep(strrep(sprintf('%d ', A), '1', 'yes'), '0', 'no')

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by