Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
我不知道这是怎么回事。我正在使用R2006b。在我提交错误报告之前,有人使用较新版本的任何机会都可以测试以查看他们是否有相同的行为?
代码:( bug1.m ) function bug1 S = struct('nothing',{},'something',{}); add_something(S, 'boing'); % does what I expect add_something(S.something,'test'); % weird behavior end function add_something(X,str) disp('X='); disp(X); disp('str='); disp(str); end 输出: >> bug1 X= str= boing X= test str= ??? Input argument "str" is undefined. Error in ==> bug1>add_something at 11 disp(str); Error in ==> bug1 at 4 add_something(S.something,'test'); 看起来S.something的空/虚无S.something允许它转移函数调用的参数。这似乎是非常不良的行为。在短期内,我想找到一个解决之道(我正在尝试制作一个函数,该函数将项目添加到最初为空的单元格数组中,该数组是结构的成员)。 编辑: 必然的问题:因此,有没有办法构造包含任何空单元格数组的struct文字? 回答: 正如您已经发现自己一样,这不是bug,而是“功能”。换句话说,这是STRUCT函数的正常行为。如果将空单元格数组作为字段值传递给STRUCT,则假定您想要具有给定字段名的空结构数组。 >> s=struct('a',{},'b',{}) s = 0x0 struct array with fields: a b 要将空单元格数组作为实际字段值传递,您可以执行以下操作: >> s = struct('a',{{}},'b',{{}}) s = a: {} b: {} 顺便说一句, 任何时候要使用STRUCT设置单元格数组的字段值时,都需要将其包含在另一个单元格数组中。例如,这将创建一个具有包含单元格数组和向量的字段的单个结构元素: >> s = struct('strings',{{'hello','yes'}},'lengths',[5 3]) s = strings: {'hello' 'yes'} lengths: [5 3] 但这会创建一个由两个结构元素组成的数组,分布单元格数组但复制矢量: >> s = struct('strings',{'hello','yes'},'lengths',[5 3]) s = 1x2 struct array with fields: strings lengths >> s(1) ans = strings: 'hello' lengths: [5 3] >> s(2) ans = strings: 'yes' lengths: [5 3] 更多&回答... |
![]() |
![]() |