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 件のコメント
採用された回答
その他の回答 (2 件)
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
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
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!