permutations of a matrix
Show older comments
Hello,
for a linear system equation of Ax = B with A dimensions 5x5 and x, a column vector. Let's say A is a binary matrix of 1's and 0's and i had the cases of having 3 1's and the rest 0's in A, or 5 1's and the rest 0's. How would I calculate the values of B for all combinations of A consisting of 3 or 5 1's?
2 Comments
David Hill
on 23 Aug 2019
% broot-force for 3 1's if I understood you correctly.
x=[1 0 1 0 1]';% any column vector
y=nan(5,1,2300);
z=zeros(5);
count=0;
for i=1:25
z(i)=1;
for j=i+1:25
z(j)=1;
for k=j+1:25
z(k)=1;
count=count+1;
y(:,1,count)=z*x;
z(k)=0;
end
z(j)=0;
end
z(i)=0;
end
Stephen23
on 23 Aug 2019
There are also answers on this forum that discuss how you could generalize that concept, so that it does not use a fixed number of nested for loops:
Accepted Answer
More Answers (1)
Bruno Luong
on 23 Aug 2019
Edited: Bruno Luong
on 23 Aug 2019
x = (1:5)';
n = size(x,1);
m = 5; % size of b
s = 3; % target sum(A(:))
[i,k] = ind2sub([m,n],nchoosek(1:m*n,s));
j = repmat((1:size(i,1))',s,1);
% each column of B is a possible vector of the set
% { b=A*x: A (m x n) binary matrix such that sum(A(:))=s }
B = accumarray([i(:) j], x(k(:)));
1 Comment
Stephen23
on 23 Aug 2019
+1 very neat
Categories
Find more on Get Started with Optimization Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!