# How to substract a loop from the first 10 cell values of the loop?

2 visualizaciones (últimos 30 días)
Wolfgang McCormack el 11 de Mzo. de 2021
Comentada: Wolfgang McCormack el 12 de Mzo. de 2021
Hi everyone,
I have a loop which reads an excel file and calculates some stuff and read a value to cells in a row
For n= 1:200
X(1,n) = C(1,2)
X(2,n) = X(1,n)- [ X(1,n) I want this tem remain constant in pattern of 10. For instance, X(1,101)-X(1,1), X(1,102) - X(1,2) up to ten and again X(1,111)-X(1,1), X(1,112)-X(1,2) ....)
end of n
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

Jorg Woehl el 11 de Mzo. de 2021
Would this work?
X(2,n) = X(1,n) - X(1,mod(n-1,10)+1)
##### 3 comentariosMostrar 1 comentario más antiguoOcultar 1 comentario más antiguo
Jorg Woehl el 12 de Mzo. de 2021
Hi Wolfgang, my pleasure :)... And yes, you can reduce the interval to every 4 simply by replacing the 10 by 4. To understand what the statement does, let's do a smaller loop:
for n=1:20
mod(n-1,10)+1
end
This gives the series 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 (and so on for larger n).
The mod function is the remainder (modulo) of the first argument (n-1) divided by the second (10). I first tried
mod(n,10)
but that yields the series 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0. Which doesn't work here, because we don't want 0 as an index into X. And we also don't want to stop at index 9, but at 10.
Which means that we need to add 1 to the mod result, but then the series starts with 2 3 4..., while we want it to start with 1 2 3.... The solution to that is to subtract 1 before taking the remainder: mod(n-1,10) + 1.
So, the modulo function gives you the repeating blocks that you want, and after that it's a little bit of playing around until everything is in place.
Wolfgang McCormack el 12 de Mzo. de 2021
@Jorg Woehl Wowwwww man you are a genius. Thank youuuuu so muchhhhh!

Iniciar sesión para comentar.

### Categorías

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

R2020b

### Community Treasure Hunt

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

Start Hunting!

Translated by