How do I create a string for values

1 view (last 30 days)
I have written this code to produce values from 1 - 3 with set probabilities:
B = randi(3,1);
P = B;
for i = 1:50
z=rand;
if B == 1
if z < .4
B = 3;
end
elseif z > .4 && z <.6
B = 2;
elseif B == 2
if z < .2
B = 1;
end
elseif z > .2 && z < .4
B =3;
elseif B == 3
if z < .2
B = 1;
elseif z > .2 && z < .25
B = 2;
end
end
P = [P;B];
end
I would like to give each number a name, so 1 = A, 2 = B and 3 = C. I tried doing this:
for c = 1:50
if P(c) == 1
P(c) = "A";
elseif P(c) == 2
P(c) = "U";
else
P(c) = "D";
end
end
but I keep receiving NaN. What am I doing wrong?
  2 Comments
YT
YT on 6 Sep 2018
Please format your code using the "{}code" button
Sebastiano Inturrisi
Sebastiano Inturrisi on 6 Sep 2018
Just fixed this issue, sorry about that.

Sign in to comment.

Accepted Answer

jonas
jonas on 6 Sep 2018
Edited: jonas on 6 Sep 2018
The class of P is double. You cannot put a string in a double, because a string is not a number. Try replacing the final loop with this
P=num2str(P);
P(P=='1')="A";
P(P=='2')="U";
P(P=='3')="D";
P =
51×1 char array
'D'
'A'
'D'
'D'
...and so on
  1 Comment
Sebastiano Inturrisi
Sebastiano Inturrisi on 6 Sep 2018
This is perfect. Thank you! I now see why my code was producing NaN values.

Sign in to comment.

More Answers (2)

OCDER
OCDER on 6 Sep 2018
You are getting NaN because you are trying to store a string value in a matrix that can only hold numeric values. See example 1 below.
If you want to store ONLY strings, then use a string array. See example 2 below.
If you want to store any type of data, like strings and numbers, then use a cell array. See example 3. below.
%Example 1 (your situation)
A = rand(1, 2);
A(1) = "A"; %NaN
A(2) = 1; %1
%Example 2
A = strings(1, 2);
A(1) = "A"; %"A"
A(2) = 1; %"1"
%Example 3
A = cell(1, 2);
A{1} = "A"; %"A"
A{2} = 1; %1
  1 Comment
Sebastiano Inturrisi
Sebastiano Inturrisi on 6 Sep 2018
Explaining the problem this way makes things very clear. Thank you for your help!

Sign in to comment.


YT
YT on 6 Sep 2018
Well P is of type double and you're trying to smash some strings into them, which results in NaNs. You have several options, but personally I like using cell arrays.
close all;clear all;
P = randi(3,[20 1]);
Pcell = {};
for c = 1:length(P);
if P(c) == 1
Pcell{c} = "A";
elseif P(c) == 2
Pcell{c} = "U";
else
Pcell{c} = "D";
end
end
%final cell
Pcell

Categories

Find more on Characters and Strings in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!