1

I have an existing structure array which is loaded into the workspace with a load() statement. The fields contain char and double.

I want to create this structure, including the contents of its fields, in a script instead, but as the structure is large, I don't want to write all the fields and values out by hand.

Dragging the structure fields from the workspace into the editor just copies the field names over.

Is there an easy and convenient way to extract the fields and their values, so that the fields of the structure array

example_struct

are turned into statements of the form

example_struct.field1 = <some_value>;

which doesn't involve writing a script?

EDIT: I want to write a script (an M-file) which populates a new structure array with actual values. I want to get the statements for that script, including the values, out of an existing structure which I have loaded with load(), but I want to know if that can be done without writing a script (say, using fprintf statements) to perform the task.

Stephen Bosch
  • 273
  • 1
  • 11
  • If all you want to do is duplicate the structure but without the data you could try the trick I proposed here: http://stackoverflow.com/questions/17805291/how-to-add-new-element-to-structure-array-in-matlab/17805633#17805633 – Dan Jul 31 '13 at 11:07
  • 1
    If you don't want to type in all the fields and values by hand, how would this "script" do it for you instead? Do you have a list of the fields stored somewhere? Are you interested in populating the structure array with actual values, or leave the fields empty? – Eitan T Jul 31 '13 at 11:13
  • @EitanT Sorry, I realize the question is a bit confusing. I've added a clarification. – Stephen Bosch Jul 31 '13 at 11:30

1 Answers1

3

If I understand correctly, you want to dump a struct into a Matlab script file, rather than a .mat file. You can do something like this with a few lines of Matlab:

fId = fopen('outputfile.m');
names = fieldnames(example_struct);
for i = 1 : length(names)
  fprintf(fId, 'example_struct.%s = %d;\n', names{i}, example_struct.(names{i}) );
end
fclose(fId);

The fieldnames function returns a cell array of field names for a structure, which can be accessed in turn using the example_struct.('name') notation. Note that that I've made some basic assumptions, like all the fields being numbers. I'll leave it to you to expand this for your needs!

devrobf
  • 6,973
  • 2
  • 32
  • 46
  • Yeah, this was how I figured it would need to be done. I was wondering if there were any GUI (or other) tricks that would make it unnecessary, particularly as I have char fields as well. – Stephen Bosch Jul 31 '13 at 11:34