how to not plot NaN but still have same array length

조회 수: 162 (최근 30일)
RuiQi
RuiQi 2016년 11월 25일
댓글: Walter Roberson 2018년 2월 9일
I have y = array of 10000 data. A lot of them are NaN. I dont want to plot NaN but if I use plot(y(~isnan(y)),'o'); my plot only goes up to ~1000. It should still go up to 10000 but not plot those with NaN. How can i do this ?

답변 (2개)

Star Strider
Star Strider 2016년 11월 25일
The NaN values themselves will not plot. This may produce breaks in the plotted line, so if you don’t want the breaks, your only option is to interpolate.
The easiest way to interpolate is to keep your original independent variable to be your interpolating variable, the eliminate all the NaN values from your dependent variable and the corresponding values of you independent variable, then use interp1.
Example:
x = 1:10;
y = [2 4 2 9 NaN 3 1 NaN 6 10];
xs = x(~isnan(y));
ys = y(~isnan(y));
yi = interp1(xs, ys, x, 'Linear');
figure(1)
subplot(2,1,1)
plot(x, y)
grid
subplot(2,1,2)
plot(x, yi)
grid
  댓글 수: 2
RuiQi
RuiQi 2016년 11월 25일
Sorry for not being specific. I am using a scatter plot. I want data that are NaN to be invisible on the plot. So i dont think i need to interpolate ?
Star Strider
Star Strider 2016년 11월 25일
The data that are NaN will be invisible on the plot.
MATLAB does not plot NaN values, so you can just use your original data in your scatter plot without any modification.
If you also want to eliminate them from your data, use code similar to what I used to create ‘xs’ and ‘ys’, then plot those.

댓글을 달려면 로그인하십시오.


Image Analyst
Image Analyst 2016년 11월 25일
Your code basically extracts the non-nan elements and plots only those so it won't go all the way up to 1000. You need to plot x also to have it still go up to 1000. See this little demo:
numPoints = 200; % Make 1000 if you want. I used 200 to make it easier to see what's going on.
% Make sine wave sample data.
x = 1 : numPoints;
period = 200;
y = sin(2 * pi * x / period);
% Introduce 80 nans
nanLocations = randi(length(x), 1, 80);
y(nanLocations) = nan;
% Plot entire array, even the nans, which won't appear.
plot(x, y, 'bo-', 'LineWidth', 2);
grid on;
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% Get rid of tool bar and pulldown menus that are along top of figure.
set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
  댓글 수: 2
atek
atek 2018년 2월 9일
what if y(1:100) = NaN? Matlab begins plotting at first real value, and I want it to plot NaN's as blank spaces
Walter Roberson
Walter Roberson 2018년 2월 9일
Use xlim() to force the left boundary to start at 0

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Discrete Data Plots에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by