Howto Replace Specified and Non-Specified Elements in Matrix with Strings
10 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
madhan ravi
2020-5-31
编辑:madhan ravi
2020-5-31
Wanted = repmat("neither",size(matrix));
Wanted(matrix == 0) = "zero";
Wanted(matrix == 1) = "one"
更多回答(1 个)
John D'Errico
2020-5-31
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!