I want to generate(or count) all possible binary matrix that satisfy certain Condition - matlab

I want to generate(or count) all possible binary matrix that satisfy below Condition.
let A be arbitrary binary matrix 4*4
A= [0 0 1 1]
[0 0 1 1]
[1 1 0 0]
[1 1 0 0]
[sum(row1) sum(r2) sum(r3) sum(r4) sum(column1) sum(c2) sum(c3) sum(c4)]
condition: [2 2 2 2 2 2 2 2]
1)how many matrix satisfy above condition?
2)how can i generate them?
answer 1 is:90
but i want a formula or algorithm ,
because i want to use it for 1024*1024 or upper and every arbitrary condition vector.

Brute-force approach: generate all 4x4 binary matrices and test which of them fulfill your condition:
condition = [2 2 2 2 2 2 2 2]; %// desired conditions
matrices = reshape(dec2bin(0:2^16-1,16).'-'0', 4,4,[]); %'// all binary matrices
ind = all(bsxfun(#eq, [squeeze(sum(matrices,1)); squeeze(sum(matrices,2))],...
condition(:))); %// gives 1 for matrices that fulfill the condition, or else 0
result = matrices(:,:,ind); %// pick solution matrices
number = size(result,3); %// number of solution matrices
The solution matrices are result(.,:,1), result(.,:,2), ...; and number is the number of solution matrices.
You could speed this a little exploiting symmetries.

Related

Finding whether the rows of a matrix in Matlab "fall" within the rows of another matrix

I have a matrix Ksets in Matlab with size Gx(l*N) and a matrix A with size MxN.
Each row of Ksets can be decomposed into l sub-rows with size 1xN.
Let me explain better with an example.
clear
N=3;
l=4;
G=2;
M=5;
Ksets=[1 2 3 5 6 7 9 10 11 0 0 0;
13 14 15 1 2 3 21 22 23 1 1 1]; %Gx(l*N)
A=[1 2 3;
5 6 7;
21 22 23;
1 2 3;
0 0 0]; %MxN
In the example:
row 1 of Ksets is composed of l sub-rows with size 1xN: [1 2 3], [5 6 7], [9 10 11], [0 0 0];
row 2 of Ksets is composed of l sub-rows with size 1xN: [13 14 15], [1 2 3], [21 22 23], [1 1 1].
I assume that each row of Ksets does not contain equal sub-rows.
I would like your help to construct a matrix Response with size GxM with Response(g,m)=1 if the row A(m,:) is equal to one of the l sub-rows of Ksets(g,:) and zero otherwise.
Continuing the example above
Response= [1 1 0 1 1;
1 0 1 1 0]; %GxM
This code does what I want:
Responsecorrectmy=zeros(G, M);
for x=1:G
for c=1:l
Responsecorrectmy(x,:)=Responsecorrectmy(x,:)+...
ismember(A,Ksets(x,(c-1)*N+1:c*N), 'rows').';
end
end
My code consists of 2 loops which is undesirable because in my real algorithm G,l are big. Do you have suggestions without loops?
It can be done with a little reshaping and dimension-permuting:
Response = permute(any(all(bsxfun(#eq, reshape(Ksets.', N, [], G), permute(A, [2 3 4 1])), 1), 2), [3 4 1 2]);
This works as follows:
reshape(Ksets.', N, [], G) reshapes Ksets into an N×l×G 3D-array so that each subrow is now separated from the others.
bsxfun(#eq, ..., permute(A, [2 3 4 1])) creates an N×l×G×M 4D-array with the result of comparing each element of the 3D-array from step 1 with each value in A.
all(..., 1) tests if all the elements of each subrow (i.e. first dimension) match. any(...,2) tests if this happens for any subrow of one of the original rows (i.e. second dimension).
permute(..., [3 4 1 2]) removes the first two dimensions (which became singleton in step 3), giving the desired G×M result. (It would not be safe to use squeeze for this because it would incorrectly remove the third dimension if G=1).
It's quite hard to do this vectorized, especially if the subsets you're trying to compare to are embedded in each row. What can be done for efficiency is to change the Ksets into a 3D matrix where each slice contains those subsets formatted into a 2D matrix where each subset is on a per-row basis. You can then use ismember combined with using just one loop on each row individually and populate your results.
Ksets2 = permute(reshape(Ksets.', [N l G]), [2 1 3]);
Response = false(G, M);
for i = 1 : G
Response(i, :) = ismember(A, Ksets2(:,:,i), 'rows')';
end
The first statement reshapes your data so that it becomes a 3D matrix, but because of MATLAB's column major processing, and because your subsets are in row major, we have to transpose the data prior to reshaping. However, this results in each column being in a subset, so we have to transpose each slice independently with the permute operation.
Once that's done, we allocate a matrix of the desired size, then loop through each row in Ksets (now transformed into rows of subsets) to produce the desired result.
We get:
>> Response
Response =
2×5 logical array
1 1 0 1 1
1 0 1 1 0

Making Tridiagonal matrix in matlab

I want to make a triadiagonal matrix with matlab, using
full(gallery('tridiag', 10, 1, -4, 6, -4, 1))
and i take that i have too many arguments in the function. Is there another way to do this?
I am trying to make the following matrix:
6 -4 1 0 0
-4 6 -4 1 0
1 -4 6 -4 1
0 1 -4 6 -4
0 0 1 -4 6
Since your matrix is pentadiagonal, I think the best solution is to use spdiags:
>> n = 5;
>> full(spdiags(ones(n,1)*[1,-4,6,-4,1],[-2,-1,0,1,2],n,n));
ans =
6 -4 1 0 0
-4 6 -4 1 0
1 -4 6 -4 1
0 1 -4 6 -4
0 0 1 -4 6
The full is optional and not recommended for large n.
Since there are 5 non-zero diagonals this is not a tridiagonal matrix so you cannot use the tridiag option. You have to manually generate such matrix by means of the diag() function, which allows you to create a matrix with a given diagonal and you can as well select which diagonal you want to write.
You can achieve this therefore by creating 5 different matrices, each of them will have a given non-zero diagonal:
n=5;
B=diag(6*ones(n,1),0)+diag(-4*ones(n-1,1),1)+diag(-4*ones(n-1,1),-1)+diag(1*ones(n-2,1),2)+diag(1*ones(n-2,1),-2);
In this code n=5 is the order of your matrix, then diag(6*ones(n,1),0) will create a vector (length n) with all 6 and such vector will be placed in the 0-th diagonal. Such matrix will have zero elsewhere.
Similarly diag(-4*ones(n-1,1),1) will create a vector (length n-1) with all -4 and such vector will be placed in the 1st superdiagonal. Such matrix will have zero elsewhere and we sum such matrix to the previous one.
And such "chain reaction" goes on until the matrix is fully generated.
Update: I've been looking around the gallery() help and there is indeed an option for a Toeplitz pentadiagonal. You might want to use then
full(gallery('toeppen',5,1,-4,6,-4,1))
I agree that for your huge case a sparse-based solution such as that of Troy Haskin is best. However, it's worth noting that you're precisely constructing a Toeplitz matrix (as Alessiox hinted), and you can use the built-in toeplitz() to do that. All that is needed is to figure out the number of zeros needed for padding the input nonzero elements of the first row and column (this is necessary since toeplitz asserts the size of the matrix to construct from the dimensions of the input vector):
n = 5; %// linear size of result
v = [1,-4,6,-4,1]; %// nonzero diagonal elements symmetrically
mid = ceil(length(v)/2); %// index of diagonal in the input vector
zerosvec = zeros(1,n-mid); %// zeros for padding the rest
colvec = [v(mid:-1:1), zerosvec]; %// first column of the result
rowvec = [v(mid:end), zerosvec]; %// first row of the result
toeplitz(colvec,rowvec) %// toeplitz does the heavy lifting

Repmat function in matlab

I have been through a bunch of questions about the Repeat function in MatLab, but I can't figure out how this process work.
I am trying to translate it into R, but my problem is that I do not know how the function manipulates the data.
The code is part of a process to make a pairs trading strategy, where the code takes in a vector of FALSE/TRUE expressions.
The code is:
% initialize positions array
positions=NaN(length(tday), 2);
% long entries
positions(shorts, :)=repmat([-1 1], [length(find(shorts)) 1]);
where shorts is the vector of TRUE/FALSE expressions.
Hope you can help.
repmat repeats the matrix you give him [dim1 dim2 dim3,...] times. What your code does is:
1.-length(find(shorts)): gets the amount of "trues" in shorts.
e.g:
shorts=[1 0 0 0 1 0]
length(find(shorts))
ans = 2
2.-repmat([-1 1], [length(find(shorts)) 1]); repeats the [-1 1] [length(find(shorts)) 1] times.
continuation of e.g.:
repmat([-1 1], [length(find(shorts)) 1]);
ans=[-1 1
-1 1];
3.- positions(shorts, :)= saves the given matrix in the given indexes. (NOTE!: only works if shorts is of type logical).
continuation of e.g.:
At this point, if you haven't omit anything, positions should be a 6x2 NaN matrix. the indexing will fill the true positions of shorts with the [-1 1] matrix. so after this, positions will be:
positions=[-1 1
NaN NaN
NaN NaN
NaN NaN
-1 1
NaN NaN]
Hope it helps
The MATLAB repmat function replicates and tiles the array. The syntax is
B = repmat(A,n)
where A is the input array and n specifies how to tile the array. If n is a vector [n1,n2] - as in your case - then A is replicated n1 times in rows and n2 times in columns. E.g.
A = [ 1 2 ; 3 4]
B = repmat(A,[2,3])
B = | |
1 2 1 2 1 2
3 4 3 4 3 4 __
1 2 1 2 1 2
3 4 3 4 3 4
(the lines are only to illustrate how A gets tiled)
In your case, repmat replicates the vector [-1, 1] for each non-zero element of shorts. You thus set each row of positions, whos corresponding entry in shorts is not zero, to [-1,1]. All other rows will stay NaN.
For example if
shorts = [1; 0; 1; 1; 0];
then your code will create
positions =
-1 1
NaN NaN
-1 1
-1 1
NaN NaN
I hope this helps you to clarify the effect of repmat. If not, feel free to ask.

matlab indexing with multiple condition

I can't figure out how to create a vector based on condition on more than one other vectors. I have three vectors and I need values of one vector if values on other vectors comply to condition.
As an example below I would like to choose values from vector a if values on vector b==2 and values on vector c==0 obviously I expect [2 4]
a = [1 2 3 4 5 6 7 8 9 10];
b = [1 2 1 2 1 2 1 2 1 2];
c = [0 0 0 0 0 1 1 1 1 1]
I thought something like:
d = a(b==2) & a(c==0)
but I have d = 1 1 1 1 1 not sure why.
It seems to be basic problem but I can find solution for it.
In your case you can consider using a(b==2 & c==0)
Use ismember to find the matching indices along the rows after concatenating b and c and then index to a.
Code
a(ismember([b;c]',[2 0],'rows'))
Output
ans =
2
4
You may use bsxfun too for the same result -
a(all(bsxfun(#eq,[b;c],[2 0]'),1))
Or you may just tweak your method to get the correct result -
a(b==2 & c==0)

Checking values of two vectors against eachother and then using the column location of equal entries to extract colums from a matrix in matlab

I'm doing a curve fitting problem in Matlab and so far I've set up some orthonormal polynomials along a specified range of x-values with x = (0:0.0001:40);
The polynomials themselves are each a manipulation of that x vector and are stored as a row in a matrix. I also have some have data entries in the form of two vectors - one for the data x-coords and one for the actual values. I need a way to use the x-coords of my data points to find the same values in my continuous x-vector and then take the corresponding columns from my polynomial matrix and add them to a new matrix.
EDIT: To be more clear. I have, for example:
x = [0 1 2 3 4 5]
Polynomial =
1 1 1 1 1 1
0 1 2 3 4 5
0 1 4 9 16 25
% Data values:
x-coord = [1 3 4]
values = [5 3 8]
I want to check the x-coord values against 'x' to find the corresponding columns and then pull out those columns from the polynomial matrix to get:
Polynomial =
1 1 1
1 3 4
1 9 16
If your x, Polynomial, and xcoord are the same length you could use logical indexing which is elegant; something along the lines of Polynomial(x==xcoord). But since this doesn't seem to be the case, there's a less fancy solution with a for-loop and find(xcoord(i)==x)