How can I shift and repeat an element within a matrix?
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
0 Kommentare
Akzeptierte Antwort
Adam
am 16 Nov. 2015
Bearbeitet: Adam
am 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 Kommentare
Adam
am 16 Nov. 2015
Bearbeitet: Adam
am 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!)
Weitere Antworten (1)
Guillaume
am 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)]
Siehe auch
Kategorien
Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!