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

17 次查看(过去 30 天)
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 个评论
Rik
Rik 2021-4-30
In general you can do that by editing the question instead of posting a new one.

请先登录,再进行评论。

采纳的回答

Scott MacKenzie
Scott MacKenzie 2021-4-30
编辑:Scott MacKenzie 2021-4-30
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');

更多回答(1 个)

EmirBeg
EmirBeg 2021-4-30
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 个评论
EmirBeg
EmirBeg 2021-4-30
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by