Error using * Matrix dimensions must agree.

when I run my code I get an error message but If i change fac with 5 for example everything runs as expected. Any idea of what can cause this?
fac is a scalar with holds the value of the element in row j column i divided by piv
Error using *
Incorrect dimensions for matrix
multiplication. Check that the
number of columns in the first
matrix matches the number of
rows in the second matrix. To
perform elementwise
multiplication, use '.*'.
Error in LU_CALC (line 15)
A(j,:)=A(j,:)-fac*A(i,:);
function [L_Matrix,U_Matrix] = LU_CALC(A)
%LU_CALC Summary of this function goes here
% Detailed explanation goes here
m = size(A,1);
L_Matrix = eye(m);
for i=1:m
for j=i+1:m
piv=A(i:i);
if piv==0
disp("Error!");
break;
end
fac=A(j:i)./piv;
A(j,:)=A(j,:)-fac*A(i,:);
end
end
U_Matrix = A;
end

답변 (1개)

James Tursa
James Tursa 2020년 3월 31일
편집: James Tursa 2020년 3월 31일

0 개 추천

Change this
piv=A(i:i);
to this
piv=A(i,i);
And change this
fac=A(j:i)./piv;
to this
fac=A(j,i)./piv;

댓글 수: 3

Ahmad Agbaria
Ahmad Agbaria 2020년 3월 31일
worked, coud you kindly explain why?
As I read matlab treats scalars as 1 by 1 matix, so what was the problem here?
James Tursa
James Tursa 2020년 3월 31일
편집: James Tursa 2020년 3월 31일
A(i,j) is the (i,j)'th element of A
A(i:j) is a subset of A using linear indexing into A based on the i:j indexing. This is completely different from A(i,j)
Let's consider a 3x2 matrix just for example. So A is 3x2.
A(1,1) is the A11 element
A(1:1) is also (concidently) the A11 element because the indexing 1:1 produces the scalar index 1
A(2,1) is the A21 element
A(2:1) is an empty matrix. The indexing 2:1 means a vector starting at 2, increasing by 1, and ending at 1. Since 2 is greater than 1, the vector 2:1 is actually empty, and when using an empty vector for indexing into A you get an empty result.
E.g., A(2,3) is the A23 element, but A(2:3) is a vector containing the 2nd and 3rd elements of A which happen to be A21 and A31, not at all what you wanted.
Ahmad Agbaria
Ahmad Agbaria 2020년 3월 31일
Thanks!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

질문:

2020년 3월 31일

댓글:

2020년 3월 31일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by