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

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

Thanks Adam.
I just ran your code but Matlab gave me a warning and an error message (Warning: Colon operands must be real scalars. ??? Subscript indices must either be real positive integers or logicals). I'm not sure I'd know what to tweak to get it to work.
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!)
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)

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)]

1 Comment

Thanks Guillaume! Now, I have 2 ways to skin this cat, lol.

Sign in to comment.

Categories

Asked:

on 16 Nov 2015

Commented:

on 16 Nov 2015

Community Treasure Hunt

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

Start Hunting!