繁体   English   中英

下标分配尺寸不匹配

[英]Subscripted assignment dimension mismatch

因此,我尝试在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矩阵。

我无法运行您的代码,因为某些变量尚未初始化,至少是errorX 我认为是由于Xsolution已从以前的运行中使用不同的大小初始化过而导致出现问题。 插入Xsolution=[]可以解决此问题。

除了消除错误,我还有一些建议可以改善您的代码:

  1. 使用“函数”时,上一次运行没有“遗留”变量,从而导致出现类似此处的错误。
  2. 不要使用变量名errori error是一个内置函数,用于引发错误,而i是虚数单位。 两者都可能导致难以调试的错误。
  3. A=-1*ones(n,n);A(eye(size(A))==1)=3;初始化A A=-1*ones(n,n);A(eye(size(A))==1)=3; ,在这种情况下,最好不要使用for循环。 要初始化b您可以简单地编写b(1)=0;b(2:n-1)=1;
  4. 使用预分配

第一次运行代码时, Xsolution(:,idx) = X将创建一个大小为XXsolution

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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