How do I create a string for values

1 回表示 (過去 30 日間)
Sebastiano Inturrisi
Sebastiano Inturrisi 2018 年 9 月 6 日
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
Sebastiano Inturrisi 2018 年 9 月 6 日
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
  1 件のコメント
Sebastiano Inturrisi
Sebastiano Inturrisi 2018 年 9 月 6 日
This is perfect. Thank you! I now see why my code was producing NaN values.

サインインしてコメントする。

その他の回答 (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
Sebastiano Inturrisi 2018 年 9 月 6 日
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 Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by