Combining matrices of different sizes at a certain location

8 ビュー (過去 30 日間)
Bryce
Bryce 2014 年 7 月 30 日
コメント済み: Star Strider 2014 年 7 月 30 日
Hello All,
I am having a problem trying to figure out how to combine two matrices of different sizes. I have one matrix that is all zeros and one smaller matrix with random values that I want to input starting at a certain "coordinate". The coordinate will not be the same every and the row and column will both be based off of two variables.
For example, if I have a 20 x 10 matrix of all zeros and I want to superimpose and replace the zeros with a random 5 x 5 matrix starting at [3,3].
The output would look like:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 3 3 8 9 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 3 4 2 5 9 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 3 2 6 2 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 6 8 3 5 4 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 8 4 3 2 5 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
If anyone has an idea on how to fix this I would be greatly appreciative.
  1 件のコメント
Salaheddin Hosseinzadeh
Salaheddin Hosseinzadeh 2014 年 7 月 30 日
Hi Bryce,
Try this
x = zeros(10,20)
y = magic(5)
x(3:7,3:7) = y

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

回答 (2 件)

Star Strider
Star Strider 2014 年 7 月 30 日
編集済み: Star Strider 2014 年 7 月 30 日
This works:
A = zeros(20,10);
B = randi(9,5,5);
A(3:7,3:7) = B
  1 件のコメント
Star Strider
Star Strider 2014 年 7 月 30 日
OK.
Here’s a more robust version (tested successfully):
A = zeros(20,10);
B = randi(9,5,5);
Sr = 3; % Beginning row to insert B
Sc = 3; % Beginning col to insert B
[Ar, Ac] = size(A);
[Br, Bc] = size(B);
Lr = Ar - (Sr + Br - 1); % Check dimension limits
Lc = Ac - (Sc + Bc - 1);
if (Lr < 0) | (Lc < 0)
fprintf(2, 'WARNING! B will not fit in A with current sizes and start indices.\n\n')
break
else
A(Sr:Sr+Br-1, Sc:Sc+Bc-1) = B;
end

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


Bryce
Bryce 2014 年 7 月 30 日
Your answers will definitely work with how I described what I am trying to do, but I failed at being specific enough. I have a matrix already made that has not "random" values in it per say, but the values are arbitrary for the problem I am having. I also will not always start at [3, 3] and there is not defined number of columns and rows for the smaller matrix. So in Star Strider's answer, the last line would be using the variables fRow and fCol and would change to "A(fRow:fRow+#ofRows, fCol:fCol+#ofColumns) = B"
However, I am not sure how to input the size of the smaller matrix as a variable and I am not sure if it will work with the addition of the start of the smaller matrix plus the dimension of that matrix.
Thanks for the very quick response everyone.

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by