Code covered by the BSD License  

Highlights from
Pack & Unpack variables to & from structures with enhanced functionality

5.0

5.0 | 8 ratings Rate this file 78 Downloads (last 30 days) File Size: 15.4 KB File ID: #31532
image thumbnail

Pack & Unpack variables to & from structures with enhanced functionality

by

 

23 May 2011 (Updated )

v2struct packs and unpacks variables to and from structures with enhanced functionality.

Editor's Notes:

This file was selected as MATLAB Central Pick of the Week

| Watch this File

File Information
Description

v2struct has dual functionality in packing & unpacking variables into structures and vice versa, according to the syntax and inputs.

Function features:
   * Pack variables to structure with enhanced field naming
   * Pack and update variables in existing structure
   * Unpack variables from structure with enhanced variable naming
   * Unpack only specific fields in a structure to variables
   * Unpack without over writing existing variables in workspace

In addition to the obvious usage, this function could by highly useful for example in working with a function with multiple inputs. Packing variables before the call to the function, and unpacking it in the beginning of the function will make the function call shorter, more readable, and you would not have to worry about arguments order any more. Moreover you could leave the function as it is and you could pass same inputs to multiple functions, each of which will use its designated arguments placed in the structure.

Moreover, the function enables extracting specific fields from a structure according to field names. This enhances the flexibility and ease of use of structures, for example it allows you to pass same inputs as structures to multiple functions, each of which will use its designated
arguments placed in the structure.

Some examples:
 Simple pack:
       x = zeros(3);
       y = 'Testing123';
       z = cell(2,3);
       fieldNames1 = {'fieldnames','x','y','z'};
       fieldNames2 = {'fieldnames','a','b','c'};
   
   >> S = v2struct(x,y,z)
   S =
       x: [3x3 double]
       y: 'Testing123'
       z: {2x3 cell}

 pack with different field names:
   >> S = v2struct(x,y,z, fieldNames2)
   S =
       a: [3x3 double]
       b: 'Testing123'
       c: {2x3 cell}

 update existing structure with additional field:
   >> S.oldField = 'field to be saved for future use'
   >> S = v2struct(x2, nameOfStruct2Update, fieldNames3)
   S =
    oldField: 'field to be saved for future use'
           x: [3x3 double]

 simple unpack:
       S.x = zeros(3);
       S.y = 'Testing123';
       S.z = cell(2,3);
       fieldNames3 = {'y'};
   >> v2struct(S)
       y
   y =
   Testing123

More examples, further comments and demo usage are available inside the .m file and the demo functions.

Comments, suggestions, bug reports and any other feedback is welcomed at adi.navve[at]gmail[dot]com

Inspired by the function 'mmv2truct' from the Mastering Matlab Toolbox (available free) by D.C. Hanselman, University of Maine, Orono, ME 04469 4/28/99, 9/29/99, renamed 10/19/99 Mastering MATLAB 5, Prentice Hall, ISBN 0-13-858366-8
available at: http://www.eece.maine.edu/mm/MM6/tbx.html

Acknowledgements

This file inspired Implot Image Plot, Apply Multiple Functions In A Single Function., and Crop Video To Sub Elements.

MATLAB release MATLAB 7.12 (R2011a)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (16)
23 Dec 2012 Jeff  
18 May 2012 Jeff  
10 May 2012 Paul

Perfect! Exactly what I needed:) Cheers

30 Apr 2012 Shawn Heide  
07 Dec 2011 Adi Navve

Hi Christian,
It seems you have stumbled upon a name collision issue combined with the issue that Matlab treats calling a command differently whether it is from the command line or within a function. I assume you have a function called 'sigma' in your Matlab's path. I did not find such function in my system so it could be a function you've created or a built-in function if you have toolboxes that I don't have or a different Matlab version. Try using 'which sigma' to find out details on sigma or better yet 'edit sigma' to edit the function. When I write a code I try to follow the practice of naming variables with a case specific name so to avoid collisions with function names or even other variables in my code.
I could also suggest a practice I've recently began using which helps me in debugging and sorting out issues such as this. I added the line 'dbstop if error' in the startup.m file so whenever an error is encountered during a run the debugger breaks in the line of the error. In your case the debugger would have stopped in a new window of the 'sigma' function.
I hope this helps. Cheers.

06 Dec 2011 Christian Dorion

