Using Matfile() in combination with a variable

1 回表示 (過去 30 日間)
Jan Majewski
Jan Majewski 2018 年 11 月 21 日
編集済み: Jan Majewski 2018 年 11 月 22 日
I reference a Matfile and to access its entries using a variable:
a = 'variablefrommat';
m = matfile('myMat.mat');
x = m.a
This results (obviously) in Matlab searching the Matfile for 'a'. In my case this error occurs:
'a' does not exist in 'myMat.mat'.
Is there a way to interpret 'a' as the variable?

採用された回答

Adam Danz
Adam Danz 2018 年 11 月 21 日
編集済み: Adam Danz 2018 年 11 月 21 日
The mat file object is similar to a structure array. Use parentheses to access fields dynamically.
m = matfile('myMat.mat');
a = 'variablefrommat';
x = m.(a) %same as m.variablefrommat
  2 件のコメント
Jan Majewski
Jan Majewski 2018 年 11 月 22 日
Thanks it works!

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

その他の回答 (1 件)

Geoff Hayes
Geoff Hayes 2018 年 11 月 21 日
Jan - if you know the name of the variable that you want to reference then why are you setting this to its own variable? What are you trying to accomplish here?
You can do this using getfield as
x = getfield(m,a)
which will return the expected result...but do you need to do it this way?
  1 件のコメント
Jan Majewski
Jan Majewski 2018 年 11 月 22 日
編集済み: Jan Majewski 2018 年 11 月 22 日
I have a function which executes it since i have a lot variables and wanted to organize it better.
Maybe should have added it in the Question.
Your solution works aswell! Thanks.

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

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT-Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by