I have a 1000 x 5 sorted matrix with numbers from 1-13. Each number denotes the numerical value of a playing card. The Ace has the value 1, then the numbers 2 through 10 follow, then the Jack has value 11, Queen with value 12 and King with value 13. Therefore, each row of this matrix constitutes a poker hand. I am trying to create a program that recognizes poker hands using these cards that are enumerated in this way.
For example:
A = [1 1 2 4 5; 2 3 4 5 7; 3, 3, 5, 5, 6; 8, 8, 8, 9, 9]
Therefore, in this matrix A, the first row has a pair (1,1). The second row has high card (7), the third row has two pair ((3,3) and (5,5)) and the last one is a full house (Pair of 9s and 3 of a kind (8).
Is there a good way to do this in MATLAB?
bsxfun won't work for this situation. This is a counting problem. It's all a matter of counting what you have. Specifically, poker hands deal with counting up how much of each card you have, and figuring out the right combination of counts to get a valid hand. Here's a nice picture that shows us every possible poker hand known to man:
Source: http://www.bestonlinecasino.tips
Because we don't have the suits in your matrix, I'm going to ignore the Royal Flush, Straight Flush and the Flush scenario. Every hand you want to recognize can be chalked up to taking a histogram of each row with bins from 1 to 13, and determining if (in order of rank):
Situation #1: A high hand - all of the bins have a bin count of exactly 1
Situation #2: A pair - you have exactly 1 bin that has a count of 2
Situation #3: A two pair - you have exactly 2 bins that have a count of 2
Situation #4: A three of a kind - you have exactly 1 bin that has a count of 3
Situation #5: Straight - You don't need to compute the histogram here. Simply sort your hand, and take neighbouring differences and make sure that the difference between successive values is 1.
Situation #6: Full House - you have exactly 1 bin that has a count of 2 and you have exactly 1 bin that has a count of 3.
Situation #7: Four of a kind - you have exactly 1 bin that has a count of 4.
As such, find the histogram of your hand using histc or histcounts depending on your MATLAB version. I would also pre-sort your hand over each row to make things simpler when finding a straight. You mentioned in your post that the matrix is pre-sorted, but I'm going to assume the general case where it may not be sorted.
As such, here's some pre-processing code, given that your matrix is in A:
Asort = sort(A,2); %// Sort rowwise
diffSort = diff(Asort, 1, 2); %// Take row-wise differences
counts = histc(Asort, 1:13, 2); %// Count each row up
diffSort contains column-wise differences over each row and counts gives you a N x 13 matrix where N are the total number of hands you're considering... so in your case, that's 1000. For each row, it tells you how many of a particular card has been encountered. So all you have to do now is go through each situation and see what you have.
Let's make an ID array where it's a vector that is the same size as the number of hands you have, and the ID tells you which hand we have played. Specifically:
* ID = 1 --> High Hand
* ID = 2 --> One Pair
* ID = 3 --> Two Pairs
* ID = 4 --> Three of a Kind
* ID = 5 --> Straight
* ID = 6 --> Full House
* ID = 7 --> Four of a Kind
As such, here's what you'd do to check for each situation, and allocating out to contain our IDs:
%// To store IDs
out = zeros(size(A,1),1);
%// Variables for later
counts1 = sum(counts == 1, 2);
counts2 = sum(counts == 2, 2);
counts3 = sum(counts == 3, 2);
counts4 = sum(counts == 4, 2);
%// Situation 1 - High Hand
check = counts1 == 5;
out(check) = 1;
%// Situation 2 - One Pair
check = counts2 == 1;
out(check) = 2;
%// Situation 3 - Two Pair
check = counts2 == 2;
out(check) = 3;
%// Situation 4 - Three of a Kind
check = counts3 == 1;
out(check) = 4;
%// Situation 5 - Straight
check = all(diffSort == 1, 2);
out(check) = 5;
%// Situation 6 - Full House
check = counts2 == 1 & counts3 == 1;
out(check) = 6;
%// Situation 7 - Four of a Kind
check = counts4 == 1;
out(check) = 7;
Situation #1 basically checks to see if all of the bins that are encountered just contain 1 card. If we check for all bins that just have 1 count and we sum all of them together, we should get 5 cards.
Situation #2 checks to see if we have only 1 bin that has 2 cards and there's only one such bin.
Situation #3 checks if we have 2 bins that contain 2 cards.
Situation #4 checks if we have only 1 bin that contains 3 cards.
Situation #5 checks if the neighbouring differences for each row of the sorted result are all equal to 1. This means that the entire row consists of 1 when finding neighbouring distances. Should this be the case, then we have a straight. We use all and check every row independently to see if all values are equal to 1.
Situation #6 checks to see if we have one bin that contains 2 cards and one bin that contains 3 cards.
Finally, Situation #7 checks to see if we have 1 bin that contains 4 cards.
A couple of things to note:
A straight hand is also technically a high hand given our definition, but because the straight check happens later in the pipeline, any hands that were originally assigned a high hand get assigned to be a straight... so that's OK for us.
In addition, a full house can also be a three of a kind because we're only considering the three of a kind that the full house contains. However, the later check for the full house will also include checking for a pair of cards, and so any hands that were assigned a three of a kind will become full houses eventually.
One more thing I'd like to note is that if you have an invalid poker hand, it will automatically get assigned a value of 0.
Running through your example, this is what I get:
>> out
out =
2
1
3
6
This says that the first hand is a one pair, the next hand is a high card, the next pair is two pairs and the last hand is a full house. As a bonus, we can actually output what the strings are for each hand:
str = {'Invalid Hand', 'High Card', 'One Pair', 'Two Pair', 'Three of a Kind', 'Straight', 'Full House', 'Four of a Kind'};
hands = str(out+1);
I've made a placeholder for the invalid hand, and if we got a legitimate hand in our vector, you simply have to add 1 to each index to access the right hand. If we don't have a good hand, it'll show you an Invalid Hand string.
We get this for the strings:
hands =
'One Pair' 'High Card' 'Two Pair' 'Full House'
Related
This question already has answers here:
Generate a matrix containing all combinations of elements taken from n vectors
(4 answers)
Closed 5 years ago.
I want to create all pattern combination which possible occur
For example, I have three ball and I want to pick 3 times. All possible is 27 events but I want to create all possible event in array like this
[1 1 1; 1 1 2; 1 1 3; 1 2 1 ;....]
Dose anyone can help me to write m-file in matlab program, please?
This can be done very easily with base conversion.
If the number of balls does not exceed 10
M = 3; % Number of balls. Must not exceed 10
N = 3; % Number of draws
result = dec2base(0:M^N-1, M)-'0'+1;
Note that dec2base ouputs chars, not numbers, and hence the -'0' part. Characters in arithmetic operations behave like their corresponding ASCII codes. So subtracting '0' transforms characters '0', '1', ..., '9' into the corresponding numbers.
With this approach M cannot exceed 10 because then dec2bin would output '0', '1', ..., '9', 'A', 'B' ... and the character arithmetic would not give the correct result for 'A', 'B', ... But this can be easily solved as follows.
For number of balls up to 36
M = 12; % Number of balls. Must not exceed 36
N = 2; % Number of draws
result = dec2base(0:M^N-1, M)-'0'+1; % same as before
result = result - ('A'-'9'-1)*(result>10); % correction
The new line simply corrects the results for 'A', 'B', ... by subtracting 'A'-'9'-1, to compensate the fact that '9' and 'A' do not have consecutive ASCII codes.
With this approach M cannot exceed 36 because of dec2base restrictions.
You can create the result like this for the specific case:
firstCol = [ones(9,1);2*ones(9,1);3*ones(9,1)];
secondCol = repeat([ones(3,1);2*ones(3,1);3*ones(3,1)],1,3);
thirdCol = repeat([1;2;3],1,9);
result = [firstCol secondCol thirdCol];
First, repeat 9 times 1,2, and 3 for first column. then repeat each of them 3 times for the second column and choose the third column once for each item. Indeed, this generate the all possible choices for each location.
How? If you suppose the first element is 1, you have 3 choice for the second place, and 3 choice for the third place. Hence, you have 9 possible option when the first place is 1. Also, fix the second place, and analyze this. You can generalize this for 2 and 3. The above code, try to generate possibilities based on this explanation.
In the above, ones generate a matrix which all elements are 1 with the specified size and repeat function repeats the specified matrix in the specified size and dimension. You can check the documentation to know more about them.
Hence, You can generalize it for n like the following:
n = 10;
result = zeros(3^n,3);
for idx = 1:n
result(:,idx) = repeat([ones(3^(n-idx),1);2*ones(3^(n-idx),1);3*ones(3^(n-idx),1)],1,3^(idx-1));
end
I am new to matlab and I was wondering what it meant to use logical indexing/masking to extract data from a matrix.
I am trying to write a function that accepts a matrix and a user-inputted value to compute and display the total number of values in column 2 of the matrix that match with the user input.
The function itself should have no return value and will be called on later in another loop.
But besides all that hubbub, someone suggested that I use logical indexing/masking in this situation but never told me exactly what it was or how I could use it in my particular situation.
EDIT: since you updated the question, I am updating this answer a little.
Logical indexing is explained really well in this and this. In general, I doubt, if I can do a better job, given available time. However, I would try to connect your problem and logical indexing.
Lets declare an array A which has 2 columns. First column is index (as 1,2,3,...) and second column is its corresponding value, a random number.
A(:,1)=1:10;
A(:,2)=randi(5,[10 1]); //declares a 10x1 array and puts it into second column of A
userInputtedValue=3; //self-explanatory
You want to check what values in second column of A are equal to 3. Imagine as if you are making a query and MATLAB is giving you binary response, YES (1) or NO (0).
q=A(:,2)==3 //the query, what values in second column of A equal 3?
Now, for the indices where answer is YES, you want to extract the numbers in the first column of A. Then do some processing.
values=A(q,2); //only those elements will be extracted: 1. which lie in the
//second column of A AND where q takes value 1.
Now, if you want to count total number of values, just do:
numValues=length(values);
I hope now logical indexing is clear to you. However, do read the Mathworks posts which I have mentioned earlier.
I over simplified the code, and wrote more code than required in order to explain things. It can be achieved in a single-liner:
sum(mat(:,2)==userInputtedValue)
I'll give you an example that may illustrate what logical indexing is about:
array = [1 2 3 0 4 2];
array > 2
ans: [0 0 1 0 1 0]
using logical indexing you could filter elements that fullfil a certain condition
array(array>2) will give: [3 4]
you could also perform alterations to only those elements:
array(array>2) = 100;
array(array<=2) = 0;
will result in "array" equal to
[0 0 100 0 100 0]
Logical indexing means to have a logical / Boolean matrix that is the same size as the matrix that you are considering. You would use this as input into the matrix you're considering, and any locations that are true would be part of the output. Any locations that are false are not part of the output. To perform logical indexing, you would need to use logical / Boolean operators or conditions to facilitate the selection of elements in your matrix.
Let's concentrate on vectors as it's the easiest to deal with. Let's say we had the following vector:
>> A = 1:9
A =
1 2 3 4 5 6 7 8 9
Let's say I wanted to retrieve all values that are 5 or more. The logical condition for this would be A >= 5. We want to retrieve all values in A that are greater than or equal to 5. Therefore, if we did A >= 5, we get a logical vector which tells us which values in A satisfy the above condition:
>> A >= 5
ans =
0 0 0 0 1 1 1 1 1
This certainly tells us where in A the condition is satisfied. The last step would be to use this as input into A:
>> B = A(A >= 5)
B =
5 6 7 8 9
Cool! As you can see, there isn't a need for a for loop to help us select out elements that satisfy a condition. Let's go a step further. What if I want to find all even values of A? This would mean that if we divide by 2, the remainder would be zero, or mod(A,2) == 0. Let's extract out those elements:
>> C = A(mod(A,2) == 0)
C =
2 4 6 8
Nice! So let's go back to your question. Given your matrix A, let's extract out column 2.
>> col = A(:,2)
Now, we want to check to see if any of column #2 is equal to a certain value. Well we can generate a logical indexing array for that. Let's try with the value of 3:
>> ind = col == 3;
Now you'll have a logical vector that tells you which locations are equal to 3. If you want to determine how many are equal to 3, you just have to sum up the values:
>> s = sum(ind);
That's it! s contains how many values were equal to 3. Now, if you wanted to write a function that only displayed how many values were equal to some user defined input and displayed this event, you can do something like this:
function checkVal(A, val)
disp(sum(A(:,2) == val));
end
Quite simply, we extract the second column of A and see how many values are equal to val. This produces a logical array, and we simply sum up how many 1s there are. This would give you the total number of elements that are equal to val.
Troy Haskin pointed you to a very nice link that talks about logical indexing in more detail: http://www.mathworks.com/help/matlab/math/matrix-indexing.html?refresh=true#bq7eg38. Read that for more details on how to master logical indexing.
Good luck!
%% M is your Matrix
M = randi(10,4)
%% Val is the value that you are seeking to find
Val = 6
%% Col is the value of the matrix column that you wish to find it in
Col = 2
%% r is a vector that has zeros in all positions except when the Matrix value equals the user input it equals 1
r = M(:,Col)==Val
%% We can now sum all the non-zero values in r to get the number of matches
n = sum(r)
M =
4 2 2 5
3 6 7 1
4 4 1 6
5 8 7 8
Val =
6
Col =
2
r =
0
1
0
0
n =
1
For my experiment I have 20 categories which contain 9 pictures each. I want to show these pictures in a pseudo-random sequence where the only constraint to randomness is that one image may not be followed directly by one of the same category.
So I need something similar to
r = randi([1 20],1,180);
just with an added constraint of two numbers not directly following each other. E.g.
14 8 15 15 7 16 6 4 1 8 is not legitimate, whereas
14 8 15 7 15 16 6 4 1 8 would be.
An alternative way I was thinking of was naming the categories A,B,C,...T, have them repeat 9 times and then shuffle the bunch. But there you run into the same problem I think?
I am an absolute Matlab beginner, so any guidance will be welcome.
The following uses modulo operations to make sure each value is different from the previous one:
m = 20; %// number of categories
n = 180; %// desired number of samples
x = [randi(m)-1 randi(m-1, [1 n-1])];
x = mod(cumsum(x), m) + 1;
How the code works
In the third line, the first entry of x is a random value between 0 and m-1. Each subsequent entry represents the change that, modulo m, will give the next value (this is done in the fourth line).
The key is to choose that change between 1 and m-1 (not between 0 and m-1), to assure consecutive values will be different. In other words, given a value, there are m-1 (not m) choices for the next value.
After the modulo operation, 1 is added to to transform the range of resulting values from 0,...,m-1 to 1,...,m.
Test
Take all (n-1) pairs of consecutive entries in the generated x vector and count occurrences of all (m^2) possible combinations of values:
count = accumarray([x(1:end-1); x(2:end)].', 1, [m m]);
imagesc(count)
axis square
colorbar
The following image has been obtained for m=20; n=1e6;. It is seen that all combinations are (more or less) equally likely, except for pairs with repeated values, which never occur.
You could look for the repetitions in an iterative manner and put new set of integers from the same group [1 20] only into those places where repetitions have occurred. We continue to do so until there are no repetitions left -
interval = [1 20]; %// interval from where the random integers are to be chosen
r = randi(interval,1,180); %// create the first batch of numbers
idx = diff(r)==0; %// logical array, where 1s denote repetitions for first batch
while nnz(idx)~=0
idx = diff(r)==0; %// logical array, where 1s denote repetitions for
%// subsequent batches
rN = randi(interval,1,nnz(idx)); %// new set of random integers to be placed
%// at the positions where repetitions have occured
r(find(idx)+1) = rN; %// place ramdom integers at their respective positions
end
I'm building a program that plays Connect 4, and one of the things to check for is cases where your opponent has the following board positions:
[0,1,1,0,0] or [0,1,0,1,0] or [0,0,1,1,0]
where your opponent is one move away from having three pieces in a row with a blank on either side. If you don't fill one of the middle elements on your next move, your opponent can go there and force a checkmate.
What I have is a board of 42 squares, numbered 1:42. And I created a matrix called FiveCheck, where each row maps to five consecutive board positions. For example:
FiveCheck(34,:) = [board(7),board(14),board(21),board(28),board(35)];
FiveCheck(35,:) = [board(14),board(21),board(28),board(35),board(42)];
are two of the diagonals of the board.
I can test for the possible checkmate with
(sum(FiveCheck(:,2:4),2) == 2 + sum(FiveCheck,2) == 2) == 2
And that gives me a vector with 1's indicating that the corresponding FiveCheck row has a possible checkmate. Let's say the 34th element of that vector has a 1, and the pattern for that diagonal (from the example given above) is [0,0,1,1,0]. How do I return 14, the board position I should move to?
Another separate example, if the 35th element of that vector has a 1, and the pattern for that diagonal is [0,1,0,1,0], how do I return 28?
EDIT: I just realized this is impossible without some sort of a map. So I created FiveMap, a matrix the same size of FiveCheck, with the same formulas except the word "board" is removed. For example:
FiveMap(34,:) = [(7),(14),(21),(28),(35)];
FiveMap(35,:) = [(14),(21),(28),(35),(42)];
Since you are dealing with binary vectors of size 5, a very efficient solution might be the use of a look up table.
Consider board to be a binary matrix. you can filter it with 4 filters (of length 5), representing horizontal, vertical and two diagonals to identify possible positions you are looking for. Then, for specious locations, you can extract the 5 binary bits and use a look up table of size 32 to get the offset to the position where you should place your piece.
a small example:
% construct LUT
LUT = zeros(32,2); % dx and dy offsets for each entry
LUT(12,:) = [ 1 0 ]; % covering the case [0 1 1 0 0] - put piece 1 to the right of center
% continue constructing LUT here...
horFilt = ones(1, 5);
resp = imfilter( board, horFilt ); % need to think about board''s boundaries here...
[yy xx] = find( resp == 2 ); all locations where filter caught 2 out of 5
pat = board( yy, xx + [ -2 1 0 1 2] ); % I assume here only one location was found
pat = bin2dec( '0'+char( pat ) ); % convert binary pattern to decimal entry
board( yy + LUT(pat,2) , xx + LUT(pat, 1) ) = ... ; % your move here...
Okay, this might seem like a weird question, but bear with me.
So I have a random vector in a .m file, with certain constraints built into it. Here is my code:
randvecall = randsample(done, done, true);
randvec = randvecall([1;diff(randvecall(:))]~=0);
"Done" is just the range of values we take the sample from, so don't worry about that. As you can see, this randsamples from a range of values, and then prunes this random vector with the diff function, so that consecutive duplicate values are removed. There is still the potential for duplicate values in the vector, but they simply cannot be consecutive.
This is all well and good, and works perfectly fine.
So, say, randvec looks like this:
randvec =
54
47
52
26
39
2
14
51
24
6
19
56
34
46
12
7
41
18
29
7
It is actually a lot longer, with something like 60-70 values, but you get the point.
What I want to do is add a little extra constraint on to this vector. When I sample from this vector, the values are classified according to their range. So values from 1-15 are category 1, 16-30 are category 2, and so on. The reasons for this are unimportant, but it is a pretty important part of the program. So if you look at the values I provided above, you see a section like this:
7
41
18
29
7
This is actually bad for my program. Because the value ranges are treated separately, 41, 18, and 29 are used differently than 7 is. So, for all intents and purposes, 7 is appearing consecutively in my script. What I want to do is somehow parse/modify/whatever the vector when it is generated so that the same number from a certain range cannot appear twice "in a row," regardless of how many other numbers from different ranges are between them. Does this make sense/did I describe this well? So, I want MATLAB to search the vector, and for all values within certain ranges (1-15,16-30,31-45,46-60) make sure that "consecutive" values from the same range are not identical.
So, then, that is what I want to do. This may not by any means be the best way to do this, so any advice/alternatives are, of course, appreciated. I know I can do this better with multiple vectors, but for various reasons I need this to be a single, long vector (the way my script is designed it just wouldn't work if I had a separate vector for each range of values).
What you may want to do is create four random vectors, one for each category, ensure that they do not contain any two consecutive equal values, and then build your final random vector by ordered picking of values from random categories, i.e.
%# make a 50-by-nCategories array of random numbers
categories = [1,16,31,46;15,30,45,60]; %# category min/max
nCategories = size(categories,2);
randomCategories = zeros(50,nCategories);
for c=1:nCategories
%# draw 100 numbers for good measure
tmp = randi(categories(:,c),[100 1]);
tmp(diff(tmp==0)) = []; %# remove consecutive duplicates
%# store
randomCategories(:,c) = tmp(1:50);
end
%# select from which bins to pick. Use half the numbers, so that we don't force the
%# numbers of entries per category to be exactly equal
bins = randi(nCategories,[100,1]);
%# combine the output, i.e. replace e.g. the numbers
%# '3' in 'bins' with the consecutive entries
%# from the third category
out = zeros(100,1);
for c = 1:nCategories
cIdx = find(bins==c);
out(cIdx) = randomCategories(1:length(cIdx),c);
end
First we assign each element the bin number of the range it lies into:
[~,bins] = histc(randvec, [1 16 31 46 61]);
Next we loop for each range, and find elements in those categories. For example for the first range of 1-16, we get:
>> ind = find(bins==1); %# bin#1 of 1-16
>> x = randvec(ind)
ans =
2
14
6
12
7
7
now you can apply the same process of removing consecutive duplicates:
>> idx = ([1;diff(x)] == 0)
idx =
0
0
0
0
0
1
>> problematicIndices = ind(idx) %# indices into the vector: randvec
Do this for all ranges, and collect those problematic indices. Next decide how you want to deal with them (remove them, generate other numbers in their place, etc...)
If I understand your problem correct, I think that is one solution. It uses unique, but applies it to each of the subranges of the vector. The values that are duplicated within a range of indices are identified so you can deal with them.
cat_inds = [1,16,31,46,60]; % need to include last element
for i=2:numel(cat_inds)
randvec_part = randvec( cat_inds(i-1):cat_inds(i) );
% Find the indices for the first unique elements in this part of the array
[~,uniqInds] = unique(randvec_part,'first');
% this binary vector identifies the indices that are duplicated in
% this part of randvec
%
% NB: they are indices into randvec_part
%
inds_of_duplicates = ~ismember(1:numel(randvec_part), uniqInds);
% code to deal with the problem indices goes here. Modify randvec_part accordingly...
% Write it back to the original vector (assumes that the length is the same)
randvec( cat_inds(i-1):cat_inds(i) ) = randvec_part;
end
Here's a different approach than what everyone else has been tossing up. The premise that I'm working on here is that you want to have a random arrangement of values in a vector without repitition. I'm not sure what other constraints you are applying prior to the point where we are giving out input.
My thoughts is to use the randperm function.
Here's some sample code how it would work:
%randvec is your vector of random values
randvec2 = unique(randvec); % This will return the sorted list of values from randvec.
randomizedvector = randvec2(randperm(length(randvec2));
% Note: if randvec is multidimensional you'll have to use numel instead of length
At this point randomizedvector should contain all the unique values from the initial randvec and but 'shuffled' or re-randomized after the unique function call. Now you could just seed the randvec differently to avoid needing the unique function call as simply calling randperm(n) will returning a randomized vector with values ranging from 1 to n.
Just an off the wall 2 cents there =P enjoy!