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."
2 views (last 30 days)
Show older comments
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
2 Comments
Answers (1)
Walter Roberson
on 15 Feb 2018
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 Comments
Walter Roberson
on 15 Feb 2018
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
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!