MATLAB Answers

How to sum specific values from a loop and create a new vector?

6 ビュー (過去 30 日間)
Philippe Corner
Philippe Corner 2018 年 1 月 23 日
コメント済み: Star Strider 2018 年 1 月 23 日
If I have this matrix M:
a=1:1:20;
b=[0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 2 0 0];
M=[a,b];
How could I find the i values where M(:,b)>0 (where the second column "b">0), and then take the values of the same row but the first column "a" M(a,:) and make a summation from that row i and i-2, i,e, [i + (i-1)+(i-2)].. like this:
X=[(5+6+7) (12+13+14) (18+17+16)] = [18 39 51]
Besides a vector Y which contains the summation from i-5 until i-3 like this:
Y=[(2+3+4) (9+10+11) (13+14+15)] = [9 30 42]
Both of them for all i values in a vector b of a matrix.

  0 件のコメント

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

採用された回答

Star Strider
Star Strider 2018 年 1 月 23 日
Use bsxfun and sum:
a=1:1:20;
b=[0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 2 0 0];
M=[a(:),b(:)];
idx = find(M(:,2) > 0);
X = sum(bsxfun(@plus, idx, -2:0),2)
Y = sum(bsxfun(@plus, idx, -5:-3),2)
X =
18
39
51
Y =
9
30
42

  8 件のコメント

表示 5 件の古いコメント
Star Strider
Star Strider 2018 年 1 月 23 日
My pleasure.
I still do not understand the reason that the prototype code did not work with your actual data.
This works:
f = sum(arrayfun(@(x)sum(M(x,1)), bsxfun(@plus, idx', (-9:0)')));
I checked to be certain it produces the correct result with your data.
It works by calculating one column vector of indices into ‘M’ for each value of ‘idx’ and the offset of ‘(-9:0)’, calculated by the bsxfun call (that turned out to be correct after all), creating a matrix that here is (10x1881), the column size being the length of ‘idx’. It then uses the custom anonymous function ‘@(x)sum(M(x,1))’ to sum the first column of ‘M’ corresponding to the indices calculated by the bsxfun call. The arrayfun function contains an implicit loop (that I hope is more efficient than an explicit for loop). It then returns the result of the row sums for each column as a row vector.
Philippe Corner
Philippe Corner 2018 年 1 月 23 日
Amazing! The last question would be how to solve the same problem but not for the rows which M(:,2)>0, but all the rows! if I apply the same sense, the problem would be for the very beginning rows.. any idea Mr Star?
Star Strider
Star Strider 2018 年 1 月 23 日
Thank you!
If you want to have a moving sum for all the rows taken 10 at a time, use the movsum (link) function (introduced in R2016a).

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

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by