MATLAB Answers

Rengin
0

Creating a matrix having repeating elements

Asked by Rengin
on 4 Sep 2019
Latest activity Commented on by Rengin
on 4 Sep 2019
% Dear users,
% Assume that I have a A matrix having the size of 5x5 and in the end;
% I want to get A=[1 -1 0 0 0; 1 -1 0 0 0; 0 1 -1 0 0; 0 1 -1 0 0; 0 0 1 -1 0]
% What is the easiest way to do it?
% Thanks in advance

  6 Comments

Since I can do it by myself, I am asking obviously something different.
OK here is different and still simple:
A=[1 -1 0 0 0; 1 -1 0 0 0; 0 1 -1 0 0; 0 1 -1 0 0; 0 0 1 -1 0]+0
The point is your question is not well formulated
Thanks but I was still be able to get my answer. It works perfectly fine.

Sign in to comment.

Tags

1 Answer

Answer by Andrei Bobrov
on 4 Sep 2019
Edited by Andrei Bobrov
on 4 Sep 2019
 Accepted Answer

A = kron(eye(5),[1;1])+kron(diag(-ones(4,1),1),[1;1]);
out = A(1:5,:);
or
n = 1:5;
A = repmat([1,-1,0,0,0],5,1);
out = A(mod(repmat(n,5,1) - ceil(n(:)/2),5)*5 + n(:));

  2 Comments

You always impress without a doubt , a +1 from me.
Thank you Madhan!

Sign in to comment.