Borrar filtros
Borrar filtros

How to Convert a Logical Vector to a Character Vector?

31 visualizaciones (últimos 30 días)
Rightia Rollmann
Rightia Rollmann el 17 de Ag. de 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’ ]

Respuestas (2)

Stephen23
Stephen23 el 17 de Ag. de 2016
Editada: Stephen23 el 18 de Ag. de 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 comentarios
Stephen23
Stephen23 el 2 de Mzo. de 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"

Iniciar sesión para comentar.


Thorsten
Thorsten el 17 de Ag. de 2016
strrep(strrep(sprintf('%d ', A), '1', 'yes'), '0', 'no')

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by