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 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Walter Roberson
am 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 Kommentare
Walter Roberson
am 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
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!