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

19 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by