MATLAB: Anyone can help me with the error using *, inner matrix dimension must agree

inner matrix dimension must agree

I am using Matlab to solve the matrix but I have the error using *, inner matrix dimension must agree in the last line? Can you help me? I know that the number of rows is equal to the number of columns .
A=input('Nhap vao ma tran A=');
B=input('Nhap vao ma tran cot B=');
% Phuong trinh dang Ax=B
N=size(A,1); % 1 la dong, 2 la cot
m=size(A,2);
if N~=m
disp('A khong la ma tran vuong');
end;
if N==m
l=zeros(N);
u=zeros(N);
for i=1:N
l(i,i)=1;
end;
for j=1:N
u(1,j)=A(1,j);
end;
if u(1,1)==0
error('khong the phan tich duoc, nhap lai ma tran khac');
end;
for i=2:N
l(i,1)=A(i,1)/u(1,1);
end;
for i=2:N-1
for j=i:N
sum=0;
for k=1:i-1
sum=sum+l(i,k)*u(k,j);
end;
u(i,j)=A(i,j)-sum;
end;
if u(i,i)==0
error('khong the phan tich duoc, nhap lai ma tran khac');
end;
for j=i+1:N
sum=0;
for k=1:i-1
sum=sum+l(j,k)*u(k,i);
end;
l(j,i)=(A(j,i)-sum)/u(i,i);
end;
end;
sum=0;
for k=1:N-1
sum=sum+l(N,k)*u(k,N);
end;
u(N,N)=A(N,N)-sum;
disp('L='), disp(l); disp('U='), disp(u);
X=inv(u)*inv(l)*B; disp('X='), disp(X);
end;

Best Answer

Your code makes sure that the input A is square. It constructs u and l matrices that are the same size as A. Eventually it does inv(u)*inv(l) which works because inv() of a square matrix is the same size as the matrix and both u and l are the same size. The result of the inv(u)*inv(l) is going to be the same size as the input matrix, A.
But then... it does a matrix multiplication of that calculated result by B. It does that without having verified first that B has the same number of rows that A has. In particular, if the user happened to enter B as a row vector then B will have only one row and the * would likely fail.
Related Question