Azzera filtri
Azzera filtri

How to Convert a Logical Vector to a Character Vector?

31 visualizzazioni (ultimi 30 giorni)
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’ ]

Risposte (2)

Stephen23
Stephen23 il 17 Ago 2016
Modificato: Stephen23 il 18 Ago 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 Commenti
Stephen23
Stephen23 il 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"

Accedi per commentare.


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

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by