# matrix addition different dimension using for loops.

조회 수: 3 (최근 30일)
Malini Bakthavatchalam 2020년 8월 15일
댓글: Walter Roberson 2020년 8월 16일
Hi,
I am trying to do matrix addition of 2*4 to fit in 4*4 matrix. I am using for loops to get me familiarize with loops so that i can use it for image matrix manupulation. But with my code my output is 2*4 instead of 4*4.. could someone explain me the concept or the logic i am lacking here ..
a = [11:14; 15:18];
b = [3 2 3 1; 2 1 1 1;1 3 3 2; 2 1 1 3];
for i = 0
for j = 0
for x = 1:2
for y = 1:4
c(i+x,j+y) =b(i+x,j+y)+a(x+i,y+j);
end
end
end
end
##### 댓글 수: 2없음 표시없음 숨기기
Walter Roberson 2020년 8월 16일
If the first matrix were
1 2 3 4
5 6 7 8
and the second matrix was all zero, then what would you want the result of the addition to be ?
Malini Bakthavatchalam 2020년 8월 16일
1 2 3 4
5 6 7 8
1 2 3 4
5 6 7 8
This would be my resultant matrix

댓글을 달려면 로그인하십시오.

### 채택된 답변

Walter Roberson 2020년 8월 16일
%this code will fail if a or b is empty, or if one size is not an exact multiple of the other
asz = size(a);
bsz = size(b);
maxsz = max(asz,bsz);
arep = maxsz ./ asz;
brep = maxsz ./ bsz;
ar = repmat(a, arep);
br = repmat(b, brep);
c = ar + br;
That is, create new matrices that contain the old matrices copied as many times as needed.
##### 댓글 수: 3이전 댓글 1개 표시이전 댓글 1개 숨기기
Walter Roberson 2020년 8월 16일
편집: Walter Roberson 2020년 8월 16일
ar = repmat(a, arep);
can be replaced with
[arows, acols, apanes] = size(a);
ar = zeros(arows*arep(1), acols*arep(2), apanes, class(a));
for J = 1 : arep(1)
arows = (J-1)*arows+1 : J*arows;
for K = 1 : arep(2)
acols = (K-1)*acols+1 : K*acols;
ar(arows, acols, :) = a;
end
end
Walter Roberson 2020년 8월 16일
I fixed a typing mistake in setting the class of ar

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by