下标分配尺寸不匹配

时间:2015-01-01 12:55:20

标签: matlab matrix

所以,我试图在Matlab中使用Gauss-Seidel方法,我找到了一个代码,但是当我将它应用到我的矩阵时,我得到了Subscripted assignment dimension mismatch.错误。我会告诉你我的代码,以便更好地了解。

%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]

我收到Xsolution(:,idx) = X;部分的错误。我不知道还能做什么。在线发布的代码虽然有效,唯一的区别是矩阵在m文件中是硬编码的,A是5x5矩阵,而b是5x1矩阵。

2 个答案:

答案 0 :(得分:1)

我无法运行您的代码,因为某些变量未初始化,至少errorX。我认为问题是由于Xsolution已经从之前运行的不同大小初始化而引起的。插入Xsolution=[]来解决此问题。

除了删除错误之外,我还有一些改进代码的建议:

  1. 使用函数,上一次运行中没有“遗留”变量,导致出现错误。
  2. 请勿使用变量名称errorierror是一个内置函数,用于抛出错误,i是虚构单位。两者都可能导致难以调试错误。
  3. 使用A=-1*ones(n,n);A(eye(size(A))==1)=3;初始化A,在这种情况下,不要使用for循环更快。要初始化b,您只需撰写b(1)=0;b(2:n-1)=1;
  4. 即可
  5. 使用预分配

答案 1 :(得分:0)

首次运行代码时,Xsolution(:,idx) = X会创建一个Xsolution,其大小为X

第二次运行时,现有的Xsolution不符合新X的大小。

这是您在使用之前总是想要分配数组的另一个原因。