Matlab uicontrol function modification - matlab

I'm working on a project in which some parts are concerned with TicTacToe game. I have the tictactoe.m file and would like to change the code so that the player's selection would be applied by a function's output, say,RESULT parameter rather than clicking on the screen by the user himself. the uicontrol part of my code is as follows. How may I control the game by another function's output instead of pushbutton style?
function B = buttons
% Initialize push buttons and text.
clf
shg
B = zeros(3,3);
M = magic(3); % strategical approach and equivalent game for TicTacToe game.
for k = 1:9
[i,j] = find(k == M);
B(i,j) = uicontrol('style','pushbutton','units','normal', ...
'fontsize',16,'callback','tictactoe(''green'')');
end
uicontrol('style','text','units','normal','pos',[0.30 0.82 0.40 0.10], ...
'fontsize',20,'background',get(gcf,'color'),'tag','toptext');
uicontrol('style','text','units','normal','pos',[0.20 0.72 0.60 0.10], ...
'fontsize',10,'background',get(gcf,'color'),'tag','toptext','string', ...
['Pick single digit numbers. Each digit can be chosen only once. ' ...
'Generate a total of 15 using exactly three digits.'])
uicontrol('style','pushbutton','units','normal','string','Game', ...
'fontsize',12,'position',[.23 .12 .15 .07], ...
'callback','tictactoe(''game'')');
uicontrol('style','pushbutton','units','normal','string','Start', ...
'fontsize',12,'position',[.43 .12 .15 .07], ...
'callback','tictactoe(''start'')');
uicontrol('style','pushbutton','units','normal','string','Exit', ...
'fontsize',12,'position',[.63 .12 .15 .07], ...
'callback','tictactoe(''exit'')');

All the push button is doing is executing a callback command. In this case the pushbutton 'Start' is calling
tictactoe('start')
So you can get another function to start the came by calling the same function, you will have to look at the function 'tictactoe' because it will need another couple of inputs, the pushbutton uicontrol automatically adds in the extra inputs, objects handles etc.

Related

Creating an unknown amount of uicontrols in matlab

