似乎arrayfun和string()之间存在冲突 [英] Seeming conflict between arrayfun and string()

查看:91
本文介绍了似乎arrayfun和string()之间存在冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够方便地确保结构数组的字段仅包含字符串(而不包含字符数组).例如,

I am hoping to be able to conveniently make sure a field of a structure array contain only strings (and not character arrays). For example,

S(1).f='abc'; S(2).f='asdfa'; S(3).f="aegwer";

如果有的话

setfield(S(1),'f',string(S(1).f))

S(1).f将按预期成功转换为"abc".

S(1).f will be successfully converted to "abc" as expected.

但是

arrayfun(@(s)setfield(s,'f',string(s.f)),S)

不仅无法将'f'下的所有字段值都设置为字符串,而且实际上将'f'下的所有字段值都转换为字符数组.

not only fails to set all field values under 'f' to strings but actually convert all field values under 'f' to character arrays.

为什么arrayfun使string()成为char()?还是其他?

Why does arrayfun make string() into char()? Or is it something else?

我正在使用的MATLAB版本:R2018a

MATLAB version I am using: R2018a

推荐答案

此处的问题是 arrayfun 不要修改原始对象S(即,结构没有类似引用的行为).他们创建一个新的修改后的对象并返回它.您必须用此返回值覆盖S才能对其进行更新:

The problem here is that setfield and arrayfun do not modify the original object S (i.e. there is no reference-like behavior for structures). They create a new modified object and return it. You would have to overwrite S with this returned value for it to be updated:

S = arrayfun(@(s) setfield(s, 'f', string(s.f)), S);

这篇关于似乎arrayfun和string()之间存在冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