Reputation: 179
I want to generate sequence of toss outcomes of n trials using the help of rand() function. I read about rand() from MATLAB reference code that rand() generates 0 and 1 or random numbers within specified range, how I can make the outcome of rand() to be variable H and T - that represent head and tail- ?
Sample Code, let 1 be H and 0 is T:
n = 10;
x = rand(1,n)<0.5;
t = 1:10;
plot(t,x);
title('outcomes of tossing a coin 10 times');
xlabel('trials');
ylabel('outcome');
axis([1 10 0 1.2]);
display(x);
Command Window
x =
1 0 1 0 0 0 1 1 1 0
Upvotes: 0
Views: 134
Reputation: 104555
That's pretty easy. Create a cell array of strings that contains two strings: Heads
and Tails
:
outcome = {'Heads', 'Tails'};
Next, you can use rand
like you did before, but then cast this to double
and add 1 so that you get values that are 1 and 2. The reason why you need this is because you can use this output to index into outcome
, as MATLAB begins accessing values at index 1. However, if you create your logical
vector of rand(1,n) < 0.5
then add 1 to this result, the output will be coalesced into a double
anyway so you would implicitly be casting the result.
You can then use this to index into outcome
to get your desired results. To reproduce this on my end:
%// Set seed for reproducibility
rng(123123);
x = rand(10,1) < 0.5; %// Generate random vector of logical 0s and 1s
%// Cast to double then add with 1 so we can generate a vector of 1s and 2s
x = x + 1;
%// Declare that cell array of strings
outcome = {'Heads', 'Tails'};
%// Use the vector of 1s and 2s to get our desired strings
y = outcome(x)
... and we get:
y =
Columns 1 through 7
'Tails' 'Heads' 'Tails' 'Heads' 'Heads' 'Tails' 'Tails'
Columns 8 through 10
'Tails' 'Heads' 'Tails'
Note that y
will be a cell array of strings, and so if you want to access a particular string, do:
str = y{idx};
idx
is the position of where you want to access.
However, if I can suggest something else, you can try using randi
and specify the maximum value of what you want to generate to be 2. This way, you are guaranteed to produce values between 1 and 2 like so:
x = randi(2, 10, 1);
This would generate a 10 x 1
array of values that are either 1 or 2. To me this looks more readable, but whatever you're comfortable with. You can then use this result and directly access outcome
to get what you want.
Upvotes: 4