How to display all the while loop at static text? (matlab GUI)

조회 수: 1 (최근 30일)
Abraham Chan
Abraham Chan 2015년 4월 4일
답변: Geoff Hayes 2015년 4월 4일
How to display the while loop output at static text on GUI?
I want this output below
i=5
i=4
i=3
i=2
i=1
i=0
code
i = 5;
while i > 0
txt=fprintf('i = %d\n', i);
i = i - 1;
set(handles.ans, 'String',txt);
end
This code not working

채택된 답변

Jos
Jos 2015년 4월 4일
Hi Abraham,
try this (assuming you added a push button to start the program and 'ans' is your static text box). Since txt will be a growing variable the size of each line has to be the same length, so if you want to start at i=10 change num2str(i,'%d') to num2str(i,'%02d') although this will result in output
i=10
i=09
i=08
etc
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
i = 5;
txt = [];
while i > 0
txt=[txt;'i = ' num2str(i,'%d')];
i = i - 1;
set(handles.ans, 'String',txt);
end

추가 답변 (1개)

Geoff Hayes
Geoff Hayes 2015년 4월 4일
Abraham - if you step through this code (which is presumably in some sort of callback for one of your GUI controls) you would observe that the output from fprintf, txt, is a double and not a string (the carriage return/line break in the string is also problematic for single line text fields). Instead of the above, try the following with sprintf
for k=5:-1:1
txt=sprintf('k = %d', k);
set(handles.edit1, 'String',txt);
pause(1.0);
end
Note the use of the for loop and how we can decrement the counter. The pause for one second allows us to actually see the change to the edit control at each iteration of the loop.

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by