How do I create a string for values

1 次查看(过去 30 天)
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 个评论
YT
YT 2018-9-6
Please format your code using the "{}code" button
Sebastiano Inturrisi
Just fixed this issue, sorry about that.

请先登录,再进行评论。

采纳的回答

jonas
jonas 2018-9-6
编辑:jonas 2018-9-6
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

更多回答(2 个)

OCDER
OCDER 2018-9-6
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 个评论
Sebastiano Inturrisi
Explaining the problem this way makes things very clear. Thank you for your help!

请先登录,再进行评论。


YT
YT 2018-9-6
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

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by