How do I create a string for values

조회 수: 1 (최근 30일)
Sebastiano Inturrisi
Sebastiano Inturrisi 2018년 9월 6일
댓글: 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 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