looping a code efficiently

1 view (last 30 days)
cgo
cgo on 29 Nov 2014
Commented: Stephen23 on 11 Jan 2016
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.

Accepted Answer

Stalin Samuel
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
cgo
cgo on 29 Nov 2014
Hi, I followed your code above and it works. Thanks.
So know I have,
for n = 1:4
velocity = ['v_',num2str(n),' = n*2'];
eval(velocity)
position = ['x_', num2str(n), '= n.^2'];
eval(position)
end
Output would be v_1 = 2, x_1 = 2 , etc , … v_4 = 8 and x_4 = 16.
Let's say that I want to something with these variables. Say for example, add those things with the same indices. v_1 + x_1. I do not know how to proceed.
Thanks
Stephen23
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:

Sign in to comment.

More Answers (0)

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!