Write a MATLAB program (script) to multiply two matrices together. Do not use th
ID: 3550116 • Letter: W
Question
Write a MATLAB program (script) to multiply two matrices together. Do not use the MATLAB matrix multiplication function, A*B. Make the program general so that it will work with matrices of any dimension. Check that the inner dimensions of the matrices are the same before performing the multiplication. If the inner dimensions do not match, display an error and stop.
You can use the MATLAB function size() to get the number of rows and columns in the matrices to be multiplied. Use the input() function to get the matrix elements. Matrices will be entered in the form [1 2 3;4 5 6;7 8 9;
Explanation / Answer
function y =inmat(A,B) % This is a program designed to multiply two matrices % together by using the inner product. % % Written by Martha Allen % % Call syntax: inmat(A,B) % Input: an mxp matrix A and an pxn matrix B % Output: the product AB which is an mxn matrix C m= size(A,1); % gets the row size of matrix A p= size(A,2); % gets the column size of matrix A n= size(B,2); % gets the column size of matrix B f= size(B,1); % gets the row size of matrix B if f==p C=zeros(m,n); % initializes the variable C for i=1:m % starts the loop for j=1:n % starts the loop C(i,j)=C(i,j) + A(i,:) * B(:,j); % updates C end % ends loop end % ends loop ans = C % prints the final answer C else error('The dimensions of the matrices must agree.') end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.