Efficient code for multiple string replace
4 次查看(过去 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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!