Insert Matrix into Matrix and don't care if some of the numbers fall off the edge

2 ビュー (過去 30 日間)
Andrew Luce
Andrew Luce 2021 年 8 月 12 日
回答済み: the cyclist 2021 年 8 月 12 日
I'm trying to make a little game. I have a 2 part question. How can I insert a matrix in a matrix where I do not care if the some of the inserted matrix falls outside the matrix I am inserting it into. Except, I don't want the center of the inserted matrix to be lost,
Thank you
Andrew
example
A= 1 1 1
1 2 1
1 1 1
B= 0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
B into A at (4,5) (coordinates based on center of A)
Result = 0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 1 1 1
0 0 0 1 2 1
  1 件のコメント
Walter Roberson
Walter Roberson 2021 年 8 月 12 日
What should happen in the case where the center of the inserted matrix would get lost?
I do not see you inserting B into A; I see you inserting A into B ?

サインインしてコメントする。

回答 (1 件)

the cyclist
the cyclist 2021 年 8 月 12 日
Probably not the most efficient, but I believe this does what you want:
% Arrays
A= [1 1 1
1 2 1
1 1 1];
B= [0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
];
% Where to center
ci = 4;
cj = 5;
% Get sizes
[mA, nA] = size(A);
[mB, nB] = size(B);
% Calculate necessary "padding" around B, which will be trimmed later
pad = (mA-1)/2;
% Initialize output as padded size
output = nan(mB+2*pad,nB+2*pad);
% Insert B into padded array
output(pad+1:end-pad,pad+1:end-pad) = B;
% Insert A into padded array, at specified coordinates
output(ci:ci+mA-1,cj:cj+nA-1) = A;
% Remove the padding (and extraneous elements of A)
output = output(pad+1:end-pad,pad+1:end-pad)
output = 4×6
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 1 2 1

カテゴリ

Help Center および File ExchangeConway's Game of Life についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by