How to recalculate cell content in gui table using other cell content of the same table just like excel?

5 views (last 30 days)
Hi
I would like to ask a question. Using guide I create a gui table (4*3) with tag uitable1. I want matlab to do calculation on third column when the user enters numbers to first column by its own without using pushbutton. For example user enters 2 6 5 9 to column 1 and matlab automatically adds 10 to each number and shows 12 16 15 19 to the third column just like excel. I tried to write codes to
function uitable1_CellEditCallback(hObject, eventdata, handles)
olddata=get(handles.uitable1,Data);
newdata(:,3)=olddata(:,1)+10;
set(handles.uitable1,'data',newdata);
but unfortunately it does not work.
The error is:
Undefined operator '+' for input arguments of type 'cell'.
...
...
It would be appreciated if you could help.
Regards
Kourosh

Answers (1)

Jan
Jan on 11 Mar 2018
Edited: Jan on 12 Mar 2018
The error message is clear already: The variable olddata is a cell array, but you can apply the addition to numerical data only.
dataC = get(handles.uitable1, 'Data');
data = cell2mat(dataC(:, 3)) + 10;
dataC(:, 3) = num2cell(data);
% [EDITED] There way a typo in the names of the variables
By the way: You used ’ as quote, but in Matlab you need '. They look almost identical, but have different ASCII codes.
  17 Comments
Jan
Jan on 20 Mar 2018
@Kourosh Sharifi: Ah! The data are char vectors, not numbers. Then their ASCII codes are used instead of the values.
You need a str2double in addition.
% dataC = {'2','3','4'; '5','6','7'}
dataC = get(handles.uitable1, 'Data')
data = str2double(dataC(:, 1)) + 10
dataC(:, 3) = sprintfc('%g', data)
set(handles.uitable1, 'Data', dataC);
sprintfc is the same as sprintf, but creates a cell array. Unfortunately this very useful function is not documented and could be removed in the future. But it existed in Matlab for at least 18 years now, such that I expect it to be available in the future also. To be sure, you could use your own function:
function C = sprintfc_(Fmt, D)
C = cell(size(D));
for k = 1:numel(D)
C{k} = sprintf(Fmt, D(k));
end
end
Kourosh Sharifi
Kourosh Sharifi on 20 Mar 2018
Edited: Kourosh Sharifi on 24 Mar 2018
Hi,
Appreciate. It completely works. I was disapointed and decided not continue discussing. But you helped me a lot proffesionally and patiently. I hope this useful function will remain.
Thanks again
Kourosh

Sign in to comment.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!