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

8 次查看(过去 30 天)
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 个评论
ForHim
ForHim 2021-7-27
It looks like the function circshift, but without circulating the values back around, rather just leaving zeros instead.
Jan
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
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 个评论
Jan
Jan 2021-7-28
I'm going to expand the code by accepting arrays of all sizes and publish it in the FileExchange. The "CropShift" might be a better name.
dpb
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!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by