So for a self project I'm creating a gui minesweeper like game in matlab and want to create an adjustable pushbutton grid however I'm not sure on how to do so. this is what I have got so far.
function createField()
xAmount = str2double(inputdlg('enter row length'));
yAmount = str2double(inputdlg('enter column length'));
for i = 1:xAmount
for j = 1:yAmount
%create buttons
end
end
end
One solution might be:
function create_field(hparent, nx, ny, width, padding)
% Test arguments
if ~test_parent_handle(hparent)
error('Parent must be a single valid graphic handle.');
elseif ~test_positive_integer(nx)
error('Number of buttons on X direction must be a scalar positive integer.');
elseif ~test_positive_integer(ny)
error('Number of buttons on Y direction must be a scalar positive integer.');
elseif ~test_positive_integer(width) ...
|| (width >= 100)
error('Button width must be a scalar positive integer smaller than 100.');
elseif ~test_positive_integer(padding) ...
|| (padding >= 20)
error('Button padding must be a scalar positive integer smaller than 20.');
end;
% Resize the parent to fit the button grid
set(hparent, 'Units', 'pixels');
ppos = get(hparent, 'Position');
ppos(3) = nx*width + (nx-1)*padding;
ppos(4) = ny*width + (ny-1)*padding;
set(hparent, 'Position', ppos);
% Create button grid
for p = 1:nx
for q = 1:ny
bpos = [ % Button spec:
(p-1)*(width+padding) % - X
(q-1)*(width+padding) % - Y
width % - W
width % - H
];
uicontrol( ...
'Units', 'pixels', ...
'Tag', sprintf('X%dY%d',p,q), ...
'Style', 'pushbutton', ...
'Parent', hparent, ...
'Position', bpos ...
);
end;
end;
% ----- NESTED FUNCTIONS -----
function tf = test_parent_handle(value)
tf = isscalar(value) ...
&& ishandle(value);
end
function tf = test_positive_integer(value)
tf = isscalar(value) ...
&& isreal(value) ...
&& isfinite(value) ...
&& (value > 0) ...
&& (fix(value) == value);
end
end
For a figure with 15 x 10 square buttons, each having the side 25 pixels with a padding of 3 pixels between the buttons, call:
create_field(figure(), 15, 10, 20, 3);
As with most problems there are many different approaches, having written something similar I'll give you the same prompts that I used when writing my helper function.
Your code is going to act based on what button is pressed so each button will need its own unique ID and properties. Depending on the MATLAB version used, each of your graphics elements will have a handle. Starting in R2014b, graphics objects can be addressed directly as objects rather than needing to utilize a numeric ID as a pointer.
Start with the figure window and check out the figure properties:
h.mainfig = figure; % Arbitrary figure window
get(h.mainfig); % Dump properties to command window
Right now we're probably most interested in the Units and Position properties of the main figure window, which you can use in a helper function to figure out how to size and space the buttons as you create them.
If we create a pushbutton graphics object with uicontrol() we're going to get mostly the same properties.
h.randombutton = uicontrol('Parent', h.mainfig, 'Style', 'pushbutton');
get(h.randombutton);
Again, we're interested in the Units and Position properties. We're also going to be interested in the Callback property, which is the function that executes when we interact with the button. Another good one is the Tag property, which can be used to set a unique string tag for each button for use with later logic.
You've probably noticed I'm using a structure array to store my graphics handles. This is similar to how MATLAB generates its object data when creating a GUI with GUIDE and has the huge advantage of a tidy data package to pass around our function. A great thing about structure arrays is that you can nest data structures, allowing us to easily generate and address graphics objects without needing to get clever with dynamic field references or eval() (yuck). Instead of having to do something like button_1, button_2, etc, we can do:
h.button(1) = uicontrol('Parent', h.mainfig, 'Style', 'pushbutton');
h.button(2) = uicontrol('Parent', h.mainfig, 'Style', 'pushbutton');
...
h.button(n) = uicontrol('Parent', h.mainfig, 'Style', 'pushbutton');
Now we know how to generate an arbitrary number of buttons programmatically and easily address them later on.
Other than the button generation we have another key function that I mentioned earlier, the button callback. Callback functions follow a slightly different syntax in that they natively pass along two arguments, the handle of the object whose callback is executing and the event data structure (see the documentation for more info). Because the function knows what UI object invoked it, we can make a pretty generic function.
Hopefully this helps!
Have you considered creating the ui in Java - undocumented matlab has some examples. Java would provide you nice LayoutManagers that will take care about resizing and more.

matlab GUIDE: storing data from loop in vector

