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

15 views (last 30 days)
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 Comments
Rik
Rik on 30 Apr 2021
In general you can do that by editing the question instead of posting a new one.

Sign in to comment.

Accepted Answer

Scott MacKenzie
Scott MacKenzie on 30 Apr 2021
Edited: Scott MacKenzie on 30 Apr 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');

More Answers (1)

EmirBeg
EmirBeg on 30 Apr 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 Comments
EmirBeg
EmirBeg on 30 Apr 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

Sign in to comment.

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!