How to save the value, a string, of a variable as a variable name of an array ?

47 vues (au cours des 30 derniers jours)
Adrien
Adrien le 4 Nov 2014
Commenté : Adrien le 4 Nov 2014
Hello,
I have a variable and a double array :
s_fieldnames = 'aaa';
a_nums = [1, 2, 3, 4, 5, 6];
I would like to save this into a mat file. To be clearer, i would like to have a mat file which contains :
aaa = [1, 2, 3, 4, 5, 6];
It means I would like to have the value of s_fieldnames as the name of the double array. So that if i look into my file I will have aaa which contains the double array.
After that I want to use the function save.
save('filename', ...);
Thank you Adrien

Réponse acceptée

Orion
Orion le 4 Nov 2014
Hi,
something like
s_fieldnames = 'aaa';
a_nums = [1, 2, 3, 4, 5, 6];
% create the variable aaa containing the values of a_nums
eval([s_fieldnames '=a_nums;']);
% save it in a mat file
save('filename',s_fieldnames)

Plus de réponses (1)

Adam
Adam le 4 Nov 2014
Modifié(e) : Adam le 4 Nov 2014
s_fieldnames = 'aaa';
a_nums = [1, 2, 3, 4, 5, 6];
temp.( s_fieldnames ) = a_nums;
save( 'filename', '-struct', 'temp' );
Try to avoid ever creating variables in your workspace from a string. It isn't a good way to go about things at all even though it is something so many people (myself included) have wanted to do before they know better!
This method allows you to use the inbuilt method for generating structure fieldnames from variables, then save to a mat file with the '-struct' option to get rid of the struct on saving. Judging by the naming of your variable s_fieldnames it was intended to be a structure field name rather than a raw variable anyway!
Note: If s_fieldnames happens to live up to its pluralised name and contain multiple variables you will have to use cellfun or a for loop to do this for each name in the cell array of names.
  1 commentaire
Adrien
Adrien le 4 Nov 2014
Thanks, that was what I was searching for, but didn't found this easy methodic !

Connectez-vous pour commenter.

Catégories

En savoir plus sur Cell Arrays dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by