MATLAB Answers

Howto Replace Specified and Non-Specified Elements in Matrix with Strings

1 view (last 30 days)
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,


Sign in to comment.

Accepted Answer

More Answers (1)

John D'Errico
John D'Errico on 31 May 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 =
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.


Sign in to comment.




Translated by