gpt4 book ai didi

matlab - 在非标量结构 matlab 中查找字符串

转载 作者:行者123 更新时间:2023-12-02 07:10:07 24 4
gpt4 key购买 nike

这是一个non-scalar structure在Matlab中:

clearvars s
s=struct;
for id=1:3
s(id).wa='nko';
s(id).test='5';
s(id).ad(1,1).treasurehunt='asdf'
s(id).ad(1,2).treasurehunt='as df'
s(id).ad(1,3).treasurehunt='foobar'
s(id).ad(2,1).treasurehunt='trea'
s(id).ad(2,2).treasurehunt='foo bar'
s(id).ad(2,3).treasurehunt='treasure'
s(id).ad(id,4).a=magic(5);
end

是否有一种简单的方法来测试结构 s 是否包含字符串“treasure”,而不必循环遍历每个字段(例如,通过变量的实际内容执行“grep”)?

目的是“快速而简单地”查看结构中是否存在字符串(无论在何处)。换句话说(对于 Linux 用户):我想使用“grep” ' 在 matlab 变量上。

我尝试了arrayfun(@(x) any(strcmp(x, 'treasure')), s)但没有成功,输出:

ans =

1×3 logical array

0 0 0

最佳答案

一种通用方法(适用于任何结构体数组s)是使用 struct2cell 将结构体数组转换为元胞数组。 ,测试是否有任何单元格 are equal 的内容到字符串 'treasure',并对包含结构的任何单元格递归地重复上述操作。这可以在 while loop 中完成如果找到字符串或没有剩余结构可供递归,则停止。这是作为函数实现的解决方案:

function found = string_hunt(s, str)
c = reshape(struct2cell(s), [], 1);
found = any(cellfun(@(v) isequal(v, str), c));
index = cellfun(@isstruct, c);
while ~found && any(index)
c = cellfun(@(v) {reshape(struct2cell(v), [], 1)}, c(index));
c = vertcat(c{:});
found = any(cellfun(@(c) isequal(c, str), c));
index = cellfun(@isstruct, c);
end
end

并使用您的示例结构s:

>> string_hunt(s, 'treasure')

ans =

logical

1 % True!

关于matlab - 在非标量结构 matlab 中查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45885811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com