Updating input data MatLAB - matlab

I have got a GUI, which imports the data from a *.xls file and plots graph. The last thing I cannot do is the data refreshing, because my xls file updates each 15 sec. I want my GUI to update input data each 20 seconds. How can I do that? And also I would like to have a button which will have an ability to pause/run data updating.
function viewSTUEP
global hPlot hChoice raw
handles.F = figure('Name','viewSTUEP', 'Position',[100 20 900 550], ...
'Color',[0.8 0.8 0.8], 'NumberTitle','off', 'Resize','off');
uicontrol('Style','pushbutton', 'Position',[690 510 94 30], ...
'FontSize',12, 'String','Load', 'Callback',#LoadData);
uicontrol('Style','pushbutton', 'Position',[790 510 94 30], ...
'FontSize',12, 'String','Save plot', 'Callback',#SaveAs);
uicontrol('Style', 'pushbutton', 'Position', [690 475 94 30], ...
'FontSize',12, 'String','Update', 'Callback',#UpdatePlot);
uicontrol('Style','pushbutton', 'Position',[790 475 94 30], ...
'FontSize',12, 'String','Close', 'Callback',{#Close,handles});
set(handles.F, 'CloseRequestFcn', {#Close,handles})
set(gcf, 'Toolbar', 'figure');
clear raw, raw(1,:) = {''};
hPlot = axes('Position',[0.06 0.08 0.68 0.9], 'Visible','on');
uicontrol('Style','text', 'Position',[690 432 130 35], ...
'BackgroundColor',[0.8 0.8 0.8], 'FontSize',12, ...
'HorizontalAlignment','left', 'String','Columns for plot:');
hChoice = uicontrol('Style','listbox', 'Position',[690 420 204 22], ...
'FontSize',12, 'String',raw(1,:), 'Min',1, 'Max',1);
function Close(hObject, eventdata, handles)
delete(handles.F);
function LoadData(hObject, eventdata)
global hChoice raw xdat
[fname, pname] = uigetfile('*.xls','Select a data file');
if fname ~= 0
filename = strcat(pname, fname);
[numeric,text,raw] = xlsread(filename);
num = length(raw(1,:));
if (num > 21) num = 21; end
posY = 442 - (20*num);
set(hChoice, 'String',raw(1,:));
set(hChoice, 'Max',num);
set(hChoice, 'Position',[690 posY 204 (20*num)]);
xdat = datenum(0,0,0,0,0,cell2mat(raw(2:end,6)));
end
function UpdatePlot(hObject, eventdata)
global hPlot hChoice raw xdat
if ~isempty(raw)
cols = get(hChoice,'Value');
plot(hPlot, xdat,cell2mat(raw(2:end,cols(1))), 'LineWidth',2), datetick('x','HH:MM')
grid on
if (length(cols) > 1)
colors = 'brgcmyk'; c = 2;
hold(hPlot, 'on')
for k = cols(2:end)
plot(hPlot, xdat,cell2mat(raw(2:end,k)),colors(c),'LineWidth',2)
c = c+1; if (c > 7) c = 1; end
end
hold(hPlot, 'off')
end
legend(hPlot, raw(1,cols), 'Interpreter','none','Location','SouthEast')
xlabel(hPlot, 'Time in minutes:');
ylabel(hPlot, 'Temperature in C:');
end
function SaveAs(hObject, eventdata, handles)
[Save,savename] = uiputfile('*.eps','Save plot as: ')
fname=fullfile(savename,Save);
print('-depsc','-r300','-noui',fname)

I think you should use a timer object - see here

Related

Changing subplot data in MATLAB using slider function

I have been trying to plot two images side by side with two sliders using uicontrol. I am relatively new to uicontrol using matlab. Only the second subplot updates when I change the slider.
close all;
clear all;
clc;
set(0,'defaultAxesFontSize',14)
set(0,'DefaultFigureWindowStyle','docked')
data = rand(3,1024,64,20);
nslice = size(data,4);
nidx = size(data,1);
if nslice == 1
sampling = 1; % in some of my data nslice would be 1 so I would like my slider to not give me error in such a case
else
sampling = 5;
end
idx = 1;
slice = 1;
h.f = figure(1);
x_axis = linspace(0,0.5,size(data,3));
y_axis = linspace(0,70,size(data,2));
set(h.f,'doublebuffer','on')
h.data = data;
inst_data = squeeze(data(nidx,:,:,slice));
h.ax(1) = subplot(1,2,1,'Parent',h.f,'Units','Normalized');
imagesc(h.ax(1),x_axis,y_axis, inst_data)
colorbar;
colormap(h.ax(1),'gray')
caxis(h.ax(1),[min(abs(inst_data(:))),max(abs(inst_data(:)))])
xlabel('xaxis')
ylabel('yaxis')
title('figure 1')
h.ax(2) = subplot(1,2,2,'Parent',h.f,'Units','Normalized');
log_data = log(inst_data);
imagesc(h.ax(2),x_axis,y_axis, log_data)
colorbar;
colormap(h.ax(2),'jet')
caxis(h.ax(2),[-max(abs(log_data(:))),max(abs(log_data(:)))])
xlabel('xaxis')
ylabel('yaxis')
title('figure 2')
sgtitle({'Sample data ', ['Slice: ',num2str(slice),' index: ', num2str(idx)]},'FontSize',16,'FontWeight','Bold')
h.slider1=uicontrol('Parent',h.f,...
'Units','Normalized',...
'Position',[0.1 0.06 0.8 0.05],...
'Style','slider',...
'SliderStep',[1,sampling],...
'Min',1,'Max',nslice,'Value',1,...
'Callback',{#slider_Callback,data,x_axis,y_axis});
txt1 = 'Slice';
txt2 = 'Index';
annotation('textbox', [0.05 0.07 0.05 0.04], 'string', txt1);
annotation('textbox', [0.05 0.021 0.05 0.04], 'string', txt2);
h.slider2=uicontrol('Parent',h.f,...
'Units','Normalized',...
'Position',[0.1 0.02 0.8 0.05],...
'Style','slider',...
'SliderStep',[1,1],...
'Min',1,'Max',nidx,'Value',1,...
'Callback',{#slider_Callback,data,x_axis,y_axis});
guidata(h.f,h)
%%
function slider_Callback(hObject,eventdata,data,x_axis,y_axis)%#ok<INUSD>
h=guidata(hObject);%retrieve struct
slice_i = round(get(h.slider1, 'Value'));
idx_i = round(get(h.slider2,'Value'));
inst = squeeze(data(idx_i,:,slice_i));
colorbar;
colormap(h.ax(1),'gray')
caxis(h.ax(1),[min(abs(inst(:))),max(abs(inst(:)))])
h.ax(1) = imagesc(x_axis,y_axis,inst); colorbar
lg = log(inst);
colorbar;
colormap(h.ax(2),'jet')
caxis(h.ax(2),[-max(abs(lg(:))),max(abs(lg(:)))])
h.ax(2) = imagesc(x_axis,y_axis, lg ); colorbar;
sgtitle({'Sample data ', ['Slice: ',num2str(slice_i),' index: ', num2str(idx_i)]},'FontSize',16,'FontWeight','Bold')
drawnow
end
Other problems include:
The slider slides with a floating value which shouldnt be the case
When my data has only 1 slice, the slider moves to value zero which shouldn't happen. You can try the same example with data = rand(3,1024,64,1);

apply two callbacks for single dynamic matrix

Display
G3.vardisp= uicontrol('Style','edit',...
'Position', [520 280 30 30],...
'String','0');
Slider
G3.slide = uicontrol('style','slide',...
'unit','pix',...
'position',[400 280 120 30],...
'min',-10,'max',10,'val',1,...
'sliderstep',[1/20 1/10],...
'callback',{#sl_call3,G3});
callback for Slider
function [] = sl_call3(varargin)
[l,G3] = varargin{[1,3]}; % calling handle and data structure.
set(G3.vardisp,'String',get(l,'value'))
vbrilho=get(l,'value')
subplot('Position',[.35, 0.575, 0.375, 0.375])
x4.head_mod=(vcontraste*x4.head)+(vbrilho*10);
imshow(x4.head_mod)
end
button
filtro.medfiltbtn1 = uicontrol('Parent',hsp,...
'Style', 'pushbutton',...
'String', 'medfilt2_1',...
'Position',[0 35 80 30],...
'callback',{#teste,1});
callback for button
function []= teste(varargin)
[t1] = varargin{[3]};
while t1==1
subplot('Position',[.35, 0.575, 0.375, 0.375])
x4.head_modf=imnoise(x4.head_mod,'gaussian',0,0.01);
t1=0;
imshow(x4.head_modf)
end
When the code is run the imnoise can be applied over the x4.head_mod, but I can't apply the equation (vcontraste*x4.head)+(vbrilho*10) over imnoise. I want somehow to nest both results.

How to change the status of a boolean with Callbacks from radiobuttons in matlab

I created a small example program to demonstrate my problem (The variable "option1selcted" does not change its value):
classdef radioexample < handle
%radioexample2
% example for radiobuttuns
properties(Hidden)
% all elements of the GUI are properties of the class trechner
formMain; % "The MainWindow"
menuFile; % "The Menu Header"
% buttons
buttonTest
% radio items
radiogroup
radio1
radio2
% statis variable
option1selcted = true;
end
methods(Hidden)
function obj = radioexample
% Constructor Form Main
obj.formMain = figure('position',[400,400,600,260],'Visible','off');
set(obj.formMain,'Name','Rradioexample','NumberTitle','off',...
'MenuBar','none','Resize','Off');
% a menu for exit the program
obj.menuFile.main = uimenu('Label','File');
obj.menuFile.exit = uimenu(obj.menuFile.main,...
'Label','Exit','Callback',{#obj.close_Callback,obj});
% radiobutton to select the mode
obj.radiogroup = uibuttongroup(obj.formMain,...
'Visible','on',...
'Units','pixels',...
'BackGroundColor',[0.8 0.8 0.8],...
'Position',[220 80 100 100]);
%'SelectionChangedFcn',#obj.bselection);
uicontrol(obj.radiogroup,...
'Style',...
'radiobutton',...
'BackGroundColor',[0.8 0.8 0.8],...
'String','Option 1',...
'Position',[10 70 70 20],...
'Callback',#obj.opt1_Callback,...
'HandleVisibility','off');
uicontrol(obj.radiogroup,...
'Style',...
'radiobutton',...
'BackGroundColor',[0.8 0.8 0.8],...
'String','Option 2',...
'Position',[10 50 70 20],...
'Callback',#obj.opt2_Callback,...
'HandleVisibility','off');
obj.buttonTest = uicontrol('Style','pushbutton','String','Print radiostaus intop the Command Window',...
'Position',[40,200,260,60],...
'Callback',{#obj.test_Callback,obj,'test'},'Enable','On');
set(obj.formMain,'Visible','on');
fprintf('programm started');
end
end
methods(Static,Access=private)
function close_Callback(~,~,obj)
% close window
close(obj.f)
end
function opt1_Callback(hObject, evt)
fprintf('switched to radio1 mode\n');
obj.option1selcted = true; %<- does not change the variable?
end
function opt2_Callback(hObject, evt)
fprintf('switched to radio2 mode\n');
%msgbox('switched to radio2 mode','Success');
obj.option1selcted = false; %<- does not change the variable?
end
function test_Callback(~,~,obj,val)
fprintf('the status of the radiobutton is: %d\n', obj.option1selcted);
end
end
methods(Access=public,Hidden)
function disp(obj)
end
end
end
To test the status of the variable "option1selcted" the testbutton writes its status into the matlab command window.
You cannot change values of obj within a static method. Define the callback-functions within a non-static methods-block. You need to add another ~ for the input arguments. I fixed this issue in the callback of the button as well.
Here is the full code:
classdef radioexample < handle
%radioexample2
% example for radiobuttuns
properties(Hidden)
% all elements of the GUI are properties of the class trechner
formMain; % "The MainWindow"
menuFile; % "The Menu Header"
% buttons
buttonTest
% radio items
radiogroup
radio1
radio2
% statis variable
option1selcted = true;
end
methods(Hidden)
function obj = radioexample
% Constructor Form Main
obj.formMain = figure('position',[400,400,600,260],'Visible','off');
set(obj.formMain,'Name','Rradioexample','NumberTitle','off',...
'MenuBar','none','Resize','Off');
% a menu for exit the program
obj.menuFile.main = uimenu('Label','File');
obj.menuFile.exit = uimenu(obj.menuFile.main,...
'Label','Exit','Callback',{#obj.close_Callback,obj});
% radiobutton to select the mode
obj.radiogroup = uibuttongroup(obj.formMain,...
'Visible','on',...
'Units','pixels',...
'BackGroundColor',[0.8 0.8 0.8],...
'Position',[220 80 100 100]);
%'SelectionChangedFcn',#obj.bselection);
uicontrol(obj.radiogroup,...
'Style',...
'radiobutton',...
'BackGroundColor',[0.8 0.8 0.8],...
'String','Option 1',...
'Position',[10 70 70 20],...
'Callback',#obj.opt1_Callback,...
'HandleVisibility','off');
uicontrol(obj.radiogroup,...
'Style',...
'radiobutton',...
'BackGroundColor',[0.8 0.8 0.8],...
'String','Option 2',...
'Position',[10 50 70 20],...
'Callback',#obj.opt2_Callback,...
'HandleVisibility','off');
obj.buttonTest = uicontrol('Style','pushbutton','String','Print radiostaus intop the Command Window',...
'Position',[40,200,260,60],...
'Callback',{#obj.test_Callback,obj,'test'},'Enable','On');
set(obj.formMain,'Visible','on');
fprintf('programm started');
end
function opt1_Callback(~,hObject,evt)
fprintf('switched to radio1 mode\n');
obj.option1selcted = true;
end
function opt2_Callback(~,hObject,evt)
fprintf('switched to radio2 mode\n');
%msgbox('switched to radio2 mode','Success');
obj.option1selcted = false;
end
function test_Callback(~,~,~,obj,val)
fprintf('the status of the radiobutton is: %d\n', obj.option1selcted);
end
end
methods(Static,Access=private)
function close_Callback(~,~,obj)
% close window
close(obj.f)
end
end
methods(Access=public,Hidden)
function disp(obj)
end
end
end

Matlab - Deployed Program - ButtonDownFcn does not execute

I'm creating a tool for our engineering team to view data coming off our systems in the field. The underlying data isn't critical to it. Basically, it consists of vectors containing Y data at X time.
I'm plotting a series of vectors using subplot. Each plot has the ButtonDownFcn defined to launch a window that allows for deeper analysis. The problem is that when I click on the axes in the deployed application, nothing happens. There are no error messages or anything. When I click on the axes running it in Matlab, it works exactly as expected.
I'm not sure what's going on once the code is deployed that is preventing it from functioning properly. I'm a little lost on where to go. I've included my code and some sample data.
Test Data:
stats = struct('name','Car 54', ...
'date', '11-Aug-2014');
stats.SOC = struct('time', linspace(1,24,100)*3600', ...
'plugdata', [100*ones(20,1); NaN(70,1); (20:4:56)'], ...
'drivedata', [NaN(20,1); (100:-2:60)'; NaN(10,1); (40:-2:20)'; NaN(20,1); (30:-2:16)'; NaN(10,1)], ...
'eptodata', [NaN(41,1); (58:-2:40)'; NaN(11,1); (18:-2:5)'; NaN(13,1); NaN(7,1); NaN(11,1)], ...
'engchargedata', [NaN(69,1); (5:2:30)'; NaN(18,1)], ...
'otherdata', NaN(100,1));
Code:
function [output] = summarytablepopup(stats)
FH = figure('Name','Summary Table Popup', ...
'Units', 'normalized', ...
'Position', [0.05 0.05 0.9 0.8], ...
'Tag', 'sumTablePU', ...
'Toolbar', 'none', ...
'NumberTitle', 'off', ...
'WindowStyle', 'normal', ...
'Resize', 'on', ...
'CloseRequestFcn', #closereq, ...
'MenuBar', 'none', ...
'UserData', {});
movegui(FH,'onscreen')
noStats = numel(stats);
screensize = get(0,'ScreenSize');
mapIMG = imread([pwd '\icons\map.jpg']);
noGraphs = 5;
AH = NaN(noStats,1); % axes handles
TT = NaN(noStats,1); % name text handles
MB = NaN(noStats,1); % map button handles
TH = NaN(ceil(noStats/noGraphs),1); % tab handles
warning('off','all')
TGH = uitabgroup('Parent',FH); % tab group handle
for ii = 1:length(TH)
TH(ii) = uitab('parent',TGH,'title',sprintf('Page %d',ii));
end
warning('on','all')
for ii = 1:noStats
currentPage = ceil(ii/noGraphs);
vehiclename = stats(ii).name;
vehicledate = stats(ii).date;
if isfield(stats(ii),'SOC') && ~isempty(stats(ii).SOC) && isfield(stats(ii).SOC,'time') && ~isempty(stats(ii).SOC.time)
SOC = stats(ii).SOC;
time = SOC.time/3600;
subplot(5,1,mod(ii-1,noGraphs)+1,'Parent',TH(currentPage))
HH = plot(time, SOC.plugdata, 'g-x', ...
time, SOC.eptodata, 'b-x', ...
time, SOC.engchargedata, 'b-x', ...
time, SOC.drivedata, 'r-x', ...
time, SOC.otherdata, 'k-x');
AH(ii) = get(HH(1),'Parent');
set(HH,'Marker','.')
set(HH(3),'Color',[0 0.75 1])
set(HH(3),'MarkerFaceColor',[0 0.75 1])
else
subplot(5,1,mod(ii-1,noGraphs)+1,'Parent',TH(currentPage))
HH = plot([0 12 24],[NaN NaN NaN]);
AH(ii) = get(HH(1),'Parent');
%}
end
pos = get(AH(ii),'Position');
pos(1) = 0.25;
pos(3) = 0.72;
set(AH(ii),'Position',pos)
set(AH(ii),'UserData', ii)
set(AH(ii),'ButtonDownFcn', #divedeep)
set(AH(ii),'YLim',[0 100])
set(AH(ii),'YTick',[0 25 50 75 100])
set(AH(ii),'YTickLabel',{'0','25','50','75','100'})
set(AH(ii),'XLim',[0 24])
set(AH(ii),'XTick',[0 4 8 12 16 20 24])
set(AH(ii),'XTickLabel',{'0000','0400','0800','1200','1600','2000','2400'})
mapHeight = 0.1;
mappos = [0.18 pos(2)+pos(4)/2-mapHeight/2 mapHeight*screensize(4)/screensize(3) mapHeight];
MB(ii) = uicontrol('Parent', TH(currentPage), 'Style', 'pushbutton', ...
'Tag', sprintf('mapButton%d',ii), ...
'String', '', ...
'Units', 'normalized', ...
'Position', mappos, ...
'CData', mapIMG, ...
'Callback', #mapbutton);
if isfield(stats(ii),'location') && ~isempty(stats(ii).location) && isfield(stats(ii).location,'time') && ~isempty(stats(ii).location.time)
set(MB(ii),'Enable','on')
else
set(MB(ii),'Enable','off')
end
textHeight = 0.05;
textpos = [0.01 pos(2)+pos(4)/2-textHeight/2 0.15 textHeight];
TT(ii) = uicontrol('Parent', TH(currentPage), 'Style', 'text', ...
'Tag', sprintf('text%d',ii), ...
'String', vehiclename, ...
'FontSize', 12, ...
'Units', 'normalized', ...
'Position', textpos);
end
uiwait(FH)
function mapbutton(source, event)
tag = get(source,'Tag');
splittag = strsplit(tag,'n');
jj = str2num(splittag{2});
loc = stats(jj).location;
if ~isempty(loc)
len = numel(loc.time);
map = [linspace(1,0,len)', linspace(0,1,len)', zeros(len,1)];
MFH = figure;
MPH = plot(loc.lon, loc.lat, 'r:');
hold on;
MSH = scatter(loc.lon, loc.lat, 50, 'o', 'filled', 'CData', map);
plot_google_map
else
msgbox('No location information available for this vehicle. Really should disable this button.')
end
end
function electric(source, event)
ratio = get(SH,'Value')/100*(0.9-startheight)+0.05;
set(PH, 'Position', [panpos(1) ratio panpos(3) panpos(4)])
end
function divedeep(source, event)
HEDtimeplot([],stats(get(source,'UserData')));
end
function closereq(source,event)
uiresume(source)
delete(source)
end
end

Converting rgb-video input to grayscale output

I would like to convert a video file using rgb2gray on the videoframes, thing is i'm not completely sure how.
I have got this script file, playing the video file using a slider:
%-------------------------------------------------------------------
function frametracking()
%# read all frames at once
filename = uigetfile('*.avi');
vid = VideoReader(filename);
numImgs = get(vid, 'NumberOfFrames');
frames = read(vid);
% Make the UI
mx = numImgs-1;
hFig = figure('Menubar','none');
uicontrol('Style','slider', 'Parent',hFig, ...
'Callback',#slider_callback, ...
'Units','pixels', 'Position',[150 0 260 20], ...
'Value',1, 'Min',1, 'Max',mx, 'SliderStep',[1 10]./mx);
pB1 = uicontrol(hFig, 'Position',[150 20 130 20], ...
'Units','pixels', ...
'String','Select file', ...
'Callback',#button1_callback);
pB2 = uicontrol(hFig, 'Position',[280 20 130 20], ...
'Units','pixels', ...
'String','Calibrate', ...
'Callback',#button2_callback);
eT1 = uicontrol(hFig, 'Style','edit',...
'Units','pixels',...
'Position',[490 400 60 20],...
'CallBack',#edit1_callback,...
'String','');
eT2 = uicontrol(hFig, 'Style','edit',...
'Units','pixels',...
'Position',[490 370 60 20],...
'CallBack',#edit2_callback,...
'String','');
eT3 = uicontrol(hFig, 'Style','edit',...
'Units','pixels',...
'Position',[490 370 60 20],...
'CallBack',#edit3_callback,...
'String','');
hAx = axes('Parent',hFig,'units','pixels',...
'Position',[80 80 400 400]);
grayframe = rgb2gray(frames(:,:,:,1));
hMainImg = imshow(grayframe(:,:,:,1), 'Parent',hAx);
%# callback functions
function slider_callback(src,~)
val = round(get(src,'Value')); %# starting index
%# update the thumbnails
for ii = 1 : numel(hMainImg)
set(hMainImg(ii), 'CData',frames(:,:,:,ii+val-1))
drawnow
end
end
function click_callback(src,~)
%# update the main image
% grayframe = rgb2gray(frames(:,:,:,1));
set(hMainImg, 'CData',get(src,'CData'));
drawnow
end
function button1_callback(src,~)
end
end
%-------------------------------------------------------------------
At line 40 i've added: grayframe = rgb2gray(frames(:,:,:,1));, this makes the first frame gray. How do I make this count for all frames? My goal is to track an object in the videoframe, so I want to convert the frames to binary images aswell, and apply a additional filter like edge detection or something similar.
Thanks in advance
for i=1:numImgs
frames(:,:,:,i)=rgb2gray(frames(:,:,:,i));
end
I'd rather get rid of rgb2gray and vectorize it
GRAYframes = uint8(mean(RGBframes,3));
1- construct a VideoReader object
2- read each frame and convert it to grayscale using RGB2GRAY
3- playback the video
clear
clc
obj = VideoReader('xylophone.mp4');
nFrames = obj.NumberOfFrames;
vidHeight = obj.Height;
vidWidth = obj.Width;
mov(1:nFrames) =struct('cdata',zeros(vidHeight,vidWidth,1,'uint8'),...
'colormap',[]);
% Read one frame at a time.
for k = 1 : nFrames
mov(k).cdata =rgb2gray( read(obj,k));
end
implay(mov);