matlab循环遍历struct结构体

作者:matrix 被围观: 12,676 次 发布时间:2019-06-27 分类:零零星星 | 2 条评论 »

这是一个创建于 1767 天前的主题,其中的信息可能已经有所发展或是发生改变。

图片4911-matlab循环遍历struct结构体
matlab网络请求操作完成之后需要对返回数据读取,操作时候出现的问题就是无法循环struct数据。
因为接口一般以json数据格式返回,matlab会把Object结构处理为struct数据而无法循环读取。很多字段的时候我可不希望看到手写矩阵声明。
取struct长度的sizelength都无法正常返回其元素个数,听说它不是向量。

办法

fieldnames函数获取struct的字段field数据(返回为cell元胞数组)
之后用structName.(expression)这种操作获取动态的struct数组数据。比如struct.a等同于动态操作的struct.('a')
现在才知道文档上有,我TM竟然随便点括号猜出来的~

%声明方式1
%s = struct('a',11,'b',222)

%声明方式2
s=struct
s.a = 11
s.b = 222

% https://ww2.mathworks.cn/help/matlab/ref/struct.html

fileds = fieldnames(s);

for i=1:length(fileds)
    k = fileds(i);
    key = k{1};
    value = s.(key);

    disp(key)
    disp(value)
    disp('---')
end

% s.('a') %动态结构体引用

升级操作:自动生成对应变量

按照Struct字段自动生成对应的变量名和值

s = struct('a',11,'b',222)

fileds = fieldnames(s);

for i=1:length(fileds)
    k = fileds(i);
    key = k{1};
    value = s.(key);
    eval(['variable_',num2str(key) ' = ' num2str(value)])
end

说明:
使用eval函数动态创建variable_%s的变量。
本来在mathworks上看到有人发布过Structure fields to variables方法来自动处理struct,但是没有正版授权码 所以无法下载使用。

参考:
https://ww2.mathworks.cn/help/matlab/learn_matlab/types-of-arrays.html
https://ww2.mathworks.cn/help/matlab/ref/struct.html
https://www.ilovematlab.cn/thread-317868-1-1.html

https://ww2.mathworks.cn/matlabcentral/fileexchange/26216-structure-fields-to-variables

PEACE~

其他文章:
本文固定链接:https://www.hhtjim.com/matlab-to-iterate-over-struct-structure.html
matrix
本文章由 matrix 于2019年06月27日发布在零零星星分类下,目前没有通告,你可以至底部留下评论。
转载请注明:matlab循环遍历struct结构体-HHTjim'S 部落格
关键字:,

有2 条评论 »

  1. 1111111 1111111 2021-10-7 12:48:55 +0800#1

    你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的你们的

添加新评论 »

 🙈 😱 😂 😛 😭 😳 😀 😆 👿 😉 😯 😮 😕 😎 😐 😥 😡 😈 💡

插入图片

NOTICE: You should type some Chinese word (like “你好”) in your comment to pass the spam-check, thanks for your patience!