【发布时间】:2017-12-18 08:19:33
【问题描述】:
我需要将结构的内容与相应的字段名称和每个结构元素周围的一些文本打印到命令窗口。
即This something [fieldname(i)] has the value of [struct.fieldname(i) value] something.
头疼了半天后,我得到了一个表达式(不起作用)和一个循环(起作用)。
问题 - 有没有办法在没有循环的情况下做到这一点?
代码:
box.apples = 25
box.cherries = 0.5
box.iron = 0.085
% Loop method (works)
for i = (1:length(struct2cell(box))) ;
printf('There are %.3f kg of %s in the box \n', struct2cell(box){i}, fieldnames(box){i})
end
% Single expression method (doesn't work)
printf('There are %.3f kg of %s in the box \n', struct2cell(box){:}, fieldnames(box){:})
循环完全按照我的意愿返回合理的输出:
There are 25.000 kg of apples in the box
There are 0.500 kg of cherries in the box
There are 0.085 kg of iron in the box
只是 printf 表达式返回这个奇怪的输出:
There are 25.000 kg of in the box
There are 0.085 kg of apples in the box
There are 99.000 kg of herries in the box
There are 105.000 kg of ron in the box
建议
【问题讨论】:
-
在开始之前,您是否确保您的箱子已清空?您发布的代码中没有任何地方可以输入 99 和 105。
-
您提供的代码会出错,即使是循环版本?您使用的是哪个版本的 MATLAB?
-
@Flynn 我可以验证 105 神奇地出现了,我也得到了一些其他意想不到的值。我预计 105 来自
iron中缺少的i,如char(105) = 'i',类似地,char(99) = 'c'来自'cherries'。 -
@Wolfie 感谢关于字符转换的提示,我没有发现它!我在 Octave 4.2.1
标签: matlab struct printf octave cell-array