Creating variable whose name is part of a string

I have a .mat file as an input for my function and I know that it contains a struct, but I don't know exactly the name of that struct (is different from file to file).
>> s = load('myFile');
>> name = fieldnames(s)
name =
unknown
where unknown depends on the .mat file input I have.
How can I access s.unknown.X? (I know for sure that unknown have an X and Y field, whatever the input might be)

 採用された回答

Robert Cumming
Robert Cumming 2013 年 6 月 13 日

2 投票

Basically - dont use eval - its bad! use dynamic fieldnames instead! :)

4 件のコメント

Vishal Rane
Vishal Rane 2013 年 6 月 13 日
編集済み: Vishal Rane 2013 年 6 月 13 日
Agreed ! But how does one dynamically create a variable which is not intended to be a struct or struct field.
Robert Cumming
Robert Cumming 2013 年 6 月 13 日
dont - change your design so you dont need to.
Jan
Jan 2013 年 6 月 13 日
I agree with Robert: Do not create variables dynamically. It would work, but increase the complexity of the code without any real benefit, slows down Matlab by impeding the JIT acceleration, and makes debugging much harder.
Dina Irofti
Dina Irofti 2013 年 6 月 13 日
You are right, it is better to use dynamic fieldnames. My solution is:
s = load('myFile');
unknown = fieldnames(s);
unknown = unknown{1};
Now I can access
s.(unknown).X

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

その他の回答 (1 件)

Vishal Rane
Vishal Rane 2013 年 6 月 13 日

0 投票

You could try this:
eval([name, ' = 10'])

1 件のコメント

Dina Irofti
Dina Irofti 2013 年 6 月 13 日
I'd rather didn't use eval()

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

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by