Making a matlab GUI. Display all values taken from an iterative loop on a static Text

1 回表示 (過去 30 日間)
Evans Gyan
Evans Gyan 2018 年 1 月 30 日
コメント済み: Jan 2021 年 6 月 21 日
hello guys, Am making a matlab GUI and i want the results to appear in a vertical format on a static textbox. This is my code
k = 15;
n = 1;
while k > n
q = mood(k,2);
if q == 0
k = k / 2;
else k = (k * 3) + 1;
end
for answer = k
%This format should display on my textbox
%disp(answer); %does not show on static textbox.
set(handles.mytext, 'String', answer)
end
end
I want the results to appear like this in a static textbox
k = 15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1 But the above code display only the last value. Thanks in advance
  1 件のコメント
Adam
Adam 2018 年 1 月 30 日
k is always a scalar so
for answer = k
will only run once. If it did run more than once you are still just overwriting what is already in the text box though anyway.
Storing all the answers you want and using something like
doc sprintf
on the whole thing rather than using a for loop would seem a better approach.

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

採用された回答

Jan
Jan 2018 年 1 月 30 日
編集済み: Jan 2018 年 1 月 30 日
k = 15;
n = 1;
i = 0;
allK = [];
while k > n
if mod(k, 2) == 0 % Not "mood"!
k = k / 2;
else
k = (k * 3) + 1;
end
i = i + 1;
allK(i) = k; % A warning will appear in the editor
end
set(handles.mytext, 'String', sprintf('%d\n', allK));
Now allK grows iteratively. This is very expensive if the resulting array is large, e.g. for 1e6 elements. For your problem, the delay is negligible. A pre-allocation is not trivial here, because you cannot know how many elements are created by this function. But it is better to pre-allocate with a poor too large estimation:
allK = zeros(1, 1e6); % instead of: allK = [];
set(handles.mytext, 'String', sprintf('%d\n', allK(1:i)));
Alternatively you can assign a cell string to the 'String' property also instead of inserting line breaks:
set(handles.mytext, 'String', sprintfc('%d', allK(1:i)));
  3 件のコメント
Muhamad Luqman Mohd Nasir
Muhamad Luqman Mohd Nasir 2021 年 6 月 21 日
@Jan hello Sir can you inspect my question (which have already been posted) since i have also encounters almost the same problem as this.
Jan
Jan 2021 年 6 月 21 日
Please do not advertise questions in comments of other questions. Imagine the clutter, if every user does this.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by