Sign up ×

I am trying to update a variable value permanently in Matlab. I want to make a GUI where there will be a button which would have variable's value (e.g. k = 3), I will add that with 4 and show the value (e.g. 7) in a text box. Now the value (i.e. 7) will be the new value of k. So if again I click on the button it would show the updated value in text box (e.g. k=7, in text box: 7+4 =11). I am new in matlab and tried many ways to solve it. The simplest way was:

  function addition_Callback(hObject, eventdata, handles)
  k =3;
  k = 4+k;
  set(handles.value,'String', ...   %here value is the name of the text box
  [ k ]);

but each time I am clicking the button, it is starting from very beginning as assumed. How can I declare the variable so that it will work the way I just mentioned?

share|improve this question
You need to post the entire code of your function for the button click please. (also btw you could just go k = k + 4, you don't need that temp a variable) –  Dan Dec 18 '13 at 9:02
Thanks for the suggestion. changed as you said. –  Bee Dec 18 '13 at 9:27
So you are saying every time you click you get the value 7 right? That's because you are never passing in the current value but always resetting it to start from k=3. –  Dan Dec 18 '13 at 9:30
Yes that's what I am saying and I understand the reason as each time I am clicking, it is starting from the beginning. So my query was: is there any way to permanently erase the value of k [i.e. k=3] until my GUI is closed or can I use some other way to put aside the previous value of k and work with only the current value of k. [i.e. 7, 11, 15, 19, 23.....] –  Bee Dec 18 '13 at 9:37
So I think you're looking for something like this:… –  Dan Dec 18 '13 at 9:41

1 Answer 1

up vote 1 down vote accepted

Why not simply use the currently displayed string as starting point?

function addition_Callback(hObject, eventdata, handles)
  % get the currently displayed value and convert it to a number
  current = str2double(get(handles.value, 'String'));
  % current will be nan if the string is empty or not a valid number
  if isnan(current)
      current = 3; % start or fallback-value
  new = 4+current;
  set(handles.value,'String', new)   %here value is the name of the text box
share|improve this answer

Your Answer


