フィルターのクリア

Using loop to sum value of an array and summation

5 ビュー (過去 30 日間)
DoinK
DoinK 2023 年 6 月 10 日
編集済み: Stephen23 2023 年 6 月 11 日
I have 2000 row vector which each array has 1008 column.
I need to sum every array to only 4 column, so every 252 item, i sum it, so the array now has 4 column.
For example, i use only 1 row vector which has 12 column and every 3 item i sum it:
J=[1 2 3 4 5 6 1 2 3 4 5 6];
for i=1:length(J)
a=sum(J(1:3));
b=sum(J(4:6));
c=sum(J(7:9));
d=sum(J(10:12));
end
p0=[a b c d]
p0 = 1×4
6 15 6 15
After that, i have to do summation:
for j=1:4
f=j*p0(j);
h(j)= sum(f);
end
h
h = 1×4
6 30 18 60
I can call 'h' too like h(3) is 18.
I can do it for small input like this, how to code for big vector?
How to summation up to 2000 vector and can call every 'h'?
May i know, summation mostly start with 0, but looping with (for) command cannot do it, ''Array indices must be positive integers or logical values."
Is there any command to use to start with 0?
  2 件のコメント
Stephen23
Stephen23 2023 年 6 月 10 日
編集済み: Stephen23 2023 年 6 月 11 日
The standard MATLAB approach:
J = [1,2,3,4,5,6,1,2,3,4,5,6];
P = sum(reshape(J,[],4),1)
P = 1×4
6 15 6 15
H = J(1:4).*P
H = 1×4
6 30 18 60
DoinK
DoinK 2023 年 6 月 10 日
thank you sir, the code is so simple and exactly what i need.

サインインしてコメントする。

採用された回答

Alan Stevens
Alan Stevens 2023 年 6 月 10 日
Here's one way:
J=[1 2 3 4 5 6 1 2 3 4 5 6];
step = 3;
ix = 1:step:numel(J);
for i = 1:numel(ix)
p(i) = sum(J(ix(i):ix(i)+step-1));
end
disp(p)
6 15 6 15
  1 件のコメント
DoinK
DoinK 2023 年 6 月 10 日
thank you sir, the code is shortened.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by