Unable to perform assignment because the left and right sides have a different number of elements - Gauss-Seidel Method to solve for inverse matrix
1 次查看(过去 30 天)
显示 更早的评论
Does anyone know why I'm getting this error: "Unable to perform assignment because the left and right sides have a different number of elements." when I try to solve for the inverse of A using the Gauss-Seidel method and identity matrix b? Thanks in advance!!
A = [8 0 1 1 4; 2 9 1 4 0; 1 5 9 2 1; 1 1 4 12 1;2 3 1 4 16];
n = length(A);
b = eye(n);
lambda = 1;
xinit = zeros(n,1);
norm = 2;
tol = 1.E-6;
maxiter = 100;
fprintf('\n-----Problem 1b------\n')
fprintf('The correct answer using the Gauss Seidel method will be the inverse matrix, x:')
[x,errst,iter] = seidel(A,b,x,lambda,tol,maxiter,norm);
x
iter
%% Functions
% Gauss Seidel
function [x,errst,iter] = seidel(A,b,x,lambda,tol,maxiter,norm)
n = length(A);
d = diag(A);
d = 1./d;
A = (A'*diag(d))';
b = b.*d;
A = A - eye(n);
err = 1.;
xold = x;
iter = 0;
while err>tol && iter<maxiter
iter = iter + 1;
for i = 1:n
x(i) = b(i)-A(i,:)*x;
end
x = lambda*x+(1-lambda)*xold;
errst(iter,:) = errnorm(x-xold)./errnorm(x);
err = errst(iter,norm);
xold = x;
end
if iter>=maxiter
fprintf('\nLinear solver maxiter exceeded!!!\n')
end
end
% error
function [abserr] =errnorm(vec)
vec = abs(vec);
abserr(1,1)= trace(vec);
abserr(1,2) = trace(sqrt(vec'*vec));
abserr(1,3) = max(max(vec));
end
0 个评论
采纳的回答
Erivelton Gualter
2019-11-19
For this case, it seems vec has 5x1 size. So you should you sum instead of trace.
function [abserr] =errnorm(vec)
vec = abs(vec);
abserr(1,1)= sum(vec);
abserr(1,2) = trace(sqrt(vec'*vec));
abserr(1,3) = max(max(vec));
end
5 个评论
Erivelton Gualter
2019-11-19
I realized the problem.
You dont need the loop to update x:
for i = 1:n
x(i) = b(i)-A(i,:)*x;
end
SO here is the final code again:
A = [8 0 1 1 4; 2 9 1 4 0; 1 5 9 2 1; 1 1 4 12 1;2 3 1 4 16];
n = length(A);
b = eye(n);
lambda = 1;
xinit = zeros(n);
norm = 2;
tol = 1.E-6;
maxiter = 100;
fprintf('\n-----Problem 1b------\n')
fprintf('The correct answer using the Gauss Seidel method will be the inverse matrix, x:')
[x,errst,iter] = seidel(A,b,xinit,lambda,tol,maxiter,norm);
x
iter
%% Functions
% Gauss Seidel
function [x,errst,iter] = seidel(A,b,x,lambda,tol,maxiter,norm)
n = length(A);
d = diag(A);
d = 1./d;
A = (A'*diag(d))';
b = b.*d;
A = A - eye(n);
err = 1.;
xold = x;
iter = 0;
while err>tol && iter<maxiter
iter = iter + 1;
x = b-A*x;
x = lambda*x+(1-lambda)*xold;
errst(iter,:) = errnorm(x-xold)./errnorm(x);
err = errst(iter,norm);
xold = x;
end
if iter>=maxiter
fprintf('\nLinear solver maxiter exceeded!!!\n')
end
end
% error
function [abserr] =errnorm(vec)
vec = abs(vec);
abserr(1,1)= trace(vec);
abserr(1,2) = trace(sqrt(vec'*vec));
abserr(1,3) = max(max(vec));
end
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!