フィルターのクリア

Creating a variable from part of a string

3 ビュー (過去 30 日間)
Benjamin
Benjamin 2018 年 11 月 7 日
編集済み: Stephen23 2018 年 11 月 7 日
I have a string:
x='dr_1e-2_A1_OFF_A2_OFF.txt';
Is there a way to create variables from this string?
How can I set
dr = 1e-2
by only referring to the string? How can I set
A1 = 0 (since Off)
by only referring to the string?
Then if I want to create a title from the variables, could I?
Like:
title('dr = ' insert dr variable )
  1 件のコメント
Stephen23
Stephen23 2018 年 11 月 7 日
"Then if I want to create a title from the variables, could I?"
You certainly could... but this is not recommended. Magically creating variable names is one way that beginners force themselves into writing slow, complex, buggy code which is hard to debug. Read this to know why:

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

採用された回答

Stephen23
Stephen23 2018 年 11 月 7 日
編集済み: Stephen23 2018 年 11 月 7 日
I recommend that you use a structure instead of magically accessing variable names:
>> x = 'dr_1e-2_A1_OFF_A2_OFF.txt';
>> [~,N] = fileparts(x);
>> C = regexp(N,'_','split');
>> S = struct(C{:});
>> S.dr
ans = 1e-2
>> S.A1
ans = OFF
>> S.A2
ans = OFF
You can easily add a conversion to numeric as well:
>> [~,N] = fileparts(x);
>> C = regexp(N,'_','split');
>> V = str2double(C);
>> X = ~isnan(V);
>> C(X) = num2cell(V(X));
>> S = struct(C{:});
>> S.dr
ans = 0.010000
"Then if I want to create a title from the variables,could I?"
Of course, read about fieldnames and dynamic field names:
  3 件のコメント
Stephen23
Stephen23 2018 年 11 月 7 日
編集済み: Stephen23 2018 年 11 月 7 日
Thank you! It just removes the file extension...
James Tursa
James Tursa 2018 年 11 月 7 日
Yikes! The rest of my edited comment didn't make it, re the splitting and struct stuff ...

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

その他の回答 (0 件)

カテゴリ

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