while loop not performing
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
更多回答(2 个)
Walter Roberson
2022-5-11
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 个评论
Image Analyst
2022-5-11
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!