以 MATLAB/Octave 格式打印结构内容和字段名称



我需要将具有相应字段名称和每个结构元素周围的一些文本的结构内容打印到命令窗口。

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

感谢建议

在 GNU Octave 中(参见 Matlab 的 Wolfies anwer

):
box.apples = 25
box.cherries = 0.5
box.iron = 0.085
printf('There are %.3f kg of %s in the box n',
horzcat(struct2cell(box),fieldnames(box))'{:});

出现"105.000"是因为您以 %f 的形式输入"铁"。 检查一下(这应该可以解释你的奇怪结果):

printf ('%f', 'iron')

只需将我的 2¢ 添加到上述答案中即可。

"没有循环"不一定总是更快。特别是现在有了matlab的JIT-编译器来循环。因此,不要只是为了拥有单行而避免循环并最终以丑陋的代码高尔夫结束。更不用说,单行不一定等于矢量化。如果对速度有疑问,请做一个简单的测试用例基准测试。

此外,循环通常更具可读性,因此除非您通过避免它获得巨大的加速,否则通常不值得为了微优化而牺牲可读性。

话虽如此,以下是我编写该循环的方式:

for CellStr = fieldnames(box).'
Name = CellStr{1};
fprintf('There are %.3f kg of %s in the boxn', box.(Name), Name)
end

或者,如果您使用的是八度,八度专门提供了以下可爱的语法:

for [Val, Field] = box
fprintf('There are %.3f kg of %s in the boxn', Val, Field)
end

我的机器上的一些基准测试(八度,没有 JIT 编译,10000 次迭代后经过的时间):

one-liner in answers above = 0.61343 seconds
top loop shown above       = 0.92640 seconds
bottom loop shown above    = 0.41643 seconds <-- wins
loop shown in the question = 1.6744  seconds

因此,在这种特殊情况下,其中一种 for 循环方法实际上比单行方法更快


另请注意,box是 matlab/octave 中函数的名称;使用隐藏内置函数的变量名称通常是一个坏主意。您通常可以通过对变量使用大写字母来解决这个问题,或者只是在调用变量之前查找该名称的函数

此方法应该适用于 MATLAB 和 Octave:

c = vertcat(struct2cell(box).',fieldnames(box).');
fprintf('There are %.3f kg of %s in the box n', c{:});

在 MATLAB 中,必须在语句末尾加上括号()使用它们的位置。所以你不能做

c = struct2cell(box){:};

并且必须这样做

c = struct2cell(box);
c = c{:};

MATLAB 还要求您使用fprintf,而不是printf。您可以在此处看到一些语言差异。


最新更新