Mathematics 726

Example for the matrix times vector product:


function y = matvect(A,x);
% This is a MatLab function to compute product of a matrix A
% and a vector x.  
% By Ralph Howard on 1/15/98
% Call syntax: y = matvect(a,b) or matvect(a,b)
% Input: The matrix A and the vector x
% Output: The product Ax
m=size(A,1);			% m = number of rows of A
n=size(A,2);			% n = number of columns of A
c=linspace(0,0,m)';		% column vector of n 0's
for i=1:m			% start the loop for i
	for j=1:n			% start the loop for j
		c(i)=c(i)+A(i,j)*x(j);	% update the i-th entry
	end;				% end j loop
end;					% end i loop
ans = c			% Value of A*v is printed at end of loop


Remarks: -
  1. In my first version of this program I used y rather than c for the variable in the loop. MatLab did not like this as y had been reserved as the name of the function in the first line of the program. The result was that the answer was printed twice rather than just once. Thus if you have trouble with getting more output than you should, one possibility is that a variable reserved for the function name in the first line of the program has been used.
  2. The commands size(A,1) and size(A,2) give the number of rows and columns of a matrix. For more information see getting information about matrices.
  3. In this program the column zero vector of length m was defined by c=linspace(0,0,m)'. There are other ways to define this vector. For example c=zeros(m,1). For more information on this see defining special matrices.
    Home