How can I make struct with existing variables?

72 ビュー (過去 30 日間)
Giorgi
Giorgi 2014 年 8 月 22 日
編集済み: Matt J 2014 年 8 月 22 日
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.

採用された回答

Matt J
Matt J 2014 年 8 月 22 日
編集済み: Matt J 2014 年 8 月 22 日
Using structvars ( Available here ).
>> clear
>> a=1; b=2; c=3;
>> s=whos;
>> C=cell2struct({s.name}.',{s.name})
C =
a: 'a'
b: 'b'
c: 'c'
>> structvars(C,0); %copy/paste the output below to the command line
ans =
C.a = a;
C.b = b;
C.c = c;
  3 件のコメント
Adam
Adam 2014 年 8 月 22 日
Did you follow Matt J's 'Available here' link and add the downloaded location to your path?
Matt J
Matt J 2014 年 8 月 22 日
Though I don't really recommend it, you could also do
>> eval(structvars(C,0).'); C
C =
a: 1
b: 2
c: 3

サインインしてコメントする。

その他の回答 (3 件)

Matt J
Matt J 2014 年 8 月 22 日
編集済み: Matt J 2014 年 8 月 22 日
>> save tempFile *
>> S=load('tempFile');

Guillaume
Guillaume 2014 年 8 月 22 日
s = struct('alpha', alpha, 'beta', beta, 'gamma', gamma);
doc struct
  2 件のコメント
Giorgi
Giorgi 2014 年 8 月 22 日
Well that is fine but if i have more than 30 variables should I write it manually? The problem is that I cant write a code with which it automaticly will assign all variables
Guillaume
Guillaume 2014 年 8 月 22 日
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

サインインしてコメントする。


Adam
Adam 2014 年 8 月 22 日
編集済み: Adam 2014 年 8 月 22 日
myStruct.alfa = alfa;
myStruct.beta = beta;
etc.
Or
myStruct = struct( 'alfa', alfa, 'beta', beta );
  4 件のコメント
Giorgi
Giorgi 2014 年 8 月 22 日
編集済み: Matt J 2014 年 8 月 22 日
Well as you say in txt file I have all variable names, so I measured its length and use cycle here is a code but it does not work any ideas?
a=length(txt(1,:));
for i=1:a
mystruct=struct(txt(1,i),[txt{1,i}]);
end
Adam
Adam 2014 年 8 月 22 日
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by