Generate ones and zeros based on size of each element in a matrix nxn

3 views (last 30 days)
i have a matrix a= [3 4 6; 0 2 3; 4 5 6] and i want to create a new matrix with ones and zeros like this:
one_zero= [ 1 1 1 0 0 0 0 1 1 1 1 1 1; 1 0 0 1 1 1; 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1]
in order to match the gaps for the one_zero matrix to have nxn columns, i want to fill gaps with 0 ( when for example the sum of first row does not match with the sum of the second row)
How it can be done?

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 26 Mar 2023
Edited: Dyuman Joshi on 26 Mar 2023
The output corresponding to 0 in a (i.e. a(2,1)) is a single 1. If that is the desired output, you will have to replace all the zeros in the matrix with one.
a = [3 4 6; 0 2 3; 4 5 6];
a(a==0)=1;
%sum of each row
m = sum(a,2);
s = size(a);
%preallocating the output matrix
out = zeros(s(1),max(m));
%vector for repetition
vec=rem(1:s(2),2);
for k=1:s(1)
out(k,1:m(k))=repelem(vec,a(k,:));
end
out
out = 3×15
1 1 1 0 0 0 0 1 1 1 1 1 1 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1
  3 Comments
Dyuman Joshi
Dyuman Joshi on 26 Mar 2023
Edited: Dyuman Joshi on 26 Mar 2023
If you have a predefined value for number of columns, you can use it directly.
But note that the value has to be equal to or greater than the max value of sum of rows.
a = [3 4 6; 0 2 3; 4 5 6];
a(a==0)=1;
%sum of each row
m = sum(a,2);
s = size(a);
%let the pre-defined value be 20
pval=20;
%preallocating the output matrix according to pre-defined value
out = zeros(s(1),pval);
%vector for repetition
vec = rem(1:s(2),2);
for k = 1:s(1)
out(k,1:m(k))=repelem(vec,a(k,:));
end
out
out = 3×20
1 1 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Identification 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!