I am new to matlab and i need some help. I am trying to make some program, where you can by 2 clicks on picture get a lenght of something. Basicly it works well, but got a problem when trying to algorytmize it. I use ginput to get coordinates and then pythagorean theorem to work with them and make important variable z2. And those variables I want to store in vector so basicly: I pressed push_button1 click twice on a picture and get some z2,now when i do the procedure again i want to store the new one with the old one in the same vector
[z2_old z2_new]. But basicly every time i tried to make something like this the old ones value is rewritten.
This is the code of my push button:
function pushbutton1_Callback(hObject, EventData, handles)
%counter - number of press (working right)
counter = get(hObject, 'UserData') + 1;
set(hObject, 'UserData', counter);
set(handles.text1, 'String', sprintf('%d', counter));
% - ginput part (working right)
c2 = ginput(2);
q3 = text(c2(1,1),c2(1,2),'X', ...
'HorizontalAlignment','center', ...
'Color', [1 1 0], ...
'FontSize',10);
q4 = text(c2(2,1),c2(2,2),'X', ...
'HorizontalAlignment','center', ...
'Color', [1 1 0], ...
'FontSize',10);
%creating the z2 variable(working right)
x2=c2(1,1)-c2(2,1);
y2=c2(1,2)-c2(2,2);
z2=sqrt(x2*x2+y2*y2);
% - loop for getting a vector (not ok)
for i=1:counter
z(i,1)=z2
end
So, basicly when I run the button first time and z2 got for example 130, second time 60, third time 210m I want to get z=[130 60 210], now I am still getting something like 1st press:z=[130], 2nd press: z=[60 60], 3rd press: z=[210 210 210], the old values are every time lost. I tried to fix it many ways but its still not working. Its only a small part of my work and i almost run out of time.
Can someone please tell me how should that loop look like? I tried z(end+1)=z2 , z=[z z2] , but the result is always the same.
Thanks for your help a lot. I really Appreciate it.
The issue is that with each click on pushbutton, it creates new values for z2. Even though the counter increments, but z2 is always the new value. So, you need to save z2 between clicks on the pushbutton. For that you have handles structure available for data storage between GUI callbacks. You need to make two changes -
Add this line inside the guiname__OpeningFcn before the handles structure is updated in guidata(hObject, handles); -
handles.z2 =[];
Edit the pushbutton callback to this -
x2=c2(1,1)-c2(2,1)
y2=c2(1,2)-c2(2,2)
z2=sqrt(x2*x2+y2*y2)
z = [handles.z2 z2]
handles.z2 = z;
guidata(hObject,handles);
Hope this works out for you, let us know!
Try this
Remove the for loop
Just write
z[z,z2]
This should add z2 to the end of the existing z every time.
In case it throws an error just first give z(0)=0; an initial garbage value to start with.

Saving GUI data from matlab in a 3D matrix

I'd like to save matrices which are input via GUI pushbuttons in a 3D matrix. for example: I click button 1 a 2-2 matrix is put in the first slice of the 3D matrix. I than click button 3 and a different 2-2 matrix is put in the second slice. SO on and so on. I hope this is clear enough. The problem I have is that I'm not an experienced programmer. I currently initialize a zeros matrix as follows in the opening func:
storageMatrix = ones(2,2,100);
setappdata(0, 'storageMatrix', storageMatrix);
I have put a function updateStorageMatrix in the main script like this, mind you this isn't finished yet.
function updateStorageMatrix
storageMatrix = getappdata(0, 'storageMatrix');
and than when I look at my code of pushbutton 1 for example it looks like this:
% --- Executes on button press in Add_Straightduct.
function Add_Straightduct_Callback(hObject, eventdata, handles)
%prompt command for k number and length
prompt = {'k0:','Length:'};
dlg_title = 'Straight Duct specs';
num_lines = 1;
SDelements = {'0','0'};
Straightduct = inputdlg(prompt,dlg_title,num_lines,SDelements)
%insert values in function
sizeStorageMatrix = size(getappdata(0,'storageMatrix')); %get size of the storage matrix
dimT = sizeStorageMatrix(1,3); %take the number of matrices
if dimT==1
straightDuct = straight_duct(str2num(SDelements{1}), str2num(SDelements{2}), Mach_Frange(1,1))
setappdata(handles.updateStorageMatrix,'storageMatrix', storageMatrix(1:2, 1:2, 1))=straight_duct(str2num(SDelements{1}), str2num(answer{2}), Mach_Frange(1,1))
dimT+1
else
setappdata(0,'storageMatrix', storageMatrix(1:2, 1:2, dimT+1))=straight_duct(str2num(SDelements{1}), str2num(answer{2}), Mach_Frange(1,1))
dimT+1
end
the straight_duct() is a function I used in the script when calculating the mufflers, I have several of those functions, I am not sure if that's the way to work when using GUI. I just hope you get the idea of what I'm trying to achieve and help me on my way. So I can actually make a UI for my script :)
This assumes you've initialized the storageMatrix elsewhere in the GUI like this...
handles.storageMatrix = zeros(2,2,100);
guidata(hObject,handles); % Must call this to save handles so other callbacks can access the new element "storageMatrix"
Then in your first button's callback...
% --- Executes on button press in Add_Straightduct.
function Add_Straightduct_Callback(hObject, eventdata, handles)
.
. % Whatever initializations you need to do
.
localStorageMatrix = handles.storageMatrix; %load the storageMatrix being used by other callbacks/functions
.
. % Whatever you need to do to generate the new 2x2 matrix "slice"
.
localStorageMatrix(:,:,end+1) = newSlice; % appends the new slice to the end of the, indexing using colons assumes newSlice is of the same first and second dimension as other slices in localStorageMatrix
handles.storageMatrix = localStorageMatrix; % overwrite the storageMatrix in handles with the contents of the new localStorageMatrix
guidata(hObject,handles); % save the handles struct again now that you've changed it
Alternatively, you could have just used the handles.storageMatrix throughout, without including a localStorageMatrix but I've included it for emphasis.

