我需要在命令窗口打印一个结构体的内容,其中包括对应的字段名和每个结构元素周围的一些文本。
例如:
问题 - 有没有一种方法可以不使用循环来实现这个目标?
代码:
循环返回的输出正是我想要的:
例如:
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
欢迎提出建议
iron
中缺失的i
,因为char(105)='i'
,同样地,char(99)='c'
来自于'cherries'
。 - Wolfie