答案 0 :(得分:2)
目前,MATLAB正在数组中所有连续点之间绘制线条,包括x
值大幅跳跃时。
一个等效的例子就是这个情节:
% Create some x with points spaced by 0.1, except at 2 jumps of 5
x = [0:0.1:10, 15:0.1:25, 30:0.1:40];
y = sin(x);
plot(x,y)
注意我们的3个部分(10-15,25-30)之间的直线连接。
我们可以使用find
和diff
来获取x
跳转的区域,然后逐个绘制每个区域。
% Include indices for the first (we're going to +1, so start at 0) and last elements
% You can change this 1 to any tolerance you like, it might be of the order 10^4 for you!
idx = [0, find(diff(x) > 1), numel(x)];
% Hold on for multiple plots
hold on;
% Loop over sections and plot
for ii = 2:numel(idx)
% Plots will loop through colours if you don't specify one, specified blue ('b') here
plot(x(idx(ii-1)+1:idx(ii)), y(idx(ii-1)+1:idx(ii)), 'b')
end
hold off; % good practise so you don't accidentally plot more on this fig!
NaN
您还可以使用NaN
值来分解数据。 NaN
值不是由MATLAB绘制的,因此如果我们在每个中断中包含一个值,则没有任何内容可以连接到该行,我们会看到中断:
% Notice the NaNs!
x = [0:0.1:10, NaN, 15:0.1:25, NaN, 30:0.1:40];
y = sin(x);
plot(x,y)
自动化:您可能希望使用diff
函数动态查找某些预先存在的x
的跳转,如此
% Define some x and y as before, without NaNs, with big gaps in x
x = [0:0.1:10, 15:0.1:25, 30:0.1:40];
y = sin(x);
% Create anonymous function to insert NaN at vector index 'n'
insertNaN = @(v, n) [v(1:n), NaN, v(n+1:end)];
% Get indices where gap is bigger than some value (in this case 1)
idx = find(diff(x) > 1);
% Loop *backwards* through indices (so they don't shift up by 1 as we go)
for ii = numel(idx):-1:1
x = insertNaN(x,idx(ii));
y = insertNaN(y,idx(ii));
end
% Plot appears the same as the second plot above
plot(x,y);
注意:如果您想对x
和y
进行进一步处理,最好将随机NaN
值添加到数组中!你可以:
之后删除它们(假设没有预先存在的NaN)
x = x(~isnan(x));
y = y(~isnan(y));
使用临时变量进行绘图
xplot = x;
% then adding NaNs to xplot for plotting ...