How to write a loop for vectors?
Ältere Kommentare anzeigen
For the attached document can someone tell me if my script file is correct. Im confused on how to get the output to determine if its a pair or 3,4,5 of a kind. I'll attach the script and if someone could maybe run it, and see whats going on with it that would help. Ive went to the tutoring lab, but no one could help. I dont know if this question is just tough or what.
Akzeptierte Antwort
Weitere Antworten (1)
Manolis Michailidis
am 2 Okt. 2015
Hello, the main issue is that in your loop you should use cell because for every iteration you have different dice results and the new overwrite the previous. Here is what i done see if it suits your demands. Also the ''counts'' variable does not seems ok to me so i made some modification in your code. As for the display part you can modify it for your needs. Note it maybe much simplier ways for counter elements ( http://www.mathworks.com/matlabcentral/answers/12636-how-can-i-count-the-number-of-times-a-number-appear-in-a-vector ) but i don't have much time and please copy the 'cell2mat.m'. function from below to your matlab path, it trasforms cell array into matrix.
rng('shuffle')
numRolls=input('Please enter how many rolls you would like to simulate:');
%counts =zeros([1,5]); % list of how many times each number came up
numDice=5;
for r = 1 : numRolls
rolls{r} = randi([1 6],[1 5]);
rolls{r} = sort(rolls{r});
theSum{r}=sum(rolls{r});
end
c1=cell2array(rolls);
for kk=1:size(c1,2)
s3(:,kk)=sum(c1(:,kk) == 3); % how many times '3' appears
s4(:,kk)=sum(c1(:,kk) == 4); % how many times '4' appears
s5(:,kk)=sum(c1(:,kk) == 5); % how many times '5' appears
end
%if any(counts == 3)
%fprintf('The role is a three of a kind')
%elseif any(counts == 4)
%fprintf('The role is a four of a kind')
%elseif any(counts == 5)
%fprintf('The role is a five of a kind')
%end
% Now normalize to get fraction of time each number came up.
%counts = (counts / numRolls)*100 % Multiply by 100 if you want percentage instead of a fraction.
_________________________________________
function [Y]=cell2array(X)
lns = cellfun(@length,X);
mt = zeros(numel(X),max(lns));
for ii = 1:numel(X)
mt(ii,1:lns(ii)) = X{ii};
end
Y=mt';
end
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!