【问题标题】:Matlab Array of structures: string not workingMatlab结构数组:字符串不起作用
【发布时间】:2016-10-18 12:31:00
【问题描述】:

我正在从文件中读取输入并将其导入到我的数据中以在 Matlab 中运行:

    parts = strread(tline,'%s','delimiter',';')       
    employee(i).name = parts(1);
    employee(i).salary= str2double(parts(2));

然后我尝试打印出来:

for i = 1:3
 fprintf('salary: %.2f\n',employee(i).salary);
 fprintf('employee name: %s\n',employee(i).name);
end

工资打印没有问题。但是对于变量“name”,它给出了一个错误:

Error using fprintf
Function is not defined for 'cell' inputs.
fprintf('employee name: %s\n',employee(i).name);

我找了一些其他的例子:

access struct data (matlab)

How do I access structure fields dynamically?

Matlab Error: Function is not defined for 'cell' inputs

How do i define a structure in Matlab

但是没有什么可以解决这种情况,只有字符串不起作用。

我没有明确地将数据声明为结构,即在代码中没有包含“结构”一词的地方,但 Matlab 显然自动将其理解为“结构数组”。

这里可能缺少什么提示?

高度赞赏所有cmets!

【问题讨论】:

  • 鉴于错误消息,我认为employee(i).namecell 而不是charclass(employee(i).name) 返回什么?
  • 我认为employee(i).name 是一个单元格。所以看看你能不能做str = employee(i).name{1}然后用str
  • 返回:ans = cell
  • 所以...这意味着parts 可能是一个cell 数组,当将数据拉入employee 时,您需要access data in a cell array
  • @ParagS.Chandakkar - 谢谢!有用。无论如何避免使用 str 的需要?

标签: matlab struct cell matlab-struct


【解决方案1】:

问题是employee(k).name 是一个单元格(检查iscell(employee(1).name)),格式字符串%s 不知道如何处理。

之所以是单元格,是因为strread返回的是一个单元格数组。要从结果中获取元素 (parts),您需要使用返回字符串的 {} 索引,而不是返回单元格的 ()

employee(i).name = parts{1};

【讨论】:

  • 感谢您的最佳回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多