# How can I translate one matrix into a new one based on given old and new (row, column) indices?

조회 수: 2(최근 30일)
Austin Land 2021년 7월 27일
댓글: dpb 2021년 7월 28일
I would like to take a matrix, Z, and translate the entire matrix based on the original and new location of a single entry in the matrix.
For example, if the desired Z value were at Z(k,w), I would like to translate all of the matrix, relative to that point, to a new location in Z, defined by indicies (i,j). Anything that gets translated out of the bounds of Z disappears and anything new can be filled in as a zero. Take a look at the example code below just to illustrate what I am trying to do.
Z = [1:4; 5:8; 9:12; 13:16];
Z_new = [6 7 8 0; 10 11 12 0; 14 15 16 0; 0 0 0 0];
%In the above example, you can see that Z(3,3) is translated to a new
%position at Z_new(2,2), and all of the points of Z are also moved relative to that
%point. Everything is simply translated up one and to the left one.
%Here is another example
Z_new2 = [0 0 0 0; 0 0 0 0; 0 0 1 2; 0 0 5 6];
%In this case, Z(1,2) is translated with all of its buddies to Z_new2(4,3).
%Everything is translated to the right two and down two.
In both examples, the old indices are (k,w) and the new indices are (i,j).
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Jan 2021년 7월 27일
An abbreviation of the question:
How can the elements shifted by a specified number of rows and columns? Vanishing elements are cropped and empty elements filled by zeros.

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

### 채택된 답변

Jan 2021년 7월 27일
편집: Jan 2021년 7월 27일
Z = [1:4; 5:8; 9:12; 13:16];
MatShift(Z, [-1, -1])
ans = 4×4
6 7 8 0 10 11 12 0 14 15 16 0 0 0 0 0
MatShift(Z, [2, 2])
ans = 4×4
0 0 0 0 0 0 0 0 0 0 1 2 0 0 5 6
function Y = MatShift(Z, Shift)
% Input: Z: Matrix,
% Shift: [row, col], negative values shift to top and left
SZ = size(Z);
li = max(1, 1 + Shift);
lf = min(SZ, SZ + Shift);
ri = max(1, 1 - Shift);
rf = min(SZ, SZ - Shift);
Y = zeros(SZ);
Y(li(1):lf(1), li(2):lf(2)) = Z(ri(1):rf(1), ri(2):rf(2));
end
##### 댓글 수: 5표시숨기기 이전 댓글 수: 4
dpb 2021년 7월 28일
Good idea, Jan...will be useful addition.
One idea if generalizing, what about an optional value to insert in place of zero only?
That kinda' kills the "crop" or "zero" out of the naming convention if incorporated, but otomh I don't have a catchy alternative. I don't recall what my version was called, explicitly, it's been 20+ years...which is, of itself hard to believe has been that long!

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

R2019b

### Community Treasure Hunt

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

Start Hunting!

Translated by