档案交换一周

我们最好的用户提交

将结构写入文字

布雷特本周的选择是struct2str, 经过Marco Cococcioni

内容

结构的字符串

早在5月,肖恩wrote aboutdifferent File Exchange submissionsthat facilitate writing cell arrays to text. That was a useful post–and one that triggered an interesting follow-up discussion between Sean and me: namely, how would one write a struct to string? I write a lot of apps, and frequently want to put the contents of a struct into a listbox, for example. That can be challenging and frustrating.

当我建议肖恩(Sean)跟进一篇关于文字写作结构的文章时,他很快同意这很有趣。但是我认为他最初错过了我的观点:他建议我可以轻松地将结构的字段名称写入列表框,例如

lb = uicontrol('units',,,,“归一化”,,,,...'位置',[0.1 0.1 0.8 0.8],,...'风格',,,,'列表框'); d = dir('。\*'); lb.String = fieldnames(d);

“True,” I replied. “But I want the contents of the struct, not just the fieldnames.” His reply: “How about”

名称= {d(:)。名称};lb.String =名称;

Okay, that gets me the values of a single fieldname (in this example, ‘name’). However, assume that I get the file information for an image, and want to drop it all in a textbox or listbox:

structinfo = imfinfo('Street2.jpg'
structInfo = filename:'c:\ program文件\ matlab \ r2015a \ toolbox \ matlab \ demos \ ...'filemoddate:'22 -mar-2004 19:54:40'filesize:39920格式:'jpg'格式:'jpg'格式:'formatversion:''''格式:''格式:''格式:''格式:'宽度:640高度:480 BitDepth:24 colortype:'trueColor'格式'格式:''numberOfSamples:3 CodingMethod:'Huffman'CodingProcess:'sequential'评论:{}

我如何轻松地将所有这些信息放入列表框中?

struct2str

那就是Marco的文件所在:

lb.String = struct2str(structInfo);

我最初是用一个特别丑陋的为了循环,但是struct2strmakes it very easy. (Marco used some loops, too, but his code alleviates for me the pain of writing that loop. Thanks, Marco!)

这是一个挑战!

请注意,该字段中有几个空字段imfinfooutput struct in the usage above. Kudos and swag to the first person who replies with an elegant approach to automatically removing from the struct the fields with empty values. Use any approach you’d like, including other File Exchange submissions. What I’d like to see is this:

structinfo = rmfield(structinfo,{'FormatVersion',,,,“格式签名”,,,,'评论'})
structInfo = filename:'c:\ program文件\ matlab \ r2015a \ toolbox \ matlab \ matlab \ demos \ ...'filemoddate:'22 -mar-2004 19:54:40'filesize:39920格式:'jpg'width:640 width:640 width:640高度:480 BITDEPTH:24 colortype:“ trueColor”编号:3 CodingMethod:'Huffman'CodingProcess:'sequention'

…但是没有空旷字段的手动规范。让我知道您将如何处理这个问题,我将选择(并奖励)我最喜欢的那个。成为博客作者很好。)

注释?

与往常一样,欢迎评论!让我知道您的想法(或回应我的挑战)here,或留给Marco的反馈here




与Matlab®R2015A一起出版

|
  • 打印
  • 发送电子邮件

Comments

要发表评论,请单击here登录您的数学帐户或创建一个新帐户。