How can I make struct with existing variables?
Show older comments
Hi all, Well i have some variables for example alfa, beta and gama, Now I want to make structure that will contain these variables. Can someone give me a code or function with which i will be able to do it.
Accepted Answer
More Answers (3)
>> save tempFile *
>> S=load('tempFile');
Guillaume
on 22 Aug 2014
s = struct('alpha', alpha, 'beta', beta, 'gamma', gamma);
doc struct
2 Comments
Giorgi
on 22 Aug 2014
Guillaume
on 22 Aug 2014
You could dynamically create a structure with 30 field names that are the names of the variables, however I would urge to think whether it's really what you want. How are you going to then use that structure if the field names are created arbitrarily. I would advise against this as your code may easily break in the future because a hardcoded field is not there anymore.
If that's really what you want to do, then structvars from the other answer (you have to download it), or the following function will do it:
function s = variables2struct(varargin)
s = struct;
for var = 1:nargin
s.(genvarname(inputname(var), fieldnames(s))) = varargin{var};
end
end
myStruct.alfa = alfa;
myStruct.beta = beta;
etc.
Or
myStruct = struct( 'alfa', alfa, 'beta', beta );
4 Comments
Giorgi
on 22 Aug 2014
Adam
on 22 Aug 2014
Is it every variable in your workspace or just some subset? If you can create a cell array of all the variable names then you can also use that with an equivalent cell array of the values of each variable to pass to struct.
Adam
on 22 Aug 2014
I could try to give some help further along this line, but I think potentially either of Matt J's solutions would work better so unless neither of them do I'll leave it.
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!