Matlab GUI - Counter update through Pushbutton

Hey MatLabers,
I am creating a GUI via the GUI editor in Matlab. However, trying to test how the pushbutton works, I was unable to make it increment a counter every time it is pressed and output the result on a static text.
Here is the part of the code in question, I thought it would be as simple as:
function Simulate_Callback(hObject, eventdata, handles)
Counter =0;
Counter = Counter +1;
set(handles.Counter ,'String',Counter);
the Counter object is just a static text.
Any idea guys?! Any help is greatly appreciated!
Thanks a lot!

 採用された回答

Image Analyst
Image Analyst 2012 年 12 月 24 日

1 投票

Your counter will always be 1, obviously. You need to get the value, not set it to zero.
% Read current text and convert it to a number.
currentCounterValue = str2double(get(handles.Counter, 'String'));
% Create a new string with the number being 1 more than the current number.
newString = sprintf('%d', int32(currentCounterValue +1));
% Send the new string to the text control.
set(handles.Counter, 'String', newString );

4 件のコメント

Qfin
Qfin 2012 年 12 月 24 日
Works as a charm! Thank you so much for your time buddy!! :)
Rae Cheong
Rae Cheong 2018 年 12 月 19 日
how can i reset the counter value to zero when the counter number exceed value of 32?
Image Analyst
Image Analyst 2018 年 12 月 19 日
Try this:
% Read current text and convert it to a number.
currentCounterValue = str2double(get(handles.Counter, 'String'));
nextValue = currentCounterValue + 1;
if nextValue >= 33
nextValue = 0;
end
% Create a new string with the number being 1 more than the current number.
newString = sprintf('%d', int32(nextValue));
% Send the new string to the text control.
set(handles.Counter, 'String', newString );
Rae Cheong
Rae Cheong 2018 年 12 月 21 日
Thank you so much!!! It saves me!!!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeEnvironment and Settings についてさらに検索

質問済み:

2012 年 12 月 24 日

コメント済み:

2018 年 12 月 21 日

Community Treasure Hunt

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

Start Hunting!

Translated by