Multiplying 2 Matrices A and B from Scratch (not built in function

How can i write a matlab function which accepts two Matrices A and B and from scratch(indexing - not built in functions) multiplies them together. in the case that they can not be multiplied together simply return an empty matrix ([])

댓글 수: 1

Obviously homework...show your work to date and where, specifically, you got stuck on a Matlab-related question.
Of course, you start with the definition of what matrix multiplication is...

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

답변 (2개)

Manvi Goel
Manvi Goel 2019년 6월 17일
Here you go
function result = mult(a, b)
[r1, c1] = size(a);
[r2, c2] = size(b);
if( c1 == r2)
result = zeros(r1, c2);
for i = 1: r1
for j =1:c2
for k = 1:r2
result(i,j) = result(i,j) + a(i,k) * b(k,j);
end
end
end
else
result = [];
end
disp(result)
end

댓글 수: 3

Providing a complete solution to a homework problem is totally not recommended in this forum.
@madhan buzzkill
It's okay in this case, because the provided code is incorrect.

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

Aniket
Aniket 2026년 8월 8일 4:30
function C = matrixMultiply(A, B)
n = size(A,1);
C=zeros(n,n);
for i=1:n
for j=1:n
sum=0;
for k=1:n
sum=sum+A(i,k)*B(k,j);
end
C(i,j)=sum;
end
end
end

댓글 수: 3

I find this to be the simplest way to solve this problem.
C=zeros(n,n);
That code is incorrect. Multiplying an n x m matrix by an m x p matrix should generate an n x p matrix.
Let's test.
A = [1 2; 3 4]; B = [2 3 4; 5 6 7]; C = [8; 9];
A*B
ans = 2×3
12 15 18 26 33 40
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
matrixMultiply(A,B)
ans = 2×2
12 15 26 33
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
A*C
ans = 2×1
26 60
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
matrixMultiply(A,C)
Index in position 2 exceeds array bounds. Index must not exceed 1.

Error in solution>matrixMultiply (line 15)
sum=sum+A(i,k)*B(k,j);
function C = matrixMultiply(A, B)
n = size(A,1);
C=zeros(n,n);
for i=1:n
for j=1:n
sum=0;
for k=1:n
sum=sum+A(i,k)*B(k,j);
end
C(i,j)=sum;
end
end
end

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

카테고리

질문:

2019년 6월 16일

댓글:

2026년 8월 8일 8:58

Community Treasure Hunt

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

Start Hunting!

Translated by