Create a matrix of this type?

Hello,
I want to make a matrix this type
1 0 0 0 0 0
2 0 0 0 0 0
3 4 0 0 0 0
5 6 0 0 0 0
7 8 9 0 0 0
10 11 12 0 0 0
13 14 15 16 0 0
17 18 19 20 0 0
% Alternate rows have same number of element
%Each element of the matrix is 1 larger than previous one
How to achieve it ?

 Accepted Answer

m = 8;
n = 6;
P = kron(triu(ones(n,m/2)),[1,1]);
P(P>0) = 1:nnz(P);
out = P';

3 Comments

P K
P K on 20 Jan 2019
Edited: P K on 20 Jan 2019
Thanks.@Andrei Bobrov. I had to create one more matrix. It would be like
A=[1 0 0 0 0 0;0 2 0 0 0 0;3 0 4 0 0 0;0 5 0 6 0 0;7 0 8 0 9 0;0 10 0 11 0 12];
I can do it with 'for loop'. But can you show some efficient way as you had done in the earlier case.
Thanks in advance.
Andrei Bobrov
Andrei Bobrov on 21 Jan 2019
Edited: Andrei Bobrov on 21 Jan 2019
m = 6;
n = 6;
lo = triu(~rem((1:n)' + (1:m),2));
out = int64(lo);
out(lo) = 1:nnz(lo);
out = out';
with kron
m = 6;
n = 6;
out = triu(kron(ones(ceil(n/2),ceil(m/2)),[1,0;0,1]));
out = out(1:n,1:m);
out(out~=0) = 1:nnz(out);
out = out';
Sir Andrei Bobrov, it took me "SO LONG" to do it and you have posted two ways to achieve it. Thank you.

Sign in to comment.

More Answers (1)

madhan ravi
madhan ravi on 20 Jan 2019
Edited: madhan ravi on 20 Jan 2019
n=6; % number of elements in a row
B=mat2cell((1:20).',repelem(1:4,2));
B=cellfun( @transpose,B,'un',0);
R=cellfun( @(x) [x zeros(1,6-numel(x))],B,'un',0);
vertcat(R{:})

1 Comment

Thanks Madhan ravi. It works.Andrei Bobrov answer is more general.

Sign in to comment.

Categories

Asked:

P K
on 19 Jan 2019

Commented:

P K
on 21 Jan 2019

Community Treasure Hunt

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

Start Hunting!