MATLAB Answers

Matrix from an array

2 views (last 30 days)
Let say A=1:15 is an array. How to obtain a matrix such that
B = [1 2 3 4 5 6; 4 5 6 7 8 9; 7 8 9 10 11 12; 10 11 12 13 14 15] ; %last n=3 elements of previous row repeats

  1 Comment

Ankit
Ankit on 26 Sep 2019
You need to create a loop in case you want to do it repeated number of times
A=1:15;
B = [A(1:6);A(4:9);A(7:12);A(10:15)];

Sign in to comment.

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 26 Sep 2019
Edited: Andrei Bobrov on 26 Sep 2019
A=1:15;
n = 6;
k = 3;
m = numel(A);
B = A((1:k:m - n + 1)' + (0:n-1));
% for old MATLAB < R2016a
B = A(bsxfun(@plus,(1:k:m - n + 1)', (0:n-1)));

  1 Comment

brijesh soni
brijesh soni on 26 Sep 2019
Many thanks !

Sign in to comment.

More Answers (1)

Bob Nbob
Bob Nbob on 26 Sep 2019
Not sure how to do it without a loop or just defining the indices, but here's something simple.
A = 1:15;
for i = 1:length(A)/3-1
B(i,:) = A((i-1)*3:(i+1)*3);
end

  0 Comments

Sign in to comment.

Sign in to answer this question.