Delete Vector Element but Keep Vector Length
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Say we have two vectors, one for time and one for position.
X = [0,1,2,3,4,5,6,7,8,9,10]
Y =[0,2,4,6,8,143,12,14,16,18,20]
We want to delete 23 from Y, but keep the vector the same length, and not cause errors. We want the X Y matrix to just have an empty value. If we delete the 6th element in Y, all of a suddent Y is 10 elements instead of 11. If we replace with NaN, we get NaN when we want no number. If we replace with 0 we get 0 instead of empty.
Ultimately, we want to plot X and Y to show a trend, and we know the 6th element is an outlier that exceeds the measurement range. But how do we flag it? Is the only option to also delete the 6th element of X to match them up?
1 commentaire
Réponses (3)
Steven Lord
le 28 Jan 2022
X = [0,1,2,3,4,5,6,7,8,9,10];
Y =[0,2,4,6,8,143,12,14,16,18,20];
[newY, removedOutliers] = rmoutliers(Y);
newX = X;
newX(removedOutliers) = []; % Remove corresponding elements from X as well
plot(newX, newY)
Alternately if you want to show that something was removed, filling that value in Y with a NaN may be the most appropriate solution. You really didn't have data there, so why show a line across there that may mislead viewers into thinking you did?
newY2 = filloutliers(Y, NaN);
plot(X, newY2, 'o-')
2 commentaires
Walter Roberson
le 29 Jan 2022
Any element-wise arithmetic calculation involving NaN results in NaN
Matrix calculations such as matrix-multiply or matrix divide, that involve a NaN, will typically result in even more NaN.
Some functions such as sum() have specific options to ignore NaN (or not)
Voss
le 28 Jan 2022
Note that using NaN's in a vector you're plotting is useful to show that something is missing:
X = [0,1,2,3,4,5,6,7,8,9,10];
Y =[0,2,4,6,8,23,12,14,16,18,20];
figure();
plot(X,Y,'-o','LineWidth',2);
Y(Y > 20) = NaN;
hold on
plot(X,Y,'--rx','LineWidth',2);
As opposed to deleting the outliers from the vectors:
X = [0,1,2,3,4,5,6,7,8,9,10];
Y =[0,2,4,6,8,23,12,14,16,18,20];
figure();
plot(X,Y,'-o','LineWidth',2);
idx = Y > 20;
X(idx) = [];
Y(idx) = [];
hold on
plot(X,Y,'--rx','LineWidth',2);
0 commentaires
Walter Roberson
le 28 Jan 2022
X = [0,1,2,3,4,5,6,7,8,9,10]
Y =[0,2,4,6,8,143,12,14,16,18,20]
Y(6) = NaN
plot(X, Y)
Since your purpose is plotting, if you just drop in NaN then no connection will be drawn.
But you might prefer
X = [0,1,2,3,4,5,6,7,8,9,10]
Y =[0,2,4,6,8,143,12,14,16,18,20]
where_out = find(isoutlier(Y, 'SamplePoints', X));
newY = filloutliers(Y, 'spline', 'SamplePoints', X);
plot(X, newY, '-*', 'Color', 'b', 'MarkerEdgeColor', 'r', 'MarkerIndices', where_out)
0 commentaires
Voir également
Catégories
En savoir plus sur 2-D and 3-D Plots dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!