[英]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.