필터 지우기
필터 지우기

while loop not performing

조회 수: 1 (최근 30일)
Eli Wolkenstein
Eli Wolkenstein 2022년 5월 11일
편집: Matt J 2022년 5월 11일
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