The outcome of the code below gives H T H T T depending on random function. How do I store the outcome of the 20 iterations into a variable called 'product' ; for example: product =[ H T H T T......] so that whenever I need it, I can fetch the outcome by just typing 'product'
fprintf('The Outcomes are:\n')
for i = 1:20
A = rand(i,1);
if A(i) >= 0.5000
fprintf('%s\n', 'H');
else
fprintf('%s\n', 'T');
end
end

 채택된 답변

David Hill
David Hill 2020년 3월 3일

0 개 추천

Why do a loop?
product=rand(1,20);
product(product>=.5)=72;
product(product<.5)=84;
product=char(product);

댓글 수: 1

Jide Williams
Jide Williams 2020년 3월 3일
Thanks, i needed the for loop because I want to perform a Monte Carlo Analysis. This is better in loops

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2020년 3월 3일

1 개 추천

Outcome(i) = 'H';
The closest to your current code would be
Outcome{i} = sprintf('%s\n', 'H') ;

댓글 수: 4

Jide Williams
Jide Williams 2020년 3월 3일
Thanks, and yes, I did that but my result is weird. One would expect a 'H' if A >= 0.5 but it returned a tail T, so I felt maybe that isnt right!
Jide Williams
Jide Williams 2020년 3월 3일
for example for the first three outcomes A =
0.0765
0.7809
0.1307
Outcome should be (T H T), right? But it returned: (T H H)
No. You call
A = rand(i, 1)n
That defines A to be a column vector of random numbers with i values in the vector. In the next line you access A(i) which is only the last of those values and not any of the values before that. But when you are examining to see whether the code works, you are reading off the first of the values, not the last. Or perhaps after the loop you are examining A, but since you overwrite all of A each time, the values that were used to make the decision have been thrown away and replaced by new values before you look.
Your code should be:
A(i) = rand(1,1);
Jide Williams
Jide Williams 2020년 3월 3일
Yeah i have seen my mistakes. Thans

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2020년 3월 3일

댓글:

2020년 3월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by