How to sum specific values from a loop and create a new vector?
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
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.
채택된 답변
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
Thank you man!, one question: X = sum(bsxfun(@plus, idx, -2:0), 2)
what does this 2 implies?
My pleasure!
The 2 is an argument to sum, and tells it to sum across columns. (The default behaviour is to sum across rows, or dimension 1.)
Philippe Corner
2018년 1월 23일
편집: Philippe Corner
2018년 1월 23일
Mr Star, im not sure what is happening, I modified the code in function of what im needing and the result is not coherent.. can you take a look? Im trying to sum 10 rain values before each event>0
clear all
[date,rain,event] = textread('date_rain_event.txt','%s %f %f','delimiter',',', 'headerlines',1);
M=[rain,event] ;
idx = find(M(:,2) > 0);
f = sum(bsxfun(@plus, idx, -9:0),2)
Originally, ‘idx’ and ‘M(:,1)’ were the same. The code using ‘M(:,1)’ is:
X = sum(bsxfun(@plus, M(idx,1), -2:0),2)
Y = sum(bsxfun(@plus, M(idx,1), -5:-3),2)
giving the same result.
So this should work in your code:
f = sum(bsxfun(@plus, M(idx,1), -9:0),2)
My apologies for the confusion.
Thank you again, you are very kind. I got your point.
Nevertheless, it is not working.. idx is doing good, the first row where M(:,2)>0 is 127.. and it should be taking the rowsum of the first column like this: (118:127, 1), but the result is not ok, and even there are negative values now..
Ill keep working on it, but if you can easily find the mistake, please let me know.
Thank you again.
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.
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?
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개)
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
