如何在matlab图中滑动绘制的线条

问题描述 投票:-1回答:2

我正在使用下面的代码绘制一个罪和余弦:

x = 0 : 0.1 : 2*pi ;
y1 = sin (x) ;
y2 = cos (x) ;
figure ;
plot(x,y1) ;
hold ;
plot(x,y2,'r')

我想移动/滑动对应于sin的线,以覆盖在对应于cos的线的顶部,并且想要在不移动平移的情况下实现它。我搜索了ob web但无法找到一个简单的解决方案。

matlab matlab-figure
2个回答
3
投票

您可以在函数中绘制2个正弦/余弦,然后使用回调来更新您的绘图,这里我更新回调函数call_S中的正弦图的相位:

function [] = slider_plot()
  % Plot different plots according to slider location.
  S.fh = figure('position',[300 300 300 300],....
                'resize','off');    
  S.x = 0:.01:4*pi;  %range.         
  S.ax = axes('unit','pix',...
              'position',[20 80 260 210]);
  S.sin = plot(S.x,sin(S.x),'r'); %sinus phase will move
  hold on
  S.cos = plot(S.x,cos(S.x),'b');       
  S.sl = uicontrol('style','slide',...
                   'position',[20 10 260 30],...
                   'min',0,'max',3*pi/2,'val',0,... %default phase = 0
                   'sliderstep',[0.1 0.1],...
                   'callback',{@call_S,S});  
function [] = call_S(varargin)
  % Callback for the phase slider.
  [h,S] = varargin{[1,3]};  % calling handle and data structure.
  set(S.sin,'ydata',sin(S.x + get(h,'value'))) %set the new phase

在这种情况下我使用滑块,但您也可以使用鼠标的位置来确定新阶段。

结果:

enter image description here

您可以移动滑块来移动相位:

enter image description here


0
投票

非常感谢@obchardon:

以下是符合我要求的代码的更新版本:

function [] = slider_plot2()
x = 0 : 0.1 : 4*pi ;
y1 = sin (x) ;
y2 = cos (x) ;
  % Plot different plots according to slider location.
  S.fh = figure('position',[300 300 500 500],....
                'resize','off');    
  S.x = x;  %range.   
  S.y2 = y2  ;
  S.ax = axes('unit','pix',...
              'position',[30 80 460 410]);
  S.line2 = plot(S.x,y2,'r'); %sinus phase will move
  hold on
  S.line1 = plot(S.x,y1,'b');       
  S.sl = uicontrol('style','slide',...
                   'position',[20 10 260 30],...
                   'min',1,'max',length(x),'val',1,... %default phase = 0
                   'sliderstep',[1 1],...
                   'callback',{@call_S,S});  
function [] = call_S(varargin)
  % Callback for the phase slider.
  [h,S] = varargin{[1,3]};  % calling handle and data structure.
  currentPosition = floor(get(h,'value'))  ;
  ydata = S.y2(currentPosition:end) ;
  xdata = S.x(1:end-currentPosition+1)  ;
 set(S.line2,'xdata',xdata,'ydata',ydata) %set the new phase
 %set( S.line2,'ydata',ydata) %set the new phase
© www.soinside.com 2019 - 2024. All rights reserved.