storing fprintf as an array.
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Jide Williams
il 3 Mar 2020
Commentato: Jide Williams
il 3 Mar 2020
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
0 Commenti
Risposta accettata
David Hill
il 3 Mar 2020
Why do a loop?
product=rand(1,20);
product(product>=.5)=72;
product(product<.5)=84;
product=char(product);
Più risposte (1)
Walter Roberson
il 3 Mar 2020
Outcome(i) = 'H';
The closest to your current code would be
Outcome{i} = sprintf('%s\n', 'H') ;
4 Commenti
Walter Roberson
il 3 Mar 2020
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);
Vedere anche
Categorie
Scopri di più su Adding custom doc in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!