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

3 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Dyuman Joshi
Dyuman Joshi il 26 Mar 2023
Modificato: Dyuman Joshi il 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 Commenti
Dyuman Joshi
Dyuman Joshi il 26 Mar 2023
Modificato: Dyuman Joshi il 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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Data Type Identification in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by