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."

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

Réponses (1)

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 commentaires

I see what you mean, I made a mistake allocating x with only one column. I want my output to be an array showing each iteration of solutions as columns, so it will be multiple columns. I guess I'm not sure how to allocate the correct number of columns because I don't know when the values will converge.
Your loop k goes to at most 100, so if there were never any "break" then the output could end up 100 columns. Use that for pre-allocation. And then when you get an early break, remove the columns that were not used.
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?
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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Linear Algebra dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by