Hi
I am writing a code that uses a lot of repetitions for certain parts. The code is attached. Now I am looking for a way to more efficiently make that code simpler with a for loop. The repetition part is the use of variable U which varies from 1 to 13. Can anyone give a suggestion on how to do that? Thank you.

 Accepted Answer

Jan
Jan on 24 Apr 2017
Sorry for this disappoiting answer: No. The most reliable idea is to delete this code and re-write it from scratch. It is neither readable nor clear and a massive change is very likely to cause troubles and bugs.
We cannot guess, which commands are equal between the parts, and even for you this will not be trivial. The general rule is not to usee numbered names for variables, but arrays. Perhaps all you need is to replace
% for U1=1
U1=1;
...
by
for U = 1:13
M = (L - 2 * R) * U / V;
...
xq = rand(U * 1000, 1) .* L;
...
end
This means: simply remove all magic indices from the names of the variables (again: do not hide indices in names, but use indexed arrays instead).
And for the next time: Never write repeated codes. Use a loop instead.

1 Comment

Adam
Adam on 24 Apr 2017
Or preferably, rather than delete it, if it gives the right answer keep it as a reference and reprogram it in a different file, checking that your reprogrammed answer matches it. This is basically a characterisation test but you don't need to write an actual test so long as you run both versions when you have re-written it in a better style.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 24 Apr 2017

0 votes

Yeah, good luck with that one. Looks like alphabet soup. My only suggestion is to take the repeated lines of code (wherever they are) and make them into a function.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 24 Apr 2017

Commented:

on 24 Apr 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!