Borrar filtros
Borrar filtros

Help with for loop

1 visualización (últimos 30 días)
Deanna
Deanna el 19 de Oct. de 2011
I need to use a for loop to calculate the change in a variable as a function of time. Each run through the loop represents a time interval of 0.5 sec. The problem is that for the first 0.5 sec interval I have one variable to evaluate, for the second 0.5 sec interval I have two variables to evaluate, and so on. I can't figure out how to add a variable each time. Here is what I need to do (using simple equations).
declare some constants: x = 100, Cw(0) = 0, n = 10 (for example, I will have variables n1, n2, n3,...n10)
Here I'm breaking down the first few runs through the loop. I will need to go through the loop 12 times.
first run through the loop: n1(1) = x*Cw(0), Cw(1) = n1(1) - x
second run through the loop: n1(2) = n1(1)*Cw(1), n2(2) = x*Cw(1), Cw(2) = [n1(2) - n1(1)] + [n2(2) - x]
third run through the loop: n1(3) = n1(2)*Cw(2), n2(3) = n2(2)*Cw(2), n3(3) = x*Cw(2), Cw(3) = [n1(3) - n1(2)] + [n2(3) - n2(2)] + [n3(3) - x]
and so on....
For the 10th run through the loop we will have n1 through n10. We will run the loop 12 times though, and for runs 11 and 12 there will still only be n1 through n10. Basically at the beginning I can define the number of ns I will have and the number of times to run the loop. Can someone help me figure out how to set up the code to do what I want to do?
Thanks!!!
  1 comentario
Jan
Jan el 19 de Oct. de 2011
Do not use n1, n2, ... See: http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F . n{1}, n{2}, ... allows for solving your problem using two nested loops.

Iniciar sesión para comentar.

Respuestas (1)

Rick Rosson
Rick Rosson el 19 de Oct. de 2011
Two suggestions:
1. Pre-allocate a single variable as a two-dimensional array of adequate size to store all of the data you will ultimately need. For example:
numIter = 12;
numVars = 10;
n = zeros(numIter,numVars);
2. Create a set of two nested for loops to compute the results. For example:
for i = 1:numIter
numVars = min(i,10);
for v = 1:numVars
...
n(i,v) = ...
...
end
end
HTH.
Rick

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by