How to write a for loop that saves every 100th value?

18 visualizaciones (últimos 30 días)
Lauren Miller
Lauren Miller el 30 de Abr. de 2021
Editada: Scott MacKenzie el 30 de Abr. de 2021
I have a code that has a for loop that calculates the eccentricity of an orbit as time passes, and I need to plot the results. Saving every single value of accentricity would be very large task, so I need to save every 100th value of eccentricity, along with the corresponding time, to some type of file.
This is what I have so far but it very much doesn't work, any advce would be greatly appreciated.
m = 0;
for i = 1: m
m = m + 1;
if m == 100
C{i} = emag;
C2{i} = t;
E(i,1) = emag;
E(i,2) = t;
matrixToWrite = [t emag];
writematrix(matrixToWrite, 'myData.txt')
m = 0;
t = t + delta;
end
end
  4 comentarios
Rik
Rik el 30 de Abr. de 2021
In general you can do that by editing the question instead of posting a new one.
Lauren Miller
Lauren Miller el 30 de Abr. de 2021
Thanks for your advice :)

Iniciar sesión para comentar.

Respuesta aceptada

Scott MacKenzie
Scott MacKenzie el 30 de Abr. de 2021
Editada: Scott MacKenzie el 30 de Abr. de 2021
If I understand your quesiton correctly, a for-loop is not necessary. It seems you have an array emag with many values and a corresponding array t with the timestamp for each value. Here's some code (using mock arrays) that saves every 100th value in t and emag in a file mydata.txt:
emag = rand(1,23456);
t = rand(1,23456);
n = length(emag);
emag100 = emag(1:100:n);
t100 = t(1:100:n);
writematrix([emag100' t100'], 'mydata.txt');

Más respuestas (1)

EmirBeg
EmirBeg el 30 de Abr. de 2021
First of all you set m=0 and then start a loop from 1 to m. So i guess your loop does nothing.
You need to set a new variable for the amount of iterations your loop will go through. After that you should also set m to 0 again in your If-statement so you get a value every 100th iteration and not just the 100th.
  2 comentarios
EmirBeg
EmirBeg el 30 de Abr. de 2021
I realise that you already added the m=0 in your If-statement or i was blind and didn't see it.
This should still be changed:
m = 0;
t = 5000; %amount of times you go through the loop
for i = 1: t
m = m + 1;
if m == 100
%...
end
end
Lauren Miller
Lauren Miller el 30 de Abr. de 2021
Thank you so much that's really helpful!

Iniciar sesión para comentar.

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!

Translated by