Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
For loop iterations not changing

Subject: For loop iterations not changing

From: Halley

Date: 20 Oct, 2011 16:43:10

Message: 1 of 2

I am trying to write a program using the inverse iteration method and I am running across an issue. With each iteration my values are not changing. With each iteration x(i) should become xnorm(i) and rho(i) should equal rho(i+1). I suspect that this is the problem, that somehow the order of the operations regarding rho is making it so that the relative error doesn't change. I have tried taking rho(i) out of the loop and calculating rho(1) but that did not seem to help either. I've been struggling with these problems for a few days so the help is really appreciated.
%Declare initial variables
A = [2 -1;-1 4];
b = [1;1];
B = [1 0;0 1];
Nmax = 20;
TOL = 1*10^-5;
k = 1;
x = zeros(2,21);
x_a = zeros(21,2);
rho = zeros(21,1);
xnorm = zeros(2,21);
x(:,1) = A\b;
x_a(1,:) = x(:,1)';

for i =1:Nmax
%Calculate old values
rho(i) = (x_a(i,:)*A*x(:,i))/(x_a(i,:)*B*x(:,i))

%Calculate new values
  xnorm(:,i) = (1/sqrt(x_a(i,:)*B*x(:,i)))*x(:,i)
  rho(i+1) = (x_a(i,:)*A*x(:,i))/(x_a(i,:)*B*x(:,i))
    
%Check for convergence
relative_error = abs((rho(i+1)-rho(i))/rho(i+1))

if ( relative_error ~= 0 && relative_error <= TOL )
x(:,i+1) = xnorm(:,i)
rho(i+1) = rho(i+1)
k = k
return
elseif (relative_error == 0)
x(:,i) = xnorm(:,i)
rho(i) = rho(i+1)
k = k+1
elseif (relative_error > TOL)
x(:,i) = xnorm(:,i)
rho(i) = rho(i+1)
k = k+1

end
end

Subject: For loop iterations not changing

From: Bob

Date: 20 Oct, 2011 17:19:01

Message: 2 of 2

Why are you computing new values and old values in the same loop
iteration?

Why the null statements such as
rho(i+1) = rho(i+1)
k = k

You seem to be re-using rho for several purposes. Why?
e.g. this raises some flags of using a variable before it is
initialized
rho(i) = rho(i+1)

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us