필터 지우기
필터 지우기

Trying to write a code for solving a system of linear equations using Jacobi method, getting this error "In an assignment A(:) = B, the number of elements in A and B must be the same."

조회 수: 1 (최근 30일)
I think it must be something with my preallocation or perhaps the way I have my index set up? In order to comply with homework requirements I can only use one for loop.
clc; close all; clear;
load('set1_HW3');
load('set2_HW3');
A=diag(1./diag(A1_HW3));
A1=diag(diag(A1_HW3));
tol=10^-4;
x=zeros(size(A1_HW3,1),1);
for k=1:100
x(k+1)=A*b1_HW3-A*(A1_HW3-A1)*x(k);
if abs((x(k+1)-x(k))/x(k))<tol
break
end

답변 (1개)

Walter Roberson
Walter Roberson 2018년 2월 15일
We can see from your line
x=zeros(size(A1_HW3,1),1);
that size(A1_HW3,1) is not expected to be 1 -- that A1_HW3 is expected to have multiple rows.
You have A=diag(1./diag(A1_HW3)) . If A1_HW3 were a scalar at that point then A would end up being a scalar, but we have reason to believe that A1_HW3 is an array at that point, in which case A is going to end up being a square array.
You have
x(k+1) = A*b1_HW3-A*(A1_HW3-A1)*x(k)
we do not know how big b1_HW3 is at that point, but we can see that you are using the * algebraic matrix multiplication operator between A and b1_HW3 . If b1_HW3 is a scalar then the result of the * would be a matrix with the same size as A -- and since we know that A has multiple rows, we know that result cannot fit within the single location x(k+1) . If b1_HW3 is an array then with the * operator the size of the result will be size(A,1) by size(b1_HW3,2) -- and we know that size(A,1) is more than one so no matter what size(B1_HW3,2) is, we can see that the result of the * is going to have multiple rows and so is not going to fit within the single location x(k+1)
  댓글 수: 4
Abigail Grein
Abigail Grein 2018년 2월 15일
I made x 100x100 and got the same error code. It must be something with my index then? Something to do with the program not knowing that x(1)=zeroes?
Walter Roberson
Walter Roberson 2018년 2월 15일
maxk = 100;
x = zeros(size(A1_HW3,1),maxk);
for k = 1:maxk
x(:,k+1)=A*b1_HW3-A*(A1_HW3-A1)*x(:,k);
if all( abs((x(:,k+1)-x(:,k))./x(:,k)) < tol )
break
end
end
x(:,k+1:end) = []; %remove unusued

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by