필터 지우기
필터 지우기

Addtion of two matrix.

조회 수: 262 (최근 30일)
priyanka
priyanka 2014년 10월 2일
댓글: Vansh 2023년 3월 23일
I am taking inputs from user to enter row n column and adding two matrix. But the output i am getting is of different dimension. please tell me what is the problem in given code.
m = input('Enter number of rows: ');
n = input('Enter number of columns: ');
for i = 1:m
for j = 1:n
str = ['Enter element in row ' num2str(i) ', col ' num2str(j) ': '];
T(i,j) = input(str);
end
end
%a = input('Enter number of rows: ');
%b = input('Enter number of columns: ');
strn = ['Enter elements for matrix S']
for i = 1:m
for j = 1:n
strn = ['Enter element in row ' num2str(i) ', col ' num2str(j) ': '];
S(i,j) = input(strn);
end
end
string= ['Addition is:']
for i=1:m
for j=1:n
C(i,j)=0;
end
end
C(i,j)=0
for i= 1:m
for j=1:n
C(i,j)= T(i,j)+ S(i,j)
end
end
  댓글 수: 1
Vansh
Vansh 2023년 3월 23일
Thanks for sharing!

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

채택된 답변

dpb
dpb 2014년 10월 2일
The problem is the line
C(i,j)=0
after the loop that creates the zero-filled array--when done, the i,j indices are one greater than the loop limit so this sets the element at C(m+1,n+1) to zero. Matlab automagically creates a full array of that size so the end result is always going to be one larger than the inputs in each direction.
Simply remove this line--it's not needed.
I presume you're doing this this way as a pedagogical exercise and realize all of these loops can be eliminated?
Also, I'd suggest adding the semicolon to the following line and then using
C(i,j)= T(i,j)+ S(i,j)
disp(C)
at the end. Perhaps you were simply echoing output to command window for debugging, however.

추가 답변 (2개)

priyanka
priyanka 2014년 10월 2일
Thank you.

Nalini Vishnoi
Nalini Vishnoi 2014년 10월 2일
Since MATLAB allows matrix manipulations directly, you can add 2 matrices A and B of the same size using a single line of code:
C = A + B;
and this should provide you with the desired result.
  댓글 수: 2
MRUTUNJAY
MRUTUNJAY 2022년 10월 17일
NICE STEP
VINEET THAKUR
VINEET THAKUR 2022년 10월 24일
Sometimes in learning we forced to not use build-in functions, so it's a good code.

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

카테고리

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