filling a matrix with a loop
Show older comments
Hi community,
I want to create a large matrix 400x400, In this matrix I want it to have the form
A= [1 1 0 1 000000000000000000........;0 1 1 0 1 00000000000000......; 0 0 1 1 0 1 00000000000000000] and so on till it is a 400x400 matrix.
I could not find a way yet to easiliy do this. As doing this manually is way too much work.
Does anyone know how to do this?
Accepted Answer
More Answers (3)
Alex Mcaulley
on 14 May 2019
A = repmat([1 1 0 1 zeros(1,396)],400,1);
A = cell2mat(arrayfun(@(i) circshift(A(i,:),i-1) , 1:size(A,1), 'UniformOutput',false)');
Jos (10584)
on 14 May 2019
% clever indexing trick
A= [1 1 0 1]
N = 10 ; % smaller example! 400 in your case
X = triu(toeplitz(1:N)) ;
X(X > numel(A)) = 0 ;
tf = X > 0 ;
X(tf) = A(X(tf))
Andrei Bobrov
on 15 May 2019
Edited: Andrei Bobrov
on 15 May 2019
0 votes
out = full(spdiags(ones(400,3),[0,1,3],400,400));
Categories
Find more on Creating and Concatenating Matrices 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!