Uniques giving duplicates (unresolved)
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Doron
am 23 Feb. 2012
Bearbeitet: Eagle
am 23 Okt. 2013
I created a matrix P, and I incremented the values in first column using a for loop...
"for X = 0.9:0.025:1..."
After plotting, I then wanted to focus a bit more on one of the values, namely X = 0.975...
So I (manually) asked matlab to do some more calculations using 0.975 without a loop:
"for X = 0.975"
However, for reasons which I now understand, the 0.975 which was created in the loop is not EXACTLY equal to 0.975.
So, when I ask for the unique values in the X column, I received 0.975 twice:
>> PU = unique(P(:,1))
PU =
0.900000000000000
0.925000000000000
0.950000000000000
0.975000000000000
0.975000000000000
1.000000000000000
>> PU(4) - PU(5)
ans =
-1.110223024625157e-16
They are out by a tiny amount...
I designed my plotting routine to plot a line for each unique X value... So, there are two distinct legend lines for X = 0.975...
Two questions:
1. How do I avoid this problem in the future (even though I understand the cause, I don't see a solution). I will generally be plotting data from the original loop seeing how it looks, and manually requesting more information on specific values. So, how do I get around the problem that the for loop does not add EXACTLY what I ask it to?
2. How do I make the two "0.975...'s" equal to each other now? (They each appear a few thousand times in the first column of matrix P)
Thanks
D Howard
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 23 Feb. 2012
xvals = 0.9:0.025:1... %list of values for your loop
for X = xvals
....
end
nearest975 = interp1(xvals, xvals, 0.975, 'nearest');
for X = nearest975
...
end
In this way, nearest975 will be an exact copy of one of the values in the list xvals, which is the list you looped over.
Also, generally speaking linspace() has higher accuracy than the colon operator.
You would use the colon operator in a "for" loop instead of linspace if memory space is tight, in that linspace will create the complete list of values and store it, but the colon operator in a for loop will not store the values ahead of time and will generate them as needed. (Note: in the code I show above, the colon operator is not being used in a for loop, so the values will be generated and stored.)
4 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!