I want to make a loop that keeps replacing its own 'S's with SLSRSLS any N number of times
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Mads Albertsen
am 11 Aug. 2021
Kommentiert: Mads Albertsen
am 11 Aug. 2021
i want it like this, but in a loop
N = 3;
k = ('S');
k_1 = regexprep(k,{'S'},{'SLSRSLS'});
k_2 = regexprep(k_1,{'S'},{'SLSRSLS'});
k_3 = regexprep(k_2,{'S'},{'SLSRSLS'});
k_4 = regexprep(k_3,{'S'},{'SLSRSLS'});
disp(k_1)
I dont know if there is a easier way to do it, from what i have researched, changing variable names in a loop is not fun
0 Kommentare
Akzeptierte Antwort
Simon Chan
am 11 Aug. 2021
N = 3;
k{1} = {'S'};
for r = 1:N
k{r+1} = strrep(k{r},{'S'},{'SLSRSLS'})
end
Results are k{1}, k{2}, k{3} & k{4}.
k{4} is
{'SLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLS'}
4 Kommentare
Stephen23
am 11 Aug. 2021
Bearbeitet: Stephen23
am 11 Aug. 2021
@Mads Albertsen: you get that error message because variable k already exists in the workspace and Simon Chan's code is not robustly written to handle that. Try this instead:
N = 5;
k = {'S'};
for ii = 2:N
k{ii} = regexprep(k{ii-1},'S','SLSRSLS');
end
celldisp(k)
If you do not need to store all of those strings (i.e. you only need the last one) then get rid of the cell array entirely.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!