Multiplying 2 Matrices A and B from Scratch (not built in function
Show older comments
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 Comment
dpb
on 16 Jun 2019
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...
Answers (2)
Manvi Goel
on 17 Jun 2019
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 Comments
madhan ravi
on 17 Jun 2019
Providing a complete solution to a homework problem is totally not recommended in this forum.
Mark
on 8 Oct 2024
@madhan buzzkill
Walter Roberson
on 8 Oct 2024
It's okay in this case, because the provided code is incorrect.
Aniket
on 8 Aug 2026 at 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 Comments
Aniket
on 8 Aug 2026 at 4:31
I find this to be the simplest way to solve this problem.
Walter Roberson
on 8 Aug 2026 at 8:55
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
matrixMultiply(A,B)
A*C
matrixMultiply(A,C)
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
Categories
Find more on Linear Algebra in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!