replace part of matrix to another matrix

9 ビュー (過去 30 日間)
mohammed hussein
mohammed hussein 2017 年 11 月 18 日
コメント済み: mohammed hussein 2017 年 11 月 19 日
Hi i have many matrices in same size , i want to add all of them together in one matrix with replace the last quarter of each one to binning of next one until complete the matrix and the rest will be zeros . for example
a =zeros(5,5)
A=[1 2 ;3 4];
B=[5 6;7 8];
C=[9 10;11 12];
D=[13 14;15 16];
the answer
a=
1 2 0 0 0
3 5 6 0 0
0 7 9 10 0
0 0 11 13 14
0 0 0 15 16
thank you very much for helping

採用された回答

Stephen23
Stephen23 2017 年 11 月 18 日
編集済み: Stephen23 2017 年 11 月 18 日
For any size matrices, even combinations of different sizes:
C = {[1,2;3,4],[5,6;7,8],[9,10;11,12],[13,14;15,16]};
num = numel(C);
szr = cellfun('size',C,1);
szc = cellfun('size',C,2);
csr = cumsum([0,szr-1]);
csc = cumsum([0,szc-1]);
M = zeros(1+csr(end),1+csc(end));
for k = 1:num
idr = csr(k)+(1:szr(k));
idc = csc(k)+(1:szc(k));
M(idr,idc) = C{k};
end
Giving:
>> M
M =
1 2 0 0 0
3 5 6 0 0
0 7 9 10 0
0 0 11 13 14
0 0 0 15 16
It works perfectly with any size matrices, e.g.:
C = {[1,2;3,4],[5,6;7,8],[1,2,3;4,5,6;7,8,9],[9,10;11,12],[13,14;15,16]};
gives
M =
1 2 0 0 0 0 0
3 5 6 0 0 0 0
0 7 1 2 3 0 0
0 0 4 5 6 0 0
0 0 7 8 9 10 0
0 0 0 0 11 13 14
0 0 0 0 0 15 16
  1 件のコメント
mohammed hussein
mohammed hussein 2017 年 11 月 19 日
thank you very much for your answer , this is exactly what i want

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

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2017 年 11 月 18 日
A=[1 2 ;3 4];
B=[5 6;7 8];
C=[9 10;11 12];
D=[13 14;15 16];
newvals = {A, B, C, D};
a = zeros(5,5);
for K = 1 : length(newvals)
a(K:K+1, K:K+1) = newvals{K};
end
  1 件のコメント
mohammed hussein
mohammed hussein 2017 年 11 月 19 日
Thank you very much for your answer

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


Andrei Bobrov
Andrei Bobrov 2017 年 11 月 18 日
編集済み: Andrei Bobrov 2017 年 11 月 18 日
In your case (without loop)
k = cat(3,A,B,D,C);
[m,n,q] = size(k);
a = full(gallery('tridiag',q*m/2+1,1,1,1));
ii = ((1:m*n-1) + (0:q-1)'*m*n)';
a(a>0) = k([ii(:);prod([m,n,q])]);
in general case (with for..end loop)
C = {[1,2;3,4],[5,6;7,8],[1,2,3;4,5,6],[9,10;11,12],[13,14;15,16]};
[m,n] = cellfun(@(x)size(x),C(:));
s = sum(m-1) + 1;
a = zeros(s,sum(n-1)+1);
jj = 1;
for ii = 1:numel(m)
id = jj + (0:m(ii)-1)' + s*(0:n(ii)-1);
a(id) = C{ii};
jj = id(end);
end
All for MATLAB >= R2016b
  1 件のコメント
mohammed hussein
mohammed hussein 2017 年 11 月 19 日
Thank you very much for your answer

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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by