How summation of two matrix so that one element of A matrix summed with B matrix and save in M(1,1)?

3 ビュー (過去 30 日間)
Hi every one.
I want to make summation of two A and B matrices so that one element summed with all elements of B matrix and save in M matrix.
for example for two 3*3 A and B matrix,
I wrote some codes for two 2*2 A and B matrices, and they worked,but I couldn't expand them for two N*N A and B matrices. help me?!!
Codes:
clc
clear all
close all
n=4;
m=2;
A=[1 2; 4 5];
B=[3 8; 6 9];
M=ones(n,n);
M1=zeros(m,m);
M2=zeros(m,m);
M3=zeros(m,m);
M4=zeros(m,m);
for i=1:m
for j=1:m
M1(i,j)=A(1,1)+B(i,j);
end
end
for i=1:m
for j=1:m
M2(i,j)=A(1,2)+B(i,j);
end
end
for i=1:m
for j=1:m
M3(i,j)=A(2,1)+B(i,j);
end
end
for i=1:m
for j=1:m
M4(i,j)=A(2,2)+B(i,j);
end
end
for i=1:m
for j=1:m
M(i,j)=M1(i,j);
end
end
for i=1:m
for j=m+1:n
M(i,j)=M2(i,j-m);
end
end
for i=m+1:n
for j=1:m
M(i,j)=M3(i-m,j);
end
end
for i=m+1:n
for j=m+1:n
M(i,j)=M4(i-m,j-m);
end
end

採用された回答

Jan
Jan 2016 年 1 月 1 日
What about:
reshape(bsxfun(@plus, reshape(B, [m,1,m,1]), reshape(A, [1,m,1,m])), n, n)
  2 件のコメント
Habib
Habib 2016 年 1 月 1 日
Mr. Jan Simon,
your codes worked, but I can't understand how it works, can you explain it for me?

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

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2016 年 1 月 1 日
編集済み: Andrei Bobrov 2016 年 1 月 1 日
M = kron(ones(size(A)),B)+kron(A,ones(size(B)));
  2 件のコメント
Habib
Habib 2016 年 1 月 1 日
Hi Abderi Borov,
Thank you for your replying. By M= kron(A,B), we can calculate the product of A and B matrices by way method that I described but I want two summation, not product of them.
what must I do?

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

カテゴリ

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