问题描述
如何从Matlab的阶梯函数输出中获取数据矢量?我尝试了以下
h = stairs(x,y);
然后我从句柄中获取数据:
x = h.XData;
y = h.YData;
但是绘制x和y时,它们看起来像是分段函数,而不是阶梯。
感谢您的帮助。 谢谢!
解决方法
显示stairs
图所需的数据相对容易自己生成。
假设您有x
和y
。要生成2个向量xs
和ys
,例如plot(xs,ys)
将显示与stairs(x,y)
相同的事物,可以使用以下2个步骤的方法:
- 复制
x
和y
的每个元素 - 将新矢量偏移一个元素(删除一个矢量的第一个点,另一个矢量的最后一个点)
示例代码:
%% demo data
x = (0:20).';
y = [(0:10),(9:-1:0)].' ;
hs = stairs(x,y) ;
hold on
%% generate `xs` and `ys`
% replicate each element of `x` and `y` vector
xs = reshape([x(:) x(:)].',[],1) ;
ys = reshape([y(:) y(:)].',1) ;
% offset the 2 vectors by one element
% => remove first `xs` and last `ys`
xs(1) = [] ;
ys(end) = [] ;
% you're good to go,this will plot the same thing than stairs(x,y)
hp = plot(xs,ys) ;
% and they will also work with the `fill` function
hf = fill(xs,ys,'g') ;
,
Matlab文档明确指出:
[xb,yb] =楼梯(___)不会创建图,但会返回矩阵xb 和yb大小相同,这样plot(xb,yb)绘制楼梯 图。