Efficient code for multiple string replace
6 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Voss
on 2 Feb 2023
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
2 Comments
More Answers (1)
Walter Roberson
on 2 Feb 2023
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.
See Also
Categories
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!