Hi,
This is a nice tool; I had one of my own but never nearly as extensive as this one. Unfortunately, there seems to be an issue with variable names that are also function names. I couldn't solve it, maybe you could...

If, for example, you write

S = struct('sigma',0.25);
v2struct(S);
whos
sigma

on the command prompt, you have that sigma is 0.25. However, if you wrap this into function test.m (not a script, a function) then you have this oddity:

>> test
Name Size Bytes Class Attributes

S 1x1 184 struct
sigma 1x1 8 double

??? Error using ==> sigma at 83
Not enough input arguments.

Error in ==> test at 5
sigma

where Matlab tries to call a function called sigma!?

Any clue?

07 Nov 2011 Per

Hi Adi
Thanks for your quick reply and support.
I would like a simple "+" funtion which combines the values from two similar structs into one. Field names and construction are equal on the inut structs. The structs are typically struct arrays with more than one level of struct arrays.
Looking forward to your next release.

06 Nov 2011 Adi Navve

Hi Per,
Thank you. Regarding your questions, first, I can think of several ways to extract variables from a struct array. They differ in complexity, both in the implementation in the code and the functionality. Could you elaborate how you would like to use this?
Second, I written a simple function to do this and I will upload it shortly. I would send a link to it here once it is published.

05 Nov 2011 Shatrughan  
04 Nov 2011 Per

Excellent m file, which simplifies my code a lot.
I wonder if it possible in a simple way to extract variables from a struct array?
Also is there a simple way to concatenate struct arrays with similar field names etc?

12 Sep 2011 Adi Navve

Thank you Vesa for your suggestion. I've just uploaded an updated version with your suggestion included. It will be available in a few days.

11 Sep 2011 Vesa Lehtinen

This is a good tool, thanks! To make it perfect, please include a new form:

S=v2struct;

This would return all variables of the current workspace as fields of S. This is sometimes very useful, especially when one wants to have access to internal variables of a function. Instead of script M-files, I use functions that return their internal variables in a v2struct-like way. This gives me full control over my workspace.

07 Aug 2011 Adi Navve

Thomas, I am sorry but I have only little experience with Simulink. However It seems like the function fits exactly to your demands. Maybe you could try and use it within a S-function? Have you tried posting a question in Matlab Central Answers? In anyway I would like to hear how it helped you further. Good luck!

05 Aug 2011 Thomas Marullo

Is it possible to use this for Matlab Embedded Functions? I am trying to solve a problem where I have a model for xPC/Simulink and passing Structures is not supported. I've tried techniques where I convert Structures from the workspace into Arrays then in the model I convert it back to a struct into a Matlab Function using Bus building blocks. The problem is that I need to know the format of the struct ahead of time and my struct can change. This looks like a great approach and I wonder how I can apply this to Simulink Matlab Embedded Function some how.

Thanks for all your hard work.

29 May 2011 Adi Navve

Nikolay, thank you for the feedback. I have addressed your issue in the last update. So now you can update an existing structure, by passing a variable with the name of the structure in the call to the function. An example is given in the file. I hope this answers your problem.

25 May 2011 Nikolay S.

Excellent! Just what I was waiting for! This will allow me to use single input to my multiple inputs functions, with only minor modification. Works like magic!!!
A liitle improvenet would be nice: Note this function clears existing structure fields, while appending might sometimes be desirable.
See the case:
uFileds= {'uR','uG','uB'};
stdFileds= {'stdR','stdG','stdB'};
Metal=v2struct(0,0,0,uFileds);
Metal=v2struct(1,1,1,stdFileds);
% will cleared uFileds, so I had to use
Metal=v2struct(0,0,0,1,1,1,cat(2,uFileds,stdFileds));

But anyhow, excellent code, great functionality, and very detailed documentation. Right on!

Updates
29 May 2011

added update structure functionality, made some documentation and demo function changes, added image :)

05 Jun 2011

* Added functionality: avoid overwritring existing variables
* Added 'unpacking' examples to demo1 .m file.

30 Jun 2011

fieldNames usage corrected, now for triggering a specific string must be included. Documentation enhanced. Code tweaked.

14 Jul 2011

fixed bug in packing with variables only

14 Aug 2011

Clarified warning and error when packing/unpacking with fieldNames.

12 Sep 2011

Added easy packing of all variables in caller workspace (thanks to Vesa Lehtinen for the suggestion), fixed bug in warning handling in packing case, edited comments.

Contact us