简体   繁体   中英

MATLAB: Save command not working

I am trying to save some variables at different time steps in a while loop using the 'save' command. It was working in other programs which I had written previously. This is the first time it's not saving. I tried many things like renaming the file to which the data is saved, renaming the script, but it's not working. Here's the sample code:

T=0;
while T<300 (time loop)
loop1

loop2
.
.
.
if T==0.01
save('arbit100x100ht10e-3results.txt','Pnew','unew','-ascii','-append')
else if T==0.02
    save('arbit100x100ht10e-3results.txt','Pnew','unew','-ascii','-append')
else if T==0.04
        save('arbit100x100ht10e-3results.txt','Pnew','unew','-ascii','-append')
.
.
. (all the if-if else statements have their respective "end")


T=T+ht; %ht is time step

end (while loop)

I am not able to figure out a way out of this.

It is probably conditions like if T==0.01 that never occur because of floating point precision limit that causes the files not to be saved.

When you're trying to compare two floating-point numbers, be very careful about using == to do so. For example, when you try:

T=0.9-0.8;
T==0.1
ans =
     0

you see that T is never ==0.1 because of the precision limit in how a double is represented in binary form :

T-0.1
ans =
   -2.7756e-17

An alternative comparison method is to check if the two numbers you're comparing are "close enough" (as expressed by a tolerance) to one another. Try to change the if conditions to something that include a threshold tolerance such as:

if abs(T-0.01)<1e-10
    ...

For an introduction to floating point arithmetic, look at Cleve's Corner article: Floating Points ( PDF )

For a more rigorous and detailed information on floating point arithmetic, read What Every Computer Scientist Should Know About Floating Point Arithmetic .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM