Uniques giving duplicates (unresolved)
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Doron
el 23 de Feb. de 2012
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 comentarios
Respuesta aceptada
Walter Roberson
el 23 de Feb. de 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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!