Question

The code:

function send_Callback(hObject, eventdata, handles)
         key = 3; %this is the variable
         current = str2double(get(handles.value, 'String'));
         %value is a textbox where user put input
         newValue = key+current;
         set(handles.listbox1,'String', newValue)
         %listbox1 is a listbox to show the value
         %Now I want to replace the value of key by the value of current
         %key = current - something like this

What I am expecting: I am expecting the key will be replaced with the current value (e.g. 8). So that when I will again input something in my textbox (e.g. 12), it will be added with previous current value (e.g. 8, and then newValue will be 12+8).

What I am getting: Whenever I am clicking the button the key is set to 3 every time and adding with current value. But I want the key to be changed permanently or atleast be put aside after first use.

Obligations: The key value which is shown as 3 here has to be exactly as 3 when I am starting my program and clicking the send button for the first time. Actually I will be using the above concept for encryption/decryption later on [for building block I am using just an addition], so for the first time my key has to be known to the device, then the user can change it when she wants.

Additional comment: My previous post was almost similar but my requirement of updating the variable was still unfulfilled. The purpose was served though that time.

Was it helpful?

Solution

You need a global variable for this.

Inside your main script, declare a global variable and assign 3 to it.

global key = 3;

Inside the function, first tell Matlab that you are using the global variable key. Then modify it as you want.

function send_Callback(hObject, eventdata, handles)
     global key;   % Tell matlab to use the global varaible key instead of a new local variable.
     current = str2double(get(handles.value, 'String'));
     [newValue, key] = [key + current, current];
     % Do something with the newValue here...
end

OTHER TIPS

If you don't want to use a global variable, add to your GUI initialization function:

handles.key = 3
guidata(hObject, handles)

And then use handles.key in place of key in your code, making sure to call guidata(hOjbect, handles) after the final assignment and before the function returns. See http://www.mathworks.com/help/matlab/ref/guidata.html , basically after setting a "variable" you're storing in handles (actually a field of the handles structure, I believe), you have to call guidata() to actually save the change. This implies you're also passing hObject; I find the whole procedure to be such a pain I just revert to globals.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top