打印结构的所有元素

时间:2015-05-14 04:01:37

标签: matlab

我正在接近Matlab,我有一个带结构的函数:

function [out] = struct1()

Account(1).name = 'John';
Account(1).number = 321;
Account(1).type = 'Current';

%.......2 to 9 

Account(10).name = 'Denis';
Account(10).number = 123;
Account(10).type = 'Something';

for ii= 1:10
out=fprintf('%s\n','%d\n','%s\n',Account{ii}.name, Account{ii}.number,Account{ii}.type);
end
end

上面的代码给出了一个错误:“来自非单元格数组对象的单元格内容引用。”

如何输出此类结构的所有元素以使用“fprintf”获取此输出?

  

姓名:'John'

     

号码:321

     

输入:'当前'

          ...... 2 to 9
     

名称:'Denis'

     

号码:123

     

输入:'Something'

1 个答案:

答案 0 :(得分:3)

您使用{}索引结构数组的元素,这些元素仅用于单元格数组。简单的()可以正常使用。

此外,由于您在formatspec中有换行符,因此您应该将所有三个字符串组合在一起。

示例:

formatspec = 'name: %s\nnumber: %d\ntype: %s\n';
for ii= 1:10
    out=fprintf(formatspec,Account(ii).name,Account(ii).number,Account(ii).type);
end
相关问题