MATLAB: Replacing numbers with text

replace

Hello everyone,
I want to replace text with numbers. 1=s, 3=r, 4=b . I tried 2 methods. Cant figure why niether of the codes wont work . What am I doing wrong?
% Method 1 / not working returns "Index exceeds the number of array elements (3)." error
mymat= [ 4 4 4
3 4 4
1 4 4
4 3 4
3 3 3
1 3 4
4 1 4]
t = string(["b", "r", "s"])
comMat = t(mymat)
%Method 2 / returns a NaN matrix and that's not what I want.
mymat= [ 4 4 4
3 4 4
1 4 4
4 3 4
3 3 3
1 3 4
4 1 4]
mymat(mymat==4)= "b"
mymat(mymat==3)= "r"
mymat(mymat==1)= "s"
mymat
thank you for your time in advance.

Best Answer

Here's a more flexible alternative.
mymat= [ 4 4 4
3 4 4
1 4 4
4 3 4
3 3 3
1 3 4
4 1 4];
t = ["s", "r", "b"];
v = unique(mymat(:)); % or maybe you want unique(mymat(:),'stable')
B = string(categorical(mymat,v,t))
B = 7×3 string array
"b" "b" "b" "r" "b" "b" "s" "b" "b" "b" "r" "b" "r" "r" "r" "s" "r" "b" "b" "s" "b"
Also works for any values
mymat(mymat==4) = 10;
mymat(mymat==1) = -42.5
mymat = 7×3
10.0000 10.0000 10.0000 3.0000 10.0000 10.0000 -42.5000 10.0000 10.0000 10.0000 3.0000 10.0000 3.0000 3.0000 3.0000 -42.5000 3.0000 10.0000 10.0000 -42.5000 10.0000
B = string(categorical(mymat, unique(mymat(:)), ["s", "r", "b"]))
B = 7×3 string array
"b" "b" "b" "r" "b" "b" "s" "b" "b" "b" "r" "b" "r" "r" "r" "s" "r" "b" "b" "s" "b"
Another alternative
B= discretize(mymat, [unique(mymat(:));inf], ["s", "r", "b"])
B = 7×3 string array
"b" "b" "b" "r" "b" "b" "s" "b" "b" "b" "r" "b" "r" "r" "r" "s" "r" "b" "b" "s" "b"