MATLAB: How to add ones to binary matrix with condition to add them

MATLABmatlab functionmatrix

if i have a four matrix like this
A = [ 1 0 0 1 1 1
0 1 0 1 0 0
1 0 1 0 0 1
0 1 0 0 1 1 ]
AND matrix B represent number of group of one's each row
B = [ 1 3 0
1 1 0
1 1 1
1 2 0 ]
AND matrix C like this
C = [ 0 0 0 0 0 1
0 0 0 0 0 0
0 0 0 0 0 1
0 0 0 0 0 1 ]
If i return the last column in C then i need function to determine if there exists a 1 in last row
if yes then return to the same row in Matrix B and put number of ones equal to the last number nonzero in B
for example
last column in C = [ 1
0
1
1 ]
then there is 1 in the first row >> then go back to first row in matrix B AND find last number nonzero in the first row which is equal to 3
the put in matrix C THE THREE ONE LIKE THIS
D = [ 0 0 0 1 1 1
0 0 0 0 0 0
0 0 0 0 0 1
0 0 0 0 0 1 ]
and the same thing will be happened to last row ,, the final solution will be
D =[ 0 0 0 1 1 1
0 0 0 0 0 0
0 0 0 0 0 1
0 0 0 0 1 1 ]

Best Answer

B = [ 1 3 0
1 1 0
1 1 1
1 2 0 ]
C = [ 0 0 0 0 0 1
0 0 0 0 0 0
0 0 0 0 0 1
0 0 0 0 0 1 ]
n=find(C(:,end));
D=zeros(size(C))
kk=0
for k=1:numel(n)
b=nonzeros(B(n(k),:));
m=b(end)
D(n(k),end-m+1:end)=ones(1,m)
end