create multiple separate vectors from a For loop
6 次查看(过去 30 天)
显示 更早的评论
I want to create a for loop that makes a pre-specified amount of passes through the loop. I have done that, but the results end up in an array. I want each pass through the loop to make a new vector. For example, I want to roll three dice, 200 times each, I then want three vectors created labelled dice1, dice2, dice3, each with 200 values.
for n = 1 : diceAmount
if (diceType == 1)
diceSelected=("d4 Selected")
diceRoll{n} = randi(4,1,200)
i already have diceAmount, and diceType working properly, the rest of the for loop allows for different dice selections.
3 个评论
Steven Lord
2020-11-20
Storing the dice in three separate cells in diceRoll will make it more difficult to work with all diceAmount dice "in spot 83 of the three arrays". The code to compute score in the example I wrote for my answer would be much more complicated with your approach.
回答(2 个)
Ameer Hamza
2020-11-20
编辑:Ameer Hamza
2020-11-20
You current approach is optimal. Creating seperate variables like dice1, dice2, .. is not a good coding approach: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. It will make your code inefficient and hard to maintain or debug.
2 个评论
Stephen23
2020-11-20
"...is there then a way after the cell is created to extract the data into new variables because that data needs to be used after to see if each roll is over a certain number, a number that is inputed by the user."
Either way you have exactly the same data available to you, so either way you can do that comparison. The approach you are trying will be more complex and much less effiicient than simply accessing the data directly from the cell array.
Steven Lord
2020-11-20
Rather than creating several different variables with numbered names or even a cell array, I'd prefer to create an array.
nsides = 6;
ndice = 4;
ntrials = 10;
A = randi(nsides, [ntrials ndice])
Doing this lets you operate on a set of rolls all at once. For instance, if I wanted to take the highest three of each set of four dice and add them up:
score = sum(A, 2)-min(A, [], 2)
If I wanted to check if the "first die" was fair or not, I could do that.
B = randi(nsides, [1e6 ndice]);
histogram(B(:, 1))
Looks pretty uniform to me.
C = randi(nsides+1, [1e6 1]);
C(C == nsides+1) = 1;
histogram(C)
Looks very biased (as expected from the way I constructed C.)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

