How do I make matrix of ones and zeros alternating depending on size and elements of an array?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
In-chan Kim
am 26 Sep. 2019
Beantwortet: Guillaume
am 26 Sep. 2019
I have an array, A, and I want to make a matrix, B, that has the size dependent on A, and has 1s and 0s alternating, depending on the value of elements in A
E.g. A=[1;2;3;4;5]
B should be of size: ((length(A)+1)/2,sum(A)]
In this case B would be a matrix of 3x15
Then the values for B needs to be be thus:
row 1:[ones(A(1)),zeros(A(2)),zeros(A(3)),zeros(A(4)),zeros(A(5))]
row2: [zeros(A(1)),zeros(A(2)),ones(A(3)),zeros(A(4)),zeros(A(5))]
row3: [zeros(A(1)),zeros(A(2)),zeros(A(3)),zeros(A(4)),ones(A(5))]
B should look like:
[1 0 0 0 0 0 0 0 0 0 0 0 0 0 0;
0 0 0 1 1 1 0 0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0 0 0 1 1 1 1 1]
I've been trying to formulate something with a nested for look for each dimension of B, but have not been succesful!
Would really appreciate any help thanks!
0 Kommentare
Akzeptierte Antwort
Fabio Freschi
am 26 Sep. 2019
% initialize
iRow = [];
jCol = [];
% preallocate
B = zeros((length(A)+1)/2,sum(A));
% indices for columns
idx = [0; cumsum(A)]+1;
for i = 1:length(A)
if mod(i,2) ~= 0
iRow = [iRow; repmat((i+1)/2,A(i),1)];
jCol = [jCol; (idx(i):idx(i+1)-1).'];
end
end
B(sub2ind(size(B),iRow,jCol)) = 1;
1 Kommentar
Fabio Freschi
am 26 Sep. 2019
if you want B to be sparse (not a bad idea)
Bsp = sparse(iRow,jCol,1,(length(A)+1)/2,sum(A));
Weitere Antworten (1)
Guillaume
am 26 Sep. 2019
Here's a fairly simple way:
B = zeros((numel(A)+1)/2, sum(A));
for row = 1:2:numel(A)
B(ceil(row/2), :) = repelem([0, 1, 0], [sum(A(1:row-1)), A(row), sum(A(row+1:end))]);
end
0 Kommentare
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!