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 日

0 投票

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 日

0 投票

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 ExchangeLoops 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