【问题标题】:Invalid field name in matlabmatlab中的字段名称无效
【发布时间】:2013-11-29 05:24:13
【问题描述】:

我有一个函数可以接收一个人的个性

function person = prompt_person ()
name = input ( ' Whats your name ? ' , 's' ) ;
day = input ( ' What day of the month were you born ? ') ;
month = input (' What month were you born ? ') ;
year = input ( ' What year were you born? ') ;
phone = input ( ' Whats your telephone number ? ') ;
date_of_birth = struct ('day', day, 'month', month, 'year', year) ;
person = struct ( 'name' , name, 'date_of_birth' , date_of_birth , 'phone' , phone ) ;
end

但我不断收到错误消息“Invalid field name "name"”、“prompt_person 中的错误消息(第 8 行)而且我不知道出了什么问题,因为我尝试创建一个更简单的小测试函数:

function [out] = tes( )
word=input('Insert word here ','s');
num=input('Insert number here ');
out= struct('Number1', word, 'Number2', num);
end

而且它工作得很好,尽管它似乎与在第一个函数中让我陷入 toruble 的代码完全相同。有什么想法吗?

【问题讨论】:

  • 尝试使用personName作为变量名。
  • 无法在此处重现...您使用的是哪个 MATLAB 版本?
  • 我正在使用 Matlab r2013a

标签: matlab struct field


【解决方案1】:

我尝试按照建议将变量名称更改为 personName,但我无意中发现了问题所在: 结果我需要使用一个变量名,'' 和文本之间没有空格。

例如'PersonName' 而不是 'PersonName'。

【讨论】:

    【解决方案2】:

    您可以考虑使用strtrim 从字符串中去除前导和尾随空白。例如:

    >> name = ' John Doe   ';
    >> name = strtrim(name)
    name =
    John Doe
    

    如果您需要删除所有空格,请尝试strrep(name,' ','')

    >> name = strrep(name,' ','')
    name =
    JohnDoe
    

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 2016-03-06
      • 2021-01-13
      相关资源
      最近更新 更多