Keep track of variable value in gui
3 次查看(过去 30 天)
显示 更早的评论
I am designing a program with GUIDE that simulates a coin toss game. It has 3 components:
+ A static text box, called text1 to keep track of your current balance.
+ An editable text box, called text2 so that you can type in the amount you want to bet.
+ A push button, called button1 to simulate a coin toss.
This is what I have tried:
%first, I used the Property Inspector on text1 to change its string from "Static text" to "1000"
%This way, the player starts the game with $1000
Current_Balance=str2double(get(handles.text1,'string'));
%Then, I acquire the bet amount from text2:
Bet=str2double(get(handles.text2,'string'));
%Next, to simulate a coin toss:
result=binornd(1,0.5);
if result==0;
Current_Balance=Current_Balance - Bet;
else Current_Balance=Current_Balance + Bet;
end
%I tried to update the value of Current_Balance with the next code.
%This is where the error message pops up;
set(handles.text1,'string',Current_Balance);
What I am trying to do is to calculate and show the new result Current_Balance each time a button is pressed. Any ideas?
1 个评论
Jan
2017-3-25
You mention an error message, but keep the message as your secret. Please reveal it, such that we do not have to guess it. :-)
回答(2 个)
Jan
2017-3-25
编辑:Jan
2017-3-25
Current_Balance = str2double(get(handles.text1, 'string'));
Now Current_Balance is a double array, most likely a scalar. You perform some arithmetic operations with it, and then:
set(handles.text1, 'string', Current_Balance);
tries to set the 'string' value with a double scalar. I guess you want:
set(handles.text1, 'string', num2str(Current_Balance));
or
set(handles.text1, 'string', sprintf('%.2f', Current_Balance));
to provide a string.
2 个评论
Jan
2017-3-26
The error message is clear: In this piece of code:
function buttonC_Callback(hObject, eventdata, handles)
set(handles.text1,'string',Current_Balance);
The variable "Current_Balance" is not defined. It was created in another callback, but the variables are not shared between functions.
The topic of sharing variables between callback is discussed frequently in this forum, therefore searching in the forum is a good idea. See e.g.:
- https://www.mathworks.com/matlabcentral/answers/102591-what-is-the-difference-between-application-data-guidata-and-userdata-in-matlab
- https://www.mathworks.com/matlabcentral/answers/330303-why-is-not-the-handles-variable-updated
- https://www.mathworks.com/matlabcentral/answers/38419-get-value-from-popup-menu-and-use-it-in-different-function
- ...
Nguyen Quang
2017-3-31
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!