How can I shift and repeat an element within a matrix?

7 views (last 30 days)
Hi all, Please, what's a neat way to build a matrix like this:
0 0 1 0 0 0;
0 1 0 0 0 0;
1 0 0 0 0 0;
0 1 0 0 0 0;
0 0 1 0 0 0;
0 0 0 1 0 0;
I want to make a larger matrix with a similar pattern, where the 1's change direction once they hit the left column.
Thanks! Mike.

Accepted Answer

Adam
Adam on 16 Nov 2015
Edited: Adam on 16 Nov 2015
idx = 3;
n = 6;
res = zeros(n);
turnIdx = n * ( idx - 1 ) + 1; % 1 element after the end of the idx-1 row
res( idx:(n-1):turnIdx ) = 1;
res( turnIdx:(n+1):end ) = 1;
res = res.';
should do the job if your problem is not actually more complex than what you describe (e.g. arrays taller than wide where you expect it to turn again on hitting the right edge.
idx is the index of the 1 on the first row, n is the size of one dimension of the square matrix.
  3 Comments
Adam
Adam on 16 Nov 2015
Edited: Adam on 16 Nov 2015
Ah, sorry - I corrected it now.
I used 'i' as the variable in my testing in Matlab but switched to the more verbose 'idx' when I moved the code here, but I missed correcting one of them originally so it would either throw an error or try to interpret the i as an imaginary number!
(A good example of why I should never start changing solutions in here after testing them in Matlab!)
Mike
Mike on 16 Nov 2015
Thanks Adam! I just tried it again and it works! You are right, it should do the job since I intend to use it just for square matrices. Much appreciated!!!

Sign in to comment.

More Answers (1)

Guillaume
Guillaume on 16 Nov 2015
Another option is to use eye:
idx = 3;
n = 6;
res = [zeros(idx-1, 1), fliplr(eye(idx-1)), zeros(idx-1, n-idx); eye(n-idx+1, n)]

Categories

Find more on Resizing and Reshaping 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!