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.)

采纳的回答

Matt J
Matt J 2022-5-11
编辑:Matt J 2022-5-11
A=[-0.2 0.1; 0.1 -2];
vm=[1; 1];
vm=vm/norm(vm);
while (1)
term=A*vm;
nterm=norm(term);
ea= nterm-abs(dot(term,vm));
if ea<=1e-6, break, end
vm=term/nterm;
end
eigval=vm\(A*vm)
eigval = -2.0055
eig(A)
ans = 2×1
-2.0055 -0.1945

更多回答(2 个)

Walter Roberson
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

Image Analyst
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
Loop exited early because of failsafe - hit max number of iterations (1000).
% Show values
ea
ea = 2×2
0 11.0770 0 200.0000
vm1
vm1 = 2×1
0.0553 -0.9985

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by