formatted print of structures contents and fieldnames in matlab/octave

Viewed 563

I need to print to command window the contents of a structure with corresponding field names and some text around every structure element.

i.e. This something [fieldname(i)] has the value of [struct.fieldname(i) value] something.

After half a day of headache I ended up with an expression (which does not work) and a loop (which works).

Question - is there a way to do this without a loop?

Code:

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){:})

The loop returns a sensible output exactly as I want:

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

Just the printf expression however returns this weird output:

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

Advice appreciated

3 Answers
Related