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.

 채택된 답변

Adam
Adam 2015년 11월 16일
편집: Adam 2015년 11월 16일
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

Mike
Mike 2015년 11월 16일
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 2015년 11월 16일
편집: Adam 2015년 11월 16일
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 2015년 11월 16일
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!!!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2015년 11월 16일
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

Mike
Mike 2015년 11월 16일
Thanks Guillaume! Now, I have 2 ways to skin this cat, lol.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2015년 11월 16일

댓글:

2015년 11월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by