while loop not performing
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Eli Wolkenstein
el 11 de Mayo de 2022
A=[-0.2 0.1; 0.1 -2];
vm=[1; 1];
while (1)
term=A*vm;
nterm=norm(term);
vm1=term/nterm;
ea=abs((vm1-vm)/vm1)*100;
vm=vm1;
if ea<=.0001, break, end
end
disp(vm1)
I wrote this code to perform the power method for finding eigenvectors. The while loop is not working though. It only goes through the program once. Does it have to do with the fact it's dealing with arrays? (Also, if you see a problem with this in regards to the power method feel free to correct that as well.)
0 comentarios
Respuesta aceptada
Más respuestas (2)
Walter Roberson
el 11 de Mayo de 2022
ea=abs((vm1-vm)/vm1)*100;
Are you certain that you want to use matrix right divide between two vectors that are each 2x1 ? The results would be 2x2 and when the fit is perfect the bottom right result would be 1.0
Perhaps you want element by element division, which is the ./ operation
0 comentarios
Image Analyst
el 11 de Mayo de 2022
Not sure what you're after but it never gets to the break and doesn't go through the loop once. In fact it gets in an infinite loop. I applied a failsafe to fix that but I still don't know when you'd ever expect it to hit the break.
A = [-0.2 0.1; 0.1 -2];
vm = [1; 1];
loopCounter = 1;
maxIterations = 1000;
while loopCounter < maxIterations
term = A * vm; % A 2x1 column vector.
nterm = norm(term); % A scalar
vm1 = term/nterm; % A 2x1 column vector.
ea = abs((vm1 - vm) / vm1) * 100; % A 2x1 column vector.
vm = vm1; % A 2x1 column vector.
if ea <= 0.0001 % Huh???!!! You're comparing two values in a column vector to a scalar.
fprintf('Hit the break!\n');
break % Never gets here.
end
loopCounter = loopCounter + 1;
end
if loopCounter == maxIterations
fprintf('Loop exited early because of failsafe - hit max number of iterations (%d).\n', maxIterations)
else
fprintf('Loop broke after %d iterations (%d).\n', loopCounter)
end
% Show values
ea
vm1
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!