Is it possible to prevent an uitable popup menu from popping up? Or: How to get a callback by clicking a cell, returning the row & column index?

For an user interface I'm programming an uitable. The user chooses an option A,B or C in the first column and the suboption in the second column depends on what was chosen in the first, either A.1,A.2 or A.3 or B.1,B.2 or B.3 or the same for C
The code for the table can be found in Appendix A.
When the user first defines the main option, then automatically the suboptions are reduced accordingly to only valid choices. This is realized by evalulating the CellEditCallback for column 1 and resetting the ColumnFormat for column 2. (function modifySelection in Appendix B)
If the user now realizes he made a mistake and needs to edit a suboption another time, then the ColumnFormat is still set according to the previous edited main option and the valid choices are not available unless he re-chooes the main option another time. (see the blue highlighting in picture).
To resolve this, I also implemented the CellSelectionCallback calling the function justifySelection (in Appendix B), which is checking by selection, which option was chosen in column 1 to offer again the right suboptions for column 2. But as this callback reacts on selection, I need to select twice, one time to trigger the CellSelectionCallback and another to actually get my choices. For large tables, this can be very annoying!
So my question is:
Is there a way to prevent the popup menu in column 2 from popping up, until it found out what's the content of the according column 1, so it immediately offers the valid choices?
Or:
How could I detect a mouse click on a cell and get the row and column-index? But without invoking the following selection and popping up action?
I was already raking all available properties but didn't found anything which could be useful.
Maybe one could do something using the ButtonDownFcn, but how to get the cell indices? What about the BusyAction property, how can that be used for my purpose?
Any ideas?
I'm sorry in advance to bomb you with so much code, it's already the most minimal example, but fully executable, so you can try it out.
Appendix A/B
function fancyUitable
selector_1 = { 'A'; 'B' ; 'C' };
selector_2 = { 'first select first row!' };
h = figure('Position',[200 100 268 120],'numbertitle','off','MenuBar','none');
defaultData = repmat( {'select main option...', 'select suboption...'} ,5,1);
columnname = {'Option ',...
'Suboption '};
columnformat = { {selector_1{:}}, selector_2 };
columneditable = [true true];
t = uitable(h,'Units','normalized','Position',[0 0 1 1],...
'Data', defaultData,...
'ColumnName', columnname,...
'ColumnEditable', columneditable,...
'ColumnFormat', columnformat,...
'RowName',[],...
'CellEditCallback',#modifySelection,...
'CellSelectionCallback',#justifySelection);
set(h,'Tag','Config_figure')
set(t,'Tag','Config_table')
end
% **Appendix B**
% (part of the same function file)
function modifySelection(~,evt_edit)
if evt_edit.Indices(2) == 1
modifyPopup( evt_edit.Indices(1) );
end
end
function justifySelection(~,evt_select)
try %to surpress an unimportant error
if evt_select.Indices(2) == 2
modifyPopup( evt_select.Indices(1) );
end
end
end
and finally the single function modifyPopup which rewrites the Columnformat:
function modifyPopup( row )
id_group_1 = {'A.1';'A.2';'A.3'};
id_group_2 = {'B.1';'B.2';'B.3'};
id_group_3 = {'C.1';'C.2';'C.3'};
id_default = {'select main option first'};
myfigure = findobj('Tag','Config_figure');
config_data = get(findobj(myfigure,'Tag','Config_table'),'Data');
selector = config_data(row,1);
selector = selector{1};
config_format = get(findobj(myfigure,'Tag','Config_table'),'ColumnFormat');
switch selector
case 'A'
config_format{2} = id_group_1';
case 'B'
config_format{2} = id_group_2';
case 'C'
config_format{2} = id_group_3';
otherwise
config_format{2} = id_default;
end
set(findobj(myfigure,'Tag','Config_table'),'ColumnFormat',config_format)
end
Bounty: Why just +50? - I guess it's either not possible or the answer is easy, once one had the right initial idea. I'm not looking a for a complex workaround using java object properties etc. Thank you in advance!
I include the discussion from the comments here to keep the overview:
If you want to try it out, you can copy the code and follow these steps to reproduce the undesired behaviour:
select main option A in the first row.
the suboption in the first row then contains the choices A.1, A.2 and
A.3.
select main option B in the second row, therefore the choices for
the suboption in the second row are B.1, B.2 and B.3
BUT NOW you want to change the suboption in the first row (directly); you would expect to get the choices A.1, A.2 and A.3; but you don't. You get offered B.1, B.2 & B.3; - Because the last main option you selected was B (though in a diffrent row).
It seems that instead of looking for the last option, you should look at the relevant option. So either make sure that clicking on a
suboption does a 'lookup' to see which main option there is,
Thats exactly what I'm looking for! But how could I do that? How to
detect the click, get the column&row indices, set the right
ColumnFormat and then finally let the cell pop up. The only
possibility I see until now is the CellSelectionCallback, but it is
executed after the cell already popped up with the invalid choices.
I'd need a kind of ClickedCallback, like there is for pushbuttons
or make sure that selecting a main option only sets the suboptions for that row.
That's not possible, you can't set a suboption for a certain row as you need to modify ColumnFormat, which affects the whole table and not just one row.
I would not use a uitable; it's just not suited for this sort of thing.
Here's how I would do it:
function GUIdemo
%%// Construct GUI
%// Main figure
mainFig = figure;
set(mainFig, 'Color', get(0, 'DefaultUicontrolBackgroundColor'));
%// Create as many blocks as needed. The only thing you have to do is
%// figure out the "right" positions for each block
popupHandles = create_ui_blocks([
0.00 0.50 1.00 0.35
0.00 0.15 1.00 0.35]);
%// This OK button gathers all selected options, and just prints them.
uicontrol(...
'style' , 'pushbutton',...
'units' , 'normalized',...
'parent' , mainFig,...
'position', [0.4 0.01 0.2 0.1],...
'callback', #(~,~)getData(popupHandles),...
'string' , 'OK'...
);
%%// Helper functions
%// Create control blocks. Each block is composed of:
%// - a uipanel as container
%// - three radio buttons for the main selection
%// - a corresponding popup or the secondary selection
function popupHandles = create_ui_blocks(positions)
%// initialize
numBlocks = size(positions,1);
panels = zeros(numBlocks,1);
groups = zeros(numBlocks,1);
radios = zeros(numBlocks,3);
popups = zeros(numBlocks,1);
%// Build each block
for ii = 1:numBlocks
%// The container
panels(ii) = uipanel(...
'parent' , mainFig,...
'position', positions(ii,:)...
);
%// The radio buttons
groups(ii) = uibuttongroup(...
'parent' , panels(ii),...
'position', [0.05 0.05 0.45 0.9]...
);
radios(ii,1) = uicontrol(...
'style' , 'radio',...
'units' , 'normalized',...
'string' , 'A',...
'parent' , groups(ii),...
'position', [0.05 0.66 0.9 0.25]...
);
radios(ii,2) = uicontrol(...
'style' , 'radio',...
'units' , 'normalized',...
'string' , 'B',...
'parent' , groups(ii),...
'position', [0.05 0.33 0.9 0.25]...
);
radios(ii,3) = uicontrol(...
'style' , 'radio',...
'units' , 'normalized',...
'string' , 'C',...
'parent' , groups(ii),...
'position', [0.05 0.0 0.9 0.25]...
);
%// Initially, nothing's selected
set(groups(ii), 'SelectedObject',[]);
%// The popups
popups(ii) = uicontrol(...
'style' , 'popup',...
'units' , 'normalized',...
'parent' , panels(ii),...
'position', [0.55 0.4 0.4 0.2],...
'string' , 'Select main option',...
'enable' , 'off'...
);
%// On changing radiobutton, correct the string list of the popups
set(groups(ii),'SelectionChangeFcn', #(~,~)selectionChangeCallback(ii));
%// This is needed by the OK button callback
popupHandles = popups;
end
%// What happens when clicking a radio button?
%// NOTE: this is a doubly-nested function
function selectionChangeCallback(num)
switch get(groups(num), 'SelectedObject')
case radios(num,1)
set(popups(num), 'string', {'A.1', 'A.2', 'A.3'}, 'enable', 'on');
case radios(num,2)
set(popups(num), 'string', {'B.1', 'B.2', 'B.3'}, 'enable', 'on');
case radios(num,3)
set(popups(num), 'string', {'C.1', 'C.2', 'C.3'}, 'enable', 'on');
otherwise
%// ...
end
end
end
%// What happens when pressing the OK button?
function data = getData(popupHandles)
data = char(cellfun(#(x,y)x{y}, ...
get(popupHandles, 'String'),...
get(popupHandles, 'Value'),...
'UniformOutput', false)) %#ok<NOPRT> //
end
end
Output in the MATLAB command window when pressing "OK":
data =
A.1
B.1
The layout is of course still crude, but you get the idea. Of course, the radio buttons can also be replaced by a popup (more compact), three pushbuttons, or whatever else you like.
The contents of the popups are not related to each other, which is exactly the problem with the uitable approach. In this GUI, changes in the popup's contents can be instantaneous when changing a radio button, simply because you have better control over how to deal with changes.
A programming note: I personally don't like it when handles of individual components in what I treat as a "block" are floating around in the top-level function, which is why I use doubly-nested functions -- it's kind of like encapsulation. Now, when used outside of classes, this is not everyone's cup of tea, so you might want to convert them. Of course, all nested functions are trivially converted to subfunctions; you just have to manually pass a lot more information around.
With this approach, you lose some functionality (the ability to re-size your UI elements), but you gain intuitive behavior of the GUI controls. When these are the choices, I've been trained to develop towards the latter option. The nice bells and whistles will only impress the end-user the first few times round, but the program's basic functionality will become more and more important with increased usage. As you noted yourself, this buggy behavior gets annoying when you have to use the tool a lot; I'd say, drop the resizability in favor of improved control behavior.
Though I highly appreciate the effort and the solution of Rody Oldenhuis and he definetely deserved the award, his solution would have required a lot of changes in my code, so I kept trying to find a simpler solution. Here it is, finally 99% bug-free.
(all code parts within on function script)
function fancyUitable
close all
%basic properties
line_height = 21.32;
table_height = 6*line_height;
lh = line_height/table_height;
cw = 200; %columnwidth
h = figure('Position',[200 100 2*cw+2 table_height],...
'numbertitle','off','MenuBar','none');
%header
uitable(h,'Units','normalized','Position',[0 1-lh 1 lh],...
'ColumnWidth', {cw cw},...
'ColumnName', {'Option','Suboption'},...
'RowName',[]);
%button (currently no icon) to store table
tbar = uitoolbar(h);
uipushtool(tbar,'ClickedCallback',#store);
% addrow(figurehandle,number of row, percentage lineheight)
% every function call creates a new row, later dynamically
addRow(h,1,lh);
addRow(h,2,lh);
addRow(h,3,lh);
addRow(h,4,lh);
addRow(h,5,lh);
end
function edit(src,evt)
if evt.Indices(2) == 1
modifyPopup( src,evt.Indices(1) );
end
% disables cell selection highlighting, when one jumps to next table,
% a bit laggy though
fh = get(src,'parent');
copyobj(src,fh);
delete(src);
end
function modifyPopup( src,row )
id_group_1 = {'A.1';'A.2';'A.3'};
id_group_2 = {'B.1';'B.2';'B.3'};
id_group_3 = {'C.1';'C.2';'C.3'};
id_default = {'select output file first'};
config_data = get(src,'Data');
selector = config_data(row,1);
selector = selector{1};
config_format = get(src,'ColumnFormat');
switch selector
case 'A'
config_format{2} = id_group_1';
case 'B'
config_format{2} = id_group_2';
case 'C'
config_format{2} = id_group_3';
otherwise
config_format{2} = id_default;
end
config_data = { selector , 'select suboption...' }; %reset column 2
set(src,'Data',config_data);
set(src,'ColumnFormat',config_format);
end
function addRow(fh,k,lhp)
selector_1 = { 'A'; 'B' ; 'C' };
selector_2 = { 'first select first row!' };
defaultData = {'select main option...', 'select suboption...'};
columnformat = { {selector_1{:}}, selector_2};
columneditable = [true true];
th = uitable(fh,'Units','normalized','Position',[0 1-(k+1)*lhp 1 lhp],...
'Data', defaultData,...
'ColumnName', [],...
'ColumnWidth', {200 200},...
'ColumnEditable', columneditable,...
'ColumnFormat', columnformat,...
'RowName',[],...
'Tag','value',...
'UserData',k,...
'SelectionHighlight','off',...
'CellEditCallback',#edit);
end
function store(~,~)
ui = findobj(0,'Type','uitable','Tag','value');
L = numel(ui);
output = cell(L,2);
order = zeros(L,1);
for ii=1:L;
output(ii,:) = get(ui(ii),'Data');
order(ii) = get(ui(ii),'UserData');
end
[~,idx] = sort(order); %as order of handles unequals displayed order
assignin('base','output',output(idx,:));
end
brings up:
The solution is to use the Cell Selection Callback with two UITables in your GUI. Make the first table hold the data of {'a','b','c'} then in the cell selection callback, make the second UITable visible and set its data based on the cell selection properties of the first UITable. This link should have everything you need if you look down at the line 'A little hack not needing findjobj'
http://www.mathworks.com/matlabcentral/newsreader/view_thread/306392

How to retrieve data point into edit text from matlab workspace to gui?

I have 8x1 cell matrix in my matlab workspace called textdata. It contains tickers in each row. How do I use pushbutton and edit1_Callbacks to program a this basic data point retrieval operaton (what is the code and where do I type it? No fancy stuff, just want to know how to import the textdata into gui and with the push of a buttun retrieve the first ticker into the edit text box (1 data point from first row of textdata)?
You can use the Matlab function evalin to retrieve a workspace variable from your GUI.
The following example GUI demonstrates this, you can probably expand from this starting point:
% GUI
function so_wsgui
figure('units','normalized',...
'position',[0.15 0.15 0.7 0.7],...
'color',[1 1 1]*0.5,...
'numbertitle','off',...
'menubar','none',...
'toolbar','none',...
'tag','figure');
data=guihandles(gcf);
uicontrol('parent',data.figure,...
'style','pushbutton',...
'string','Import',...
'units','normalized',...
'position',[0.1 0.85 0.8 0.05],...
'callback',#import_callback);
uicontrol('parent',data.figure,...
'style','edit',...
'horizontalalignment','center',...
'backgroundcolor',[1 1 1],...
'units','normalized',...
'position',[0.1 0.5 0.8 0.05],...
'tag','text');
data=guihandles(gcf);
guidata(gcf,data);
end
% Callbacks
function import_callback(obj,event) %#ok
data=guidata(gcbf);
try
wsvar=evalin('base','textdata');
set(data.text,'string',wsvar{1});
catch exception
set(data.text,'string',['Error: ' exception.identifier]);
end
end
However you have to be careful with this because nothing garantees you that the variable exists or that it is a cell array, so you must be cautious. This is not really the usual way to pass data to a GUI.