Nick T
Nick T

Reputation: 26747

How can I unpack a Matlab structure into function arguments?

Using a combination of this question and this Mathworks help thing on comma sep. lists I came up with this ugly way to make my formatting arguments a little prettier:

formatting{1,1} = 'color';      formatting{2,1} = 'black';
formatting{1,2} = 'fontweight'; formatting{2,2} = 'bold';
formatting{1,3} = 'fontsize';   formatting{2,3} = 24;

xlabel('Distance', formatting{:});

But it's still kinda ugly...is there a way to unpack a structure into a bunch of arguments a la a Python dictionary to **kwargs?

For instance, if I had the (IMHO) cleaner structure:

formatting = struct()
formatting.color = 'black';
formatting.fontweight = 'bold';
formatting.fontsize = 24;

Can I just pass that in somehow? If I try directly (xlabel('blah', formatting), or formatting{:}, it craps out saying "Wrong number of arguments".

Upvotes: 3

Views: 4518

Answers (2)

yuk
yuk

Reputation: 19880

You can convert your structure to cell array with this function:

function c = struct2opt(s)

fname = fieldnames(s);
fval = struct2cell(s);
c = [fname, fval]';
c = c(:);

Then

formatting = struct2opt(formattingStructure);
xlabel('Distance', formatting{:});

Upvotes: 7

shoelzer
shoelzer

Reputation: 10708

You are very close. Just switch to a 1-D cell array.

formatting = {'Color', 'Red', 'LineWidth', 10};
figure
plot(rand(1,10), formatting{:})

If you really want to use a struct for formatting arguments, you can unpack it to a cell array and use it like above.

formattingStruct = struct();
formattingStruct.color = 'black';
formattingStruct.fontweight = 'bold';
formattingStruct.fontsize = 24;

fn = fieldnames(formattingStruct);
formattingCell = {};
for i = 1:length(fn)
    formattingCell = {formattingCell{:}, fn{i}, formattingStruct.(fn{i})};
end

plot(rand(1,10), formatting{:})

It's probably a good idea to do the struct unpacking a separate little function so you can reuse it easily.

Upvotes: 8

Related Questions