[英]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矩阵。
我无法运行您的代码,因为某些变量尚未初始化,至少是error
和X
我认为是由于Xsolution
已从以前的运行中使用不同的大小初始化过而导致出现问题。 插入Xsolution=[]
可以解决此问题。
除了消除错误,我还有一些建议可以改善您的代码:
error
或i
。 error
是一个内置函数,用于引发错误,而i
是虚数单位。 两者都可能导致难以调试的错误。 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;
第一次运行代码时, Xsolution(:,idx) = X
将创建一个大小为X
的Xsolution
。
第二次运行时,现有的Xsolution
不适合新X的大小。
这是为什么您总是要在使用之前分配数组的另一个原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.