Effacer les filtres
Effacer les filtres

Translate a matrix with nested loops?

1 vue (au cours des 30 derniers jours)
Colin Starker
Colin Starker le 18 Mar 2017
Réponse apportée : dpb le 18 Mar 2017
I need to translate a matrix up and to the right with nested loops.
The code should be able to take any matrix A...
A=
[1 2 3 4 5;
6 7 8 9 10;
11 12 13 14 15;
16 17 18 19 20]
...and translate it by user inputs X and Y (2 and 2, in this example) to produce matrix B...
B=
[0 0 11 12 13;
0 0 16 17 18;
0 0 0 0 0;
0 0 0 0 0]

Réponse acceptée

Roger Stafford
Roger Stafford le 18 Mar 2017
No need for loops:
up = 2; right = 2;
B = zeros(size(A));
B(1:end-up,1+right:end) = A(1+up:end,1:end-right);

Plus de réponses (1)

dpb
dpb le 18 Mar 2017
Alternate
B=circshift(A,[up right]);
B(:,1:right)=0; B(end-up+1:end,:)=0;
I've always thought there should be a companion to cirshift that shifts in a constant or by default zero...think I've made the enhancement request a time or two, even.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by