How can I find the iteration error? The norm function is giving me a dimension error.
1 view (last 30 days)
Show older comments
%%Part A
clear all;clc;
% 4x1 + 2x2 + x3 = 11
% -x1 + 2x2 = 3
% 2x1 + x2 + 4x3 = 16
a= [4 2 1;-1 2 0;2 1 4];
b=[11 3 16]';
X=a\b;
xpart1=X
%%Part B
clc;
% x1= 2.75 - .5x2 -.25x3
% x2= 1.5 + .5x1
% x3 = 4 -.5x1 -.25x2
B= [0 -.5 -.25; .5 0 0; -.5 -.25 0];
c= [2.75;1.5;4];
x0=[0;1;2];
tol = 1e-10;
X = x0; k = 1;
while 1
xnew = B*X + c;
if norm(xnew-X) < tol
break;
end
X = xnew;
k = k+1;
end
k
xpart2= X
error= abs(xpart1-xpart2)
%%Part C
clc;
X(:,1)=x0; k=1;
while 1
X(:,k+1) = B*X(:,k) + c;
if norm(X(:,k+1)-X(:,k)) < tol
break;
end
k = k+1;
end
k
x=X(:,k)
%%Iteration Plot
K=0:28;
bottom=X(1,:);
middle=X(2,:);
top=X(3,:);
figure;
plot(K,bottom,'b-','LineWidth',2)
hold on
plot(K,middle,'g-','LineWidth',2)
hold on
plot(K,top,'r-','LineWidth',2)
axis([0 37 0 4])
xlabel('iteration index, k')
ylabel('x(k)')
title('iterative solution')
ax=gca;
ax.YTick=[0:4]
legend('x_{1}','x_{2}','x_{3}','Location','se')
%%Iteration Error
E(K)=norm(a*X -b);
% u=0:28
% plot(u,E(k))
0 Comments
Answers (1)
Walter Roberson
on 29 Nov 2015
You define
K=0:28;
and you try to do
E(K)=norm(a*X -b);
so you are trying to index E at 0, 1, 2, ... 28. But MATLAB does not allow you to index a variable at index 0. You should just be leaving that (K) out and using
E = norm(a*X - b);
You will still have a problem, though. At that point in your code, a is 3 x 3 and X is 3 x 29 so a*X is going to be 3 x 29 . But your b is 3 x 1 and you cannot subtract a 3 x 1 from a 3 x 29. And if you expand the 3 x 1 to be 3 x 29 then you will be taking norm() of a 3 x 29 matrix which is going to give you a scalar result. You should be considering looping.
Possibly, though, you would consider it acceptable to use
E = sqrt(sum(bsxfun(@minus,a*X,b).^2));
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!