简体   繁体   中英

Subscripted assignment dimension mismatch

So, I'm trying to do the Gauss-Seidel method in Matlab and I found a code that does this but when I apply it to my matrices I get the Subscripted assignment dimension mismatch. error. I will show you my code in order to get a better idea.

%size of the matrix
n = 10;

%my matrices are empty in the beginning because my professor wants to run the algorithm for n = 100
and n = 1000. A's diagonal values are 3 and every other value is -1. b has the constants and the
first and last value will be 2,while every other value will be 1.
A = [];
b = [];

%assign the values to my matrices
for i=1:n
  for j=1:n
     if i == j
         A(i,j) = 3;
     else
         A(i,j) = -1;
   end
 end
end

for i=2:n-1
    b(i) = 1;
end

%here is the Gauss-Seidel algorithm
idx = 0;
while max(error) > 0.5 * 10^(-4)
    idx = idx + 1;
    Z = X;
    for i = 1:n
        j = 1:n; % define an array of the coefficients' elements
        j(i) = [];  % eliminate the unknow's coefficient from the remaining coefficients
        Xtemp = X;  % copy the unknows to a new variable
        Xtemp(i) = [];  % eliminate the unknown under question from the set of values
        X(i) = (b(i) - sum(A(i,j) * Xtemp)) / A(i,i);
    end
    Xsolution(:,idx) = X;
    error  = abs(X - Z);
end

GaussSeidelTable = [1:idx;Xsolution]'
MaTrIx = [A X b]

I get the error for the Xsolution(:,idx) = X; part. I don't know what else to do. The code posted online works though, and the only difference is that the matrices are hardcoded in the m-file and A is a 5x5 matrix while b is a 5x1 matrix.

I am unable to run your code because some variables are not initialised, at least error and X . I assume the Problem is caused because Xsolution is already initialised from a previous run with a different size. Insert a Xsolution=[] to fix this.

Besides removing the error I have some suggestions to improve your code:

  1. Use Functions, there are no "left over" variables from a previous run, causing errors like you got here.
  2. Don't use the variable name error or i . error is a build-in function to throw errors and i is the imaginary unit. Both can cause hard to debug errors.
  3. Initialise A with A=-1*ones(n,n);A(eye(size(A))==1)=3; , it's faster not to use a for loop in this case. To initialise b you can simply write b(1)=0;b(2:n-1)=1;
  4. Use preallocation

the first time you run the code, Xsolution(:,idx) = X will create a Xsolution with the size of X .

the second time you run it, the existing Xsolution does not fit the size of new X.

this is another reason why you always want to allocate the array before using it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM