在gauss-Seidel迭代中
function Gauss(A, B)
(m, n) = size(A)
z = [convert(Matrix{Float64}, A) convert(Vector{Float64}, B)]
x = zeros(Float64, n)
for i = 1:n - 1
for j = i + 1:n
if z[i, i]!= 0
m = -z[j, i] / z[i, i]
z[j, :] = z[j, :] + m * z[i, :]
else
println("不能用高斯消去")
end
end
end
B = z[:, n + 1]
x[n] = B[n] / z[n, n]
for k = (n - 1):-1:1
s = 0.0
for t = k + 1:n
s = s + z[k, t] * x[t]
end
x[k] = (B[k] - s) / z[k, k]
# println("解x[%.0f]的值为%.1f", k, x[k])
end
return x
end
function GaussSeidelMatrix(A, B, tol = 1e-6)
(m, n) = size(A)
# 确认系数矩阵A是方阵(Gauss-Seidel迭代法要求系数矩阵为方阵,这里添加检查更严谨)
if m!= n
error("系数矩阵A必须是方阵")
end
# 确保B是列向量形式,维度为 (n, 1),如果不是则进行转换
if size(B, 2)!= 1
B = reshape(B, n, 1)
elseif size(B, 1)!= n
error("常数项向量B的维度与系数矩阵A的行数不匹配")
end
# 初始化迭代向量x,明确初始化为列向量形式(确保维度正确)
x = zeros(Float64, n, 1)
xGS = zeros(Float64, n, 1)
L = tril(A)
U = triu(A, 1)
max_iterations = 1000
iteration_count = 0
while true
xGS = (B - U * x) / L
error = norm(xGS - x)
if error < tol || iteration_count >= max_iterations
return xGS[:, 1]
end
x = xGS
iteration_count += 1
end
end
A = [10 -1 2 0; -1 11 -1 3; 2 -1 10 -1; 0 3 -1 8]
B = [6; 25; -11; 15]
solution_gauss = Gauss(A, B)
println("The solution of Gauss is")
for i in 1:length(solution_gauss)
println("x$i = ", solution_gauss[i])
end
solution_gauss_seidel = GaussSeidel(A, B)
println("The solution of Gauss-Seidel is")
for i in 1:length(solution_gauss_seidel)
println("x$i = ", solution_gauss_seidel[i])
end
Julia报错DimensionMismatch: Both inputs should have the same number of columns,怎么修改代码?