Write a MATLAB function called zgemm that computes the generalized matrix multip
ID: 2997539 • Letter: W
Question
Write a MATLAB function called zgemm that computes the generalized matrix multiplication alphaAB + betaC using loops, where A, B, and C are matrices and alpha and beta are scalar values. The input order should be (alpha, A, B, beta, C). Check for proper dimensions on each input, report any error and return an empty matrix if they are incorrect. Do not use MATLAB's matrix multiply functions inside this function. Use alpha=0.1, A=[5 7;11 9;0 2], B=[1 2 3 4; 9 8 7 6], C=eye(n,m), beta=0.9 to test zgemm and compare to MATLAB matrix multiply (>>alpha*A*B+beta*C)
Explanation / Answer
% This function computes alpha*A*B+ beta*C without using matlab's inbuilt multiplication.
function mul = zgemm(alpha,A,B,beta,C)
D=multiply(alpha,A);
D=multiply(D,B);
mul=multiply(beta,C);
mul=D+mul;
end
function mul=multiply(A,B)
[m n]=size(A);
[p q]=size(B);
sum=0;
mul=zeros(m,q);
if(m~=1 || n~=1)
if(n~=p) 'Matrix dimensions do not match'
else
for c=1:m
for d=1:q
for k=1:p
sum = sum + A(c,k)*B(k,d);
end
mul(c,d)=sum;
sum=0;
end
end
end
else
for i=1:p
for j=1:q
B(i,j)=A*B(i,j);
end
end
mul=B;
end
end
OUTPUT:
alpha=0.1; A=[5 7;11 9;0 2]; B=[1 2 3 4; 9 8 7 6]; C=eye(3,4); beta=0.9;
>> alpha*A*B+beta*C
ans =
7.7000 6.6000 6.4000 6.2000
9.2000 10.3000 9.6000 9.8000
1.8000 1.6000 2.3000 1.2000
>> zgemm(alpha,A,B,beta,C)
ans =
7.7000 6.6000 6.4000 6.2000
9.2000 10.3000 9.6000 9.8000
1.8000 1.6000 2.3000 1.2000
>>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.