Howto Replace Specified and Non-Specified Elements in Matrix with Strings
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
William Collants
le 31 Mai 2020
Réponse apportée : John D'Errico
le 31 Mai 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 commentaires
Réponse acceptée
madhan ravi
le 31 Mai 2020
Modifié(e) : madhan ravi
le 31 Mai 2020
Wanted = repmat("neither",size(matrix));
Wanted(matrix == 0) = "zero";
Wanted(matrix == 1) = "one"
Plus de réponses (1)
John D'Errico
le 31 Mai 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 commentaires
Voir également
Catégories
En savoir plus sur Logical 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!