How to present the content of a field in a program?

4 Ansichten (letzte 30 Tage)
Csaba
Csaba am 31 Mai 2025
Bearbeitet: Image Analyst am 31 Mai 2025
I want to present the variables and their value from a structure in a program, just for information for the users.
Let's say:
a.a=234.5;
a.b=444;
a.s='This is an example';
a
if I run this code in the command window, I get the answer:
a =
struct with fields:
a: 234.5
b: 444
s: 'This is an example'
I want to reproduce this answer and put it in a text window in my program. I could not figure out how to do that.
Thanks for any help!

Akzeptierte Antwort

Image Analyst
Image Analyst am 31 Mai 2025
Bearbeitet: Image Analyst am 31 Mai 2025
Try this:
a.a=234.5;
a.b=444;
a.s='This is an example';
a
a = struct with fields:
a: 234.5000 b: 444 s: 'This is an example'
fn = fieldnames(a)
fn = 3×1 cell array
{'a'} {'b'} {'s'}
str = sprintf('a = \nstruct with fields:');
for k = 1 : numel(fn)
thisFieldName = fn{k};
if ischar(a.(thisFieldName))
% Print using %s
str = sprintf("%s\n\t%s: '%s'", str, thisFieldName, a.(thisFieldName));
else
% Print using %g
str = sprintf("%s\n\t%s: %g", str, thisFieldName, a.(thisFieldName));
end
end
str % Display in command window.
str =
"a = struct with fields: a: 234.5 b: 444 s: 'This is an example'"

Weitere Antworten (0)

Kategorien

Mehr zu Environment and Settings finden Sie in Help Center und File Exchange

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by