The following piece of code is supposed to multiply a matrix by a vector. The co
ID: 3814920 • Letter: T
Question
The following piece of code is supposed to multiply a matrix by a vector. The code has several serious logical errors however. Clearly identify the errors and write the correct code. function mat_vect_mult % nra = input ('Enter the number of rows of the matrix: '); nca = input ('Enter the number of columns of the matrix: ') nentries_vect = input ('Enter the number of entries of the vector: '); A=rand (nra, nca); vect = rand (nentries_vect); if (nra ~= nentries_vect) disp ('Error - Multiplication cannot be performed'); else result=zeros (nra); for ii=1: nra mult (kk)=0.0; for jj = kk:nentries_a result(jj) = result(jj) + A(ii, jj)*vect(jj); end end disp (result) endExplanation / Answer
function mat_vect_mult
nra = input('Enter the number of rows of the matrix: ');
nca = input('Enter the number of columns of the matrix: ');
nentries_vect = input('Enter the number of entries of the vector: ');
A = rand(nra, nca); %Creates a random array of size nra x nca.
vect = rand(1, nentries_vect); %Creates a random vector of size nentries_vect.
if nca ~= 1 %If number of columns of matrix not equals number of rows of vector, i.e., 1.
disp('Error - Multiplication cannot be performed.');
else
result = zeros(nra, nentries_vect);
for ii = 1 : nra
for jj = 1 : nentries_vect
result(ii, jj) = 0.0;
for kk = 1 : nca
result(ii) = result(ii, jj) + A(ii, kk) * vect(kk, jj);
end
end
end
disp(vect);
disp(A);
disp(result);
end
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.