In: Computer Science
4. The product y = Ax of an m × n matrix A times a vector x = (x1, x2, . . . , xn) T can be computed row-wise as y = [A(1,:)*x; A(2,:)*x; ... ;A(m,:)*x]; that is y(1) = A(1,:)*x y(2) = A(2,:)*x ... y(m) = A(m,:)*x Write a function M-file that takes as input a matrix A and a vector x, and as output gives the product y = Ax by row, as defined above (Hint: use a for loop to define each entry of the vector y.) Your M-file should perform a check on the dimensions of the input variables A and x and return a message if the dimensions do not match. Call the file myrowproduct.m. Note that this file will NOT be the same as the myproduct.m example. Test your function on a random 5 × 3 matrix A and a random 3 × 1 vector x. Compare the output with A*x. Repeat with a 3 × 6 matrix and a 6 × 1 vector and with a 3 × 6 matrix and a 1 × 6 vector. Use the command rand to generate the random matrices for testing. Include in your lab report the function M-file and the output obtained by running it.
.m file
function y = myrowproduct(A,x)
y=[];
[r1 c1]=size(A);
[r2 c2]=size(x);
if c1~=r2
disp('dimensions not agree');
return;
else
for i=1:r1
y(i,1)=A(i,:)*x;
end
end
end
command window output:
>> clear all
>> A = [1 2 3;4 5 6]
A =
1 2 3
4 5 6
>> b = [1;2;3]
b =
1
2
3
>> m1 =myrowproduct(A,b)
m1 =
14
32
>> C = [1 2 3 4;4 5 6 7;2 5 4 7]
C =
1 2 3 4
4 5 6 7
2 5 4 7
>> x = [4;2;7;8]
x =
4
2
7
8
>> m1 =myrowproduct(C,x)
m1 =
61
124
102
>> x = x'
x =
4 2 7 8
>> m1 =myrowproduct(C,x)
dimensions not agree
m1 =
[]
>>
Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions. Thank You! ==========================================================================