Want to Create A Combination of Non-Decreasing Elements with Condition - matlab

I want to create a combination of non-decreasing elements. The combination will be like,
If i=10 and w=5, then the elements of the combination can be any value from 1 to w and the sum will be equal to i.
Possible combinations are like,
1+1+1+1+1+5
1+1+1+1+1+1+4
1+1+1+1+1+1+1+3
1+1+1+1+1+1+1+1+1+1
......
But 1+1+1+7 is not a desired combination because 7 is greater than w
How to get the combinations using MatLab? I need to get the combinations for higher values of i and w like may be i=20 and w=8.
Thank You

You can do it with a recursive function. The following code contains a wrapper function and the recursive function which does the actual work:
function result = partitions(s,M)
%// s: desired sum; M: maximum value
result = partitions_rec(s,1,M,s);
end
function mat = partitions_rec(s,m,M,n)
%// s: desired sum, m: minimum value; M: maximum value; n: number of entries
M = min(M,s);
if s==0
mat = zeros(1,n);
else
mat = [];
for ii = m:M;
aux = partitions_rec(s-ii,ii,M,n-1);
if size(aux,1)
mat = [ mat; ii*ones(size(aux,1),1) aux ];
end
end
end
end
Example:
>> result = partitions(5,3)
ans =
1 1 1 1 1
1 1 1 2 0
1 1 3 0 0
1 2 2 0 0
2 3 0 0 0
A 0 indicates no number. If you want to remove the zeros, you need to put the result in the form of a cell array, where each cell is a vector with nonzero values:
result_cell = arrayfun(#(ii) result(ii, logical(result(ii,:))), 1:size(result,1), 'uniformoutput', 0);
In the example, this would give
>> result_cell{:}
ans =
1 1 1 1 1
ans =
1 1 1 2
ans =
1 1 3
ans =
1 2 2
ans =
2 3

Related

Extract unique elements from each row of a matrix (Matlab)

I would like to apply the function unique to each row of a given matrix, without involving any for loop. Suppose I have the following 4-by-5 matrix
full(A) = [0 1 0 0 1
2 1 0 3 0
1 2 0 0 2
0 3 1 0 0]
where A is the corresponding sparse matrix. As an example using a for loop, I can do
uniq = cell(4,1);
for i = 1:4
uniq{i} = unique(A(i,:));
end
and I would obtain the cell structure uniq given by
uniq{1} = {1}
uniq{2} = {[1 2 3]}
uniq{3} = {[1 2]}
uniq{4} = {[1 3]}
Is there a quicker way to vectorize this and avoid for loops?
I need to apply this to matrices M-by-5 with M large.
Note that I'm not interested in the number of unique elements per row (I know there are around answers for such a problem).
You can use accumarray with a custom function:
A = sparse([0 1 0 0 1; 2 1 0 3 0; 1 2 0 0 2; 0 3 1 0 0]); % data
[ii, ~, vv] = find(A);
uniq = accumarray(ii(:), vv(:), [], #(x){unique(x.')});
This gives:
>> celldisp(uniq)
uniq{1} =
1
uniq{2} =
1 2 3
uniq{3} =
1 2
uniq{4} =
1 3
you can use num2cell(A,2) to convert each row into cell and then cellfun with unique to get cell array of unique values from each row:
% generate large nX5 matrix
n = 5000;
A = randi(5,n,5);
% convert each row into cell
C = num2cell(A,2);
% take unique values from each cell
U = cellfun(#unique,C,'UniformOutput',0);

Fastest way of generating a logical matrix by given row indices of true values?

What is the most efficient way of generating
>> A
A =
0 1 1
1 1 0
1 0 1
0 0 0
with
>> B = [2 3; 1 2; 1 3]
B =
2 3
1 2
1 3
in MATLAB?
E.g., B(1, :), which is [2 3], means that A(2, 1) and A(3, 1) are true.
My attempt still requires one for loop, iterating through B's row. Is there a loop-free or more efficient way of doing this?
This is one way of many, though sub2ind is the dedicated function for that:
%// given row indices
B = [2 3; 1 2; 1 3]
%// size of row index matrix
[n,m] = size(B)
%// size of output matrix
[N,M] = deal( max(B(:)), n)
%// preallocation of output matrix
A = zeros(N,M)
%// get col indices to given row indices
cols = bsxfun(#times, ones(n,m),(1:n).')
%// set values
A( sub2ind([N,M],B,cols) ) = 1
A =
0 1 1
1 1 0
1 0 1
If you want a logical matrix, change the following to lines
A = false(N,M)
A( sub2ind([N,M],B,cols) ) = true
Alternative solution
%// given row indices
B = [2 3; 1 2; 1 3];
%// number if rows
r = 4; %// e.g. = max(B(:))
%// number if cols
c = 3; %// size(B,1)
%// preallocation of output matrix
A = zeros(r,c);
%// set values
A( bsxfun(#plus, B.', 0:r:(r*(c-1))) ) = 1;
Here's a way, using the sparse function:
A = full(sparse(cumsum(ones(size(B))), B, 1));
This gives
A =
0 1 1
1 1 0
1 0 1
If you need a predefined number of rows in the output, say r (in your example r = 4):
A = full(sparse(cumsum(ones(size(B))), B, 1, 4, size(B,1)));
which gives
A =
0 1 1
1 1 0
1 0 1
0 0 0
You can equivalently use the accumarrray function:
A = accumarray([repmat((1:size(B,1)).',size(B,2),1), B(:)], 1);
gives
A =
0 1 1
1 1 0
1 0 1
Or with a predefined number of rows, r = 4,
A = accumarray([repmat((1:size(B,1)).',size(B,2),1), B(:)], 1, [r size(B,1)]);
gives
A =
0 1 1
1 1 0
1 0 1
0 0 0

Replace specific matrix position with array value without using for loop in MATLAB

can I know how can I replace values in specific matrix position without using for loop in MATLAB? I initialize matrix a that I would like to replace its value on specified row and column for each no. This has to be done a few time within num for loop. The num for loop is important here because I would want the update the value in the original code.
The real code is more complicated, I am simplifying the code for this question.
I have the code as follow:
a = zeros(2,10,15);
for num = 1:10
b = [2 2 1 1 2 2 2 1 2 2 2 2 1 2 2];
c = [8.0268 5.5218 2.9893 5.7105 7.5969 7.5825 7.0740 4.6471 ...
6.3481 14.7424 13.5594 10.6562 7.3160 -4.4648 30.6280];
d = [1 1 1 2 1 1 1 1 1 1 3 1 6 1 1];
for no = 1:15
a(b(no),d(no),no) = c(1,no,:)
end
end
A sample output for, say no 13 is as follows:
a(:,:,13) =
Columns 1 through 8
0 0 0 0 0 7.3160 0 0
0 0 0 0 0 0 0 0
Columns 9 through 10
0 0
0 0
Thank you so much for any help I could get.
It can be done using sub2ind, which casts the subs to a linear index.
Following your vague variable names, it would look like this (omitting the useless loop over num):
a = zeros(2,10,15);
b = [2 2 1 1 2 2 2 1 2 2 2 2 1 2 2];
d = [1 1 1 2 1 1 1 1 1 1 3 1 6 1 1];
c = [8.0268 5.5218 2.9893 5.7105 7.5969 7.5825 7.0740 4.6471 ...
6.3481 14.7424 13.5594 10.6562 7.3160 -4.4648 30.6280];
% // we vectorize the loop over no:
no = 1:15;
a(sub2ind(size(a), b, d, no)) = c;
Apart from the sub2ind based approach as suggested in Nras's solution, you can use a "raw version" of sub2ind to reduce a function call if performance is very critical. The related benchmarks comparing sub2ind and it's raw version is listed in another solution. Here's the implementation to solve your case -
no = 1:15
a = zeros(2,10,15);
[m,n,r] = size(a)
a((no-1)*m*n + (d-1)*m + b) = c
Also for pre-allocation, you can use a much faster approach as listed in Undocumented MATLAB blog post on Preallocation performance with -
a(2,10,15) = 0;
The function sub2ind is your friend here:
a = zeros(2,10,15);
x = [2 2 1 1 2 2 2 1 2 2 2 2 1 2 2];
y = [1 1 1 2 1 1 1 1 1 1 3 1 6 1 1];
z = 1:15;
dat = [8.0268 5.5218 2.9893 5.7105 7.5969 7.5825 7.0740 4.6471 ...
6.3481 14.7424 13.5594 10.6562 7.3160 -4.4648 30.6280];
inds = sub2ind(size(a), x, y, z);
a(inds) = dat;
Matlab provides a function 'sub2ind' may do what you expected.
with variable as the same you posted:
idx = sub2ind(size(a),b,d,[1:15]); % return the index of row a column b and page [1:15]
a(idx) = c;

How to traverse two same size matrices and compare them

I have two matrices filled with 0s and 1s
e.g.
A = [ 0 0 1 0,
1 0 1 0 ]
B = [ 1 1 1 1
0 0 0 0 ]
and I'd like to compared the values form the same position against each other and return a 2x2 matrice
R = [ TP(1) FN(3)
FP(2) TN(2) ]
TP = returns the amount of times A has the value 1, and B has the value 1
FN = returns the amount of times A has the value 0, and B has the value 1
FP = returns the amount of times A has the value 1, and B has the value 0
TN = returns the amount of times A has the value 0, and B has the value 0
How do i get each individual number in A and B?
Approach #1: Comparison based using bsxfun -
pA = [1 0 1 0] %// pattern for A
pB = [1 1 0 0] %// pattern for B
%// Find matches for A against pattern-A and pattern-B for B using bsxfun(#eq.
%// Then, perform AND for detecting combined matches
matches = bsxfun(#eq,A(:),pA) & bsxfun(#eq,B(:),pB)
%// Sum up the matches to give us the desired counts
R = reshape(sum(matches),2,[]).'
Output -
R =
1 3
2 2
Approach #2: Finding decimal numbers -
Step-1: Find decimal numbers corresponding to the combined A's and B's
>> dec_nums = histc(bin2dec(num2str([B(:) A(:)],'%1d')),0:3)
dec_nums =
2
2
3
1
Step-2: Re-order the decimal numbers such that they line up as needed in the problem
>> R = reshape(flipud(dec_nums),2,[])'
R =
1 3
2 2
Use logical operators & and ~ applied on the linearized versions of A and B, and then nnz (or sum) to count the true values:
R = [nnz(A(:)&B(:)) nnz(~A(:)&B(:)); nnz(A(:)&~B(:)) nnz(~A(:)&~B(:))];

matlab - creating a single dimensional array from two dimensional parts

hi i have the following situation
h = [0,1,1,1;
0,0,0,0;
1,1,1,1];
i'll check incoming values which can range between 0 and rowsize of h, i.e. in this case 2,. so my options are 0,1,2.
now i want to create a single dimensional array (let's name it j) as follows
whenever the incoming value is 0
j = [0,1,1,1]
next time if the incoming value is 1
then j = [0,1,1,1,0,0,0,0]
and so on... how is it possible to achieve this in matlab? thanks!
Matlab, as you know, indexes from 1 so you will need to add 1 to the index 0,1,2 to get the row identifier for h. So if the input is 'index'
j = h(index+1,:)
Then, for the next index
j = [j h(index+1,:)]
and so on.
Try this (with x as your vector of incoming values):
j = reshape(h(x+1,:).',1,[]);
The above uses x+1 as an index to select copies of the rows, then transposes and reshapes the result into a single row vector. Here's a test:
>> h = [0 1 1 1; 0 0 0 0; 1 1 1 1];
>> x = [0 0 0];
>> j = reshape(h(x+1,:).',1,[])
j =
0 1 1 1 0 1 1 1 0 1 1 1
If the incoming value is x, you could do something like:
g = h.'
j = g(1:(x+1)*size(h,2))