in this loop value of n is 0.05 and value of t is 0.700. If I run this loop, then for 'o = 1'. the matrix generatd fr U does not contain the lat element i.e. 0.700 and the V matrix does not contain first element - 0.700. Please help

1 次查看(过去 30 天)
o = 1;
U = zeros(1,t);
while(o<=2)
U = 0:n:t
o =o +1;
V = t:-n:0;
t = t - n;
end
|If the value of 'n' and 't' is assigned/generated from some other m file, which is used here, then this problem persists. If i intialise these values here in this m file then it is working fine. Moreover, if i change n from 0.05 to 0.005 then also loop shows error at t = 0.7000|

回答(2 个)

John Petersen
John Petersen 2012-8-2
Please put your question in the main body and use the subject line to describe the problem in a few words.
If the other mfile is a function then the variables are local to that function and can't be used in another script unless they are passed into your script. I don't see the point of the loop. Also, your initialization of U will not work if t<1 and is pointless anyway since you reassign U in the loop.
The first time through the loop you will have the right value. But you decrement t in the loop so that the next time it will not be 0.7 any more. The loop will run twice. Is that what you intend?

James Tursa
James Tursa 2012-8-2
In expressions like this:
U = 0:n:t
:
V = t:-n:0;
you should not use a value of n that is fractional (e.g., 0.7 or 0.005 etc) because these cannot be represented exactly in IEEE arithmetic and as a result you cannot control what the actual endpoints of the loop that uses them will be. You should always use integers for loop ranges initially and then divide them downstream if necessary. E.g., instead of doing stuff like this:
X = 0:0.05:10;
you should do this instead:
X = (0:(10*20))/20;
That way you can control exactly how many elements are in X and how many iterations of the loop will run if X is used for loop values.

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by