MATLAB: How to add and remove a row from a Table in the GUI

add rowguiguideremove row

Hey everybody,
I am working on project in matlab, and i first have to add and remove a row from a table in the GUI
after contructing the different items to the GUI , I wrote the code the following way:
% --- Executes just before untitled is made visible.
function untitled_OpeningFcn(hObject, eventdata, handles, varargin)
% Choose default command line output for untitled
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% --- Outputs from this function are returned to the command line.
function varargout = untitled_OutputFcn(hObject, eventdata, handles)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in add.
function add_Callback(hObject, eventdata, handles)
data = get(handles.uitable1, 'data');
data(end+1,:) = 0;
set(handles.uitable1, 'data', data);
% --- Executes on button press in remove.
function remove_Callback(hObject, eventdata, handles)
data = get(handles.uitable1, 'data');
data(end-1,:);
set(handles.uitable1, 'data', data);
but it is somehow not working, the following error statment show up when I click on the button "Add" and the button "remove" does not respond at all!
What I am doing wrong ?
As you might have notice, I derived the code to "remove" from the one to "add", is that the right way to do ?
thank you in advance,
Paul

Best Answer

You have coded the add callback under the assumption that when you fetch the data from the uitable that you will get back a numeric matrix. Numeric matrices are one of the two ways that you can store the data for a uitable, with the other way being cell array (one cell entry for each table entry). You need to know which way your empty table has been initialized, [] or {}. Or you could find out which one you currently have and make the conversion:
data = get(handles.uitable1, 'data');
if iscell(data); data = cell2mat(data); end
data(end+1,:) = 0;
set(handles.uitable1, 'data', data);
Your remove button is responding and doing what you programmed it to do. You have
data = get(handles.uitable1, 'data');
data(end-1,:);
set(handles.uitable1, 'data', data);
The second line of that,
data(end-1,:);
requests that the data in the second-last row be fetched into the current expression. And then the semi-colon at the end of the line says to do nothing with the current expression: if there were no semi-colon there then the result would be to display the current expression. Notice that you do not change your data before storing it back. Hint:
data(K,:) = []; %delete row K