Matlab 结构数组:字符串不起作用
Matlab Array of structures: string not working
我正在从文件中读取输入并将其导入我的数据到 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
但是没有什么可以解决这种情况,只有字符串不起作用。
我没有明确地将数据声明为结构,即在代码中没有任何地方包含 "struct" 单词,但 Matlab 显然会自动将其理解为 "Array of structures"。
这里有什么遗漏的提示吗?
非常感谢所有评论!
问题是 employee(k).name
是一个单元格(用 iscell(employee(1).name)
检查)并且格式字符串 %s
不知道如何处理它。
它是一个单元格的原因是因为 strread
return 是一个单元格数组。要从结果 (parts
) 中获取一个元素,您需要使用 {}
索引,其中 return 是一个字符串,而不是 ()
索引 return 一个单元格。
employee(i).name = parts{1};
我正在从文件中读取输入并将其导入我的数据到 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
但是没有什么可以解决这种情况,只有字符串不起作用。
我没有明确地将数据声明为结构,即在代码中没有任何地方包含 "struct" 单词,但 Matlab 显然会自动将其理解为 "Array of structures"。
这里有什么遗漏的提示吗?
非常感谢所有评论!
问题是 employee(k).name
是一个单元格(用 iscell(employee(1).name)
检查)并且格式字符串 %s
不知道如何处理它。
它是一个单元格的原因是因为 strread
return 是一个单元格数组。要从结果 (parts
) 中获取一个元素,您需要使用 {}
索引,其中 return 是一个字符串,而不是 ()
索引 return 一个单元格。
employee(i).name = parts{1};