looping a code efficiently
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
cgo
el 29 de Nov. de 2014
Comentada: Stephen23
el 11 de En. de 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.
0 comentarios
Respuesta aceptada
Stalin Samuel
el 29 de Nov. de 2014
eval(['your_variable' num2str(iiterration_variable)]) for example for n=1:100 eval(['v_' num2str(n)]);end
2 comentarios
Stephen23
el 11 de En. de 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:
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!