how a matlab .m code can write text in a GUI textarea?
15 views (last 30 days)
Show older comments
Otavio Carpinteiro
on 15 May 2020
Answered: Otavio Carpinteiro
on 16 May 2020
Let's suppose a simple file "test.m" with the following code:
obj = app1;
for i = 1:10
fprintf('\ni = %d\n', i);
if i==1
str = num2str(i);
else
str = sprintf('%s\n%s', str, num2str(i));
end
obj.writeText('1', str); % line 10
obj.TextArea_2.Value = str; % line 11
end
"app1.mlapp" is a GUI class made through appdesigner. In its code I defined two textareas:
% Create TextArea_1
app.TextArea_1 = uitextarea(app.UIFigure);
app.TextArea_1.Position = [47 187 259 150];
% Create TextArea_2
app.TextArea_2 = uitextarea(app.UIFigure);
app.TextArea_2.Position = [335 187 259 150];
and defined a public function:
methods (Access = public)
function writeText(app, ind, text)
if ind <= length(2)
ta = ['TextArea_', ind];
ta.Value = text;
end
end
end
only line 11 prints in in TextArea_2. So, why doesn't line 10 print in TextArea_1 ???
thanks in advance.
PS: in the attached file "GUI-example.zip", it's included the 2 files "app1.mlapp" and "test.m".
4 Comments
Stephen23
on 16 May 2020
Putting pseudo-indices into variable names is a sign that you are doing something wrong.
Create one handle array:
app.TextArea(1) = uitextarea(app.UIFigure);
app.TextArea(2) = uitextarea(app.UIFigure);
and then use basic, simple, efficient indexing to access them, or even set / get for multiple objects/properties at once.
Accepted Answer
More Answers (1)
Walter Roberson
on 16 May 2020
length(2) is 1 and '1' < 1 is false, so you never execute the lines
ta = ['TextArea_', ind];
ta.Value = text;
If you did, then you get an error message, because ta would contain a character vector, and character vectors do not have a Value fieldname or property or method.
You should not be doing what you are trying to do. http://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
You should make app.Text_Area a vector that you index into.
3 Comments
Walter Roberson
on 16 May 2020
You can have the app designer generate TextArea_1 and TextArea_2 for you, but your initialization can also do
app.TextArea = [app.TextArea_1, app.TextArea_2];
after which you can index app.TextArea(idx).Value
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!