フィルターのクリア

Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Sum variables from three in three, after summing compute an equation and organize all data into a new column?

1 回表示 (過去 30 日間)
rpid
rpid 2019 年 1 月 26 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
How can I sum variables from three in three and put these same sums in another column? I thought in splitting in two "for" conditions as shown below.
x=data(:,1);
i=1;
j=1;
for i=1:length(data)
for j=1:3
x(i)=1;
x(i+1)=2^2;
x(i+2)=3^3;
h=x(i)+x(i+1)+x(i+2);
i=i+1;
end
j=j+3;
end
Can anyone help me, please? Thank you.

回答 (2 件)

Steven Lord
Steven Lord 2019 年 1 月 27 日
x=data(:,1);
i=1;
j=1;
for i=1:length(data)
for j=1:3
x(i)=1;
x(i+1)=2^2;
x(i+2)=3^3;
h=x(i)+x(i+1)+x(i+2);
i=i+1;
end
j=j+3;
end
The line "j=j+3;" at the end of the body of your "for i" loop does increment j ... for the remainder of that iteration over i. As soon as MATLAB moves to the next iteration of the "for i" loop, it starts a loop that assigns 1, 2, and 3 in turn to j. This throws away the value that was previously in j (which was not actually used in the for loop over j.)
Perhaps what you want is to have i jump by steps of 3? Look at the documentation for the colon function or the : operator for examples that will show you how to do that.
  1 件のコメント
rpid
rpid 2019 年 1 月 27 日
Thanks for your attention. I did it and I got another results, but the code is still not working as it should.
These are the values I need to reproduce.
i, j x y h=sum_x sum_y
1 64 2 - -
2 9 55 - -
3 17 47 90 104
4 40 26 - -
5 32 34 - -
6 41 23 113 83
7 49 15 - -
8 8 58 - -
9 64 2 121 75
10 9 55 - -
11 17 47 - -
12 40 26 66 128
13 32 34 - -
14 41 23 - -
15 49 15 122 72
n ... ... - -
The code now, with your help:
x=data(:,1);
n=length(data);
i=1;
j=1;
for j=1:n
for i=1:3
x(i);
x(i+1);
x(i+2);
h=x(i)+x(i+1)+x(i+2);
i=i+1;
end
j=1:3:n;
end
The h value returns just one number ow and I need a sequence as presented in h=sum_x. Can you help me, please? Thks!!!

Kevin Phung
Kevin Phung 2019 年 1 月 26 日

この質問は閉じられています。

Community Treasure Hunt

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

Start Hunting!

Translated by