While loop is not stopping at value.
Show older comments
Trying to understand why this code will not stop at the desired value. The goal is to get yini to stop prior to arriving at 1. Then have the second while loop take over for value greater than or equal to one. I am stumped looking at it.
%establish variables and values being used
clc;
clear;
start=input('Input Start Day');
stop=input('Input End Day');
h=input('Step Size(h)');
t=(start:h:stop);
f=3.*(sin(t).*sin(t));
fini=0;
yini=.6;
while yini < 1
yini=yini+(h*f);
end
while yini >= 1
yini=yini+(h*g);
g=f-(3*((ypos.^(2/3)-1).^1.5));
end
f
yini
2 Comments
Walter Roberson
on 26 Oct 2018
What inputs should we test with?
Vsevolod Kurtov
on 26 Oct 2018
Answers (2)
James Tursa
on 26 Oct 2018
Edited: James Tursa
on 26 Oct 2018
This line
yini=yini+(h*f);
makes yini a vector, since f is a vector. Given that, is the following test which is operating on a vector really what you intended?
while yini < 1
Walter Roberson
on 26 Oct 2018
t=(start:h:stop);
so in most cases, t will be a row vector.
f=3.*(sin(t).*sin(t));
With t being a row vector, sin(t) will be a vector, .* preserves vector shape, so f will be a row vector.
yini=.6;
yini starts as a scalar
while yini < 1
That is equivalent to
while all(yini(:) < 1)
by definition.
yini=yini+(h*f);
f is a row vector, 1 x N. You have used the * algebraic matrix multiplication operator. If h is a scalar, then h*f will be the same size of f, and so will be a row vector. If h is not a scalar then for the * operator to work, h would have to be a column vector, M x 1, and then h*f would be (M x 1) * (1 x N) which would give an M x N result. Scalar is not actually a special case for this, as scalar is M = 1, 1 x 1, with 1 x N result just as was described earlier for scalar.
So, h*f is M x N for some M that might well be 1, and N that is probably not 1.
You then add that M x N to the scalar yini, getting a M x N yini (probably a row vector), and that becomes your new yini.
Then the next time around the "while" loop, you are testing all of the entries in yini as being less than 1, and the while loop will not continue if even one of them fails the test.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!