File: ef230-2023-08/www/examples/pendulum_wave_gui.m Download
%! Fifteen Pendulums Swinging
%! Simulation with GUI showing fifteen pendulums swinging together
%! The lengths are such that they make neat visual patterns near 0, 30, and 60 seconds
%! This .m file requires the similarly named .fig file
%  University of Tennessee - EF 230 Fall, 2014 W. Schleter

function varargout = pendulum_wave_gui(varargin)
% PENDULUM_WAVE_GUI MATLAB code for pendulum_wave_gui.fig
%      PENDULUM_WAVE_GUI, by itself, creates a new PENDULUM_WAVE_GUI or raises the existing
%      singleton*.
%
%      H = PENDULUM_WAVE_GUI returns the handle to a new PENDULUM_WAVE_GUI or the handle to
%      the existing singleton*.
%
%      PENDULUM_WAVE_GUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in PENDULUM_WAVE_GUI.M with the given input arguments.
%
%      PENDULUM_WAVE_GUI('Property','Value',...) creates a new PENDULUM_WAVE_GUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before pendulum_wave_gui_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to pendulum_wave_gui_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help pendulum_wave_gui

% Last Modified by GUIDE v2.5 20-Nov-2014 14:00:16

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @pendulum_wave_gui_OpeningFcn, ...
                   'gui_OutputFcn',  @pendulum_wave_gui_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before pendulum_wave_gui is made visible.
function pendulum_wave_gui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to pendulum_wave_gui (see VARARGIN)

% Choose default command line output for pendulum_wave_gui
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes pendulum_wave_gui wait for user response (see UIRESUME)
% uiwait(handles.pendulum_figure);

clc;
init_plot();

% --- Outputs from this function are returned to the command line.
function varargout = pendulum_wave_gui_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on slider movement.
function time_slider_Callback(hObject, eventdata, handles)
% hObject    handle to time_slider (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
D=getappdata(gcf,'D');
D.t = get(hObject,'value');
setappdata(gcf,'D',D);
update_plot();

% --- Executes during object creation, after setting all properties.
function time_slider_CreateFcn(hObject, eventdata, handles)
% hObject    handle to time_slider (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end


function init_plot
% define parameters

D.a0 = 15; %initial angle (degrees)
D.g = 9.81; % gravity
D.dt = 0.1; % time step
D.sp = 1; % speed factor
D.dz=0.05; % offset in Z for each pendulum
D.c = rand(15,3); % random colors
D.f = (51:65)./60;  % frequencies (cycles/sec)
D.w = D.f*(2.*pi); % angular frequencies (rad/sec)
% w =sqrt(g/L) % basic equation
D.L = D.g./(D.w.^2); % pendulum lengths
D.t = 0; % current time
D.maxt = 60;
D.viewtype = 3;

% set axis and annotation
hold on;
axis equal
axis off
xlim([-.1 .1]);
ylim([-max(D.L)*1.1 0]);
zlim([0 .8]);

% slider
h=findobj(gcf,'tag','time_slider');
set(h,'min',0,'max',D.maxt,'sliderstep',[D.dt/D.maxt,1/D.maxt]);
addlistener(h,'ContinuousValueChange',@listener_callback);
% create the initial plot objects
for i=1:length(D.L)
    D.h(i)=plot3([0 D.L(i).*sind(D.a0)],[0 -D.L(i).*cosd(D.a0)],[i.*D.dz i.*D.dz],'o-',...
        'markersize',10,'markerfacecolor',D.c(i,:),'color',D.c(i,:));
end

% viewing
view(3)
set(gca,'cameraposition',[-.5 0 5]);
set(gca,'cameraupvector',[0,1,0]);

% timer
D.timer = timer();
D.timer.TimerFcn = @timer_callback;
D.timer.ExecutionMode = 'fixedRate';
D.timer.period = D.dt;
D.timer.busymode = 'drop';
set(D.timer,'userdata',gcf);
setappdata(gcf,'D',D);

function listener_callback(h,e)
% gcf and such also not available to listeners, findobj didn't work either
f = findall(0,'tag','pendulum_figure');
update_plot(f);

function update_plot(f)
% disp('start of update_plot')
if nargin==0
    f=gcf;
end
D=getappdata(f,'D');
h=findobj(f,'tag','time_slider');
D.t = get(h,'value');

set(findobj(f,'tag','time_text'),'string',sprintf('%.01f',D.t));

% update the plot for this time
    a= D.a0.*cos(D.w.*D.t);
    x= D.L.*sind(a);
    y=-D.L.*cosd(a);
    % set new position for each pendulum
    for i=1:length(D.L)
        set(D.h(i),'XData',[0 x(i)],'YData',[0 y(i)]);
    end
drawnow

% --- Executes on button press in startstop_button.
function startstop_button_Callback(hObject, eventdata, handles)
% hObject    handle to startstop_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
toggle_run()

function toggle_run(f)
if nargin==0
    f=gcf;
end
% disp('start of toggle_run');
D=getappdata(f,'D');
h = findobj(f,'tag','startstop_button');

if strcmp(D.timer.Running,'on')
    stop(D.timer);
    set(h,'string','Start')
else
    set(h,'string','Stop')
    start(D.timer);
end


% --- Executes on button press in viewtype_button.
function viewtype_button_Callback(hObject, eventdata, handles)
% hObject    handle to viewtype_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

D=getappdata(gcf,'D');

if D.viewtype==2
    % viewing
    view(3)
    set(gca,'cameraposition',[-.5 0 5]);
    set(gca,'cameraupvector',[0,1,0]);
    set(hObject,'string','2D');
    D.viewtype=3;
else
    D.viewtype=2;
    view(2);
    set(hObject,'string','3D');
end
setappdata(gcf,'D',D);

function timer_callback(t,~)
% BEWARE: gcf isn't defined for timer callbacks and anything called from the callback !!!???
% my workaround was to store the figure handle with the timer and pass it around
% disp('start of timer callback')
f=get(t,'userdata'); % figure handle stored here when timer was created
D=getappdata(f,'D');
h=findobj(f,'tag','time_slider');
t = get(h,'value')+D.dt;
t = round(t*10)/10;
if t>D.maxt
    toggle_run(f)
else
    set(h,'value',t);
    update_plot(f);
end


% --- Executes when user attempts to close pendulum_figure.
function pendulum_figure_CloseRequestFcn(hObject, ~, ~)
% hObject    handle to pendulum_figure (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure
D = getappdata(hObject,'D');
stop(D.timer);
delete(D.timer);
delete(hObject);