Efficient code for multiple string replace
7 ビュー (過去 30 日間)
表示 古いコメント
Hello,
I am attempting to replace substrings and evaluate equations for a large number of lines. The following code works for what I want:
% Define sets:
sec = ["T", "N"]; co = ["H","F"];
nco = numel(co); nsec = numel(sec);
for cc = 1:numel(co);
for ss = 1:numel(sec);
eval(replace(['tau_payr_#S_#C_bar = 1; '],["#S","#C"], [sec(ss),co(cc)]));
eval(replace(['tau_pinv_#S_#C_bar = 2; '],["#S","#C"], [sec(ss),co(cc)]));
eval(replace(['tau_payr_#S_#C = tau_payr_#S_#C_bar; '],["#S","#C"], [sec(ss),co(cc)]));
eval(replace(['tau_pinv_#S_#C = tau_pinv_#S_#C_bar; '],["#S","#C"], [sec(ss),co(cc)]));
end;
end;
I am wondering whether there's a better way to write this, where I don't have to write eval and replace at each line.
Thanks,
0 件のコメント
採用された回答
Voss
2023 年 2 月 2 日
You can store all those variables in a structure, and use dynamic field names.
sec = ["T", "N"]; co = ["H","F"];
nco = numel(co); nsec = numel(sec);
S = struct();
for cc = 1:numel(co)
for ss = 1:numel(sec)
payr_name = sprintf('tau_payr_%s_%s',sec(ss),co(cc));
pinv_name = sprintf('tau_pinv_%s_%s',sec(ss),co(cc));
S.([payr_name '_bar']) = 1;
S.([pinv_name '_bar']) = 2;
S.(payr_name) = S.([payr_name '_bar']);
S.(pinv_name) = S.([pinv_name '_bar']);
end
end
S
その他の回答 (1 件)
Walter Roberson
2023 年 2 月 2 日
If you are going to write something like that, then you should write it in the clearest way you can come up with, because you are going to end up spending a lot of time staring at the code when it fails to work the way you expect.
Please read http://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval for information about why we strongly recommend against creating variable names dynamically.
参考
カテゴリ
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!