Howto Replace Specified and Non-Specified Elements in Matrix with Strings
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
William Collants
el 31 de Mayo de 2020
Respondida: John D'Errico
el 31 de Mayo de 2020
Hi Guys,
In a given Matrix, I would like to replace/ substitute
every Element equal to 0 with the String "zero"
every Element equal to 1 with the String "one"
and Every Other Element, of any other Value with the String "neither".
What would be an elegant way to accomplish this?
Kind Regards,
T
0 comentarios
Respuesta aceptada
madhan ravi
el 31 de Mayo de 2020
Editada: madhan ravi
el 31 de Mayo de 2020
Wanted = repmat("neither",size(matrix));
Wanted(matrix == 0) = "zero";
Wanted(matrix == 1) = "one"
Más respuestas (1)
John D'Errico
el 31 de Mayo de 2020
You cannot do so. Sort of. Ok, well, you can. sort of.
A double precision matrix in MATLAB is a rectangular array that contains just one number per element. A string is not an option. So you cannot do it.
IF you are willing to convert the matrix into some other class of array, a cell array stands out at least immediately, then you can do so, using a tool like mat2cell. Then there is no problem with going forwards with your scheme to replace any elements as you wish with anything you want. Note that cell arrays don't display that terribly well, because they can contain anything at all. So you can do it, but not terribly well.
Or, you can do this:
X = randi([0 2],[3,4])
X =
2 0 2 1
0 1 2 1
2 1 0 1
S = repmat("neither",size(X));
S(X == 0) = "zero";
S(X == 1) = "one";
S
S =
3×4 string array
"neither" "zero" "neither" "one"
"zero" "one" "neither" "one"
"neither" "one" "zero" "one"
Which will only require a recent enough MATLAB release that the string class exists. It was R2016b when they appeared.
0 comentarios
Ver también
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!