looping a code efficiently
1 view (last 30 days)
Show older comments
Hi,
I am writing a loop code for a particle. The equations involved are the following:
f_1x(t) = x_1;
v_1 = w*v_1 + c_p*rand*(x_1best - x_1) + c_n*rand*(g_best - x_1);
x_1 = x_1 + v_1;
As you can see, if I add another particle, all I need to do is actually add another set of those equations, and change all 1's to 2's. They will work out to be fine.
The problem is … if I want work with 100 other particles, there is should be a better way than just copying and pasting these equations 100 times!
Please help me find out what functions/commands I need for this. You do not need to write down the code for me. I need to know what commands/functions I should be dealing with so that I can study these after.
0 Comments
Accepted Answer
Stalin Samuel
on 29 Nov 2014
eval(['your_variable' num2str(iiterration_variable)]) for example for n=1:100 eval(['v_' num2str(n)]);end
2 Comments
Stephen23
on 11 Jan 2016
The reason that you "do not know how to proceed" is because this is a really awful way to program. Whoever advises you to use eval should be ignored, as it is very bad advice.
You should learn to use complete numeric arrays and indexing instead of using slow and buggy code with eval.
Note that your question title is "looping a code efficiently", but the answer you have accepted is the buggiest and slowest solution. The answer you have been given is "looping really slowly using buggy code". You would do much better to learn to write vectorized code, to use indexing properly, and to learn to use the dimensions of arrays.
If you are interested in why eval is a poor way to code, read this very carefully:
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!