Why isn't my y value changing?

3 次查看(过去 30 天)
Xavier Bardwell
Xavier Bardwell 2021-11-23
I have a while loop where i iterate through polyval calculations an unkown amount of times based on the r^2 value. My loop currently runs infinitely because my y values are not changing as the order changes. WHy isnt my y value changing and how can i fix it?
while rSQ < .95
y = polyval(polyfit(x,y,currOrder), x)
rSQTop = (yOG - y).^2
rSQBot = (yOG - yAVG).^2
rSQ = 1 - (sum(rSQTop) / sum(rSQBot))
if rSQ > .95
plot(x,y,'b-')
else
plot(x,y,'r--');
currOrder = currOrder + 1;
end
end
  1 个评论
Xavier Bardwell
Xavier Bardwell 2021-11-23
x = [-2.0000 -0.1130 -0.0545 0.0168 0.5409 0.5414 1.6444]
y = [50.1774 0.0007 0.0001 -0.0000 -0.0316 -0.0315 26.1672]

请先登录,再进行评论。

回答(1 个)

Image Analyst
Image Analyst 2021-11-23
I think you are trying to do this:
% Demo by Image Analyst
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 22;
x = linspace(0, 2*pi, 400);
y = cos(x) + 0.3 * rand(1, length(x));
p1 = plot(x,y,'b-');
hold on;
rSQ = 0;
loopCounter = 1;
maxIterations = 100;
currentOrder = 1;
requiredRSquared = 0.95;
while rSQ < requiredRSquared && loopCounter < maxIterations
fprintf('On iteration %d\n', loopCounter);
coefficients = polyfit(x,y,currentOrder);
yFitted = polyval(coefficients, x);
yAVG = mean(yFitted);
rSQTop = (yFitted - y).^2;
rSQBot = (yFitted - yAVG).^2;
rSQ = 1 - (sum(rSQTop) / sum(rSQBot));
message = sprintf('On iteration %d rSQ = %f. Order = %d', loopCounter, rSQ, currentOrder);
fprintf('%s\n', message)
if rSQ > requiredRSquared
p2 = plot(x, yFitted, 'g-', 'LineWidth', 5);
else
p2 = plot(x, yFitted, 'r-', 'LineWidth', 5);
currentOrder = currentOrder + 1;
end
grid on;
title(message, 'FontSize', 18);
g = gcf;
g.WindowState = 'maximized';
promptMessage = sprintf('Showing iteration %d.\nDo you want to Continue processing,\nor Quit processing?', loopCounter);
titleBarCaption = 'Continue?';
buttonText = questdlg(promptMessage, titleBarCaption, 'Continue', 'Quit', 'Continue');
if contains(buttonText, 'Quit', 'IgnoreCase', true)
break; % or break or continue.
end
loopCounter = loopCounter + 1;
% Get rid of last plot.
if rSQ < requiredRSquared
delete(p2);
end
end

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by