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 Center および File ExchangeLogical についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by