create multiple separate vectors from a For loop
조회 수: 4 (최근 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!

