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

조회 수: 12 (최근 30일)
Lauren Miller
Lauren Miller 2021년 4월 30일
편집: Scott MacKenzie 2021년 4월 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.
Lauren Miller
Lauren Miller 2021년 4월 30일
Thanks for your advice :)

댓글을 달려면 로그인하십시오.

채택된 답변

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
Lauren Miller
Lauren Miller 2021년 4월 30일
Thank you so much that's really helpful!

댓글을 달려면 로그인하십시오.

카테고리

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