I have a matrix B that has three columns. A week number is in the first column, a day number is in the second column, and data is in the third column.
B=
1 6 9
3 15 11
4 23 11
5 30 11
6 37 12
6 38 11
6 39 10
9 58 12
10 65 13
What I want to do is turn this into a matrix with 10 rows, one for each week. Whenever there is a week with no data, like week 2 and week 7, I want to add a row with the proper week number, but zeros for the day number and the data. Also, whenever there is a week with more than 1 data entry, like week 6, I want to convert that to one row with 6 as the week number, any value for the day number, and the mean of the data values as the one data value. In other words, I want to convert matrix B into:
C=
1 6 9
2 0 0
3 15 11
4 23 11
5 30 11
6 38 11
7 0 0
8 0 0
9 58 12
10 65 13
How can I go about doing this?

댓글 수: 1

Walter Roberson
Walter Roberson 2014년 2월 4일
I notice you have edited the question, but as I read, I do not notice the difference between the current version and the original ?

댓글을 달려면 로그인하십시오.

 채택된 답변

Walter Roberson
Walter Roberson 2014년 2월 4일

0 개 추천

widx = B(:,1);
dayvec = accumarray(widx, B(:,2), [], @min);
valvec = accumarray(widx, B(:,3), [], @mean);
C = [(1:max(widx)).', dayvec(:), valvec(:)];

댓글 수: 5

Michael
Michael 2014년 2월 5일
Thank you! This works well, my only question would how could I make it so that if the 10th week was missing, it would fill in a tenth week without stopping at 9?
Walter Roberson
Walter Roberson 2014년 2월 5일
Replace the [] with [10 1]
It was telling me that the dimensions of the matrices being concatenated are not consistent, so I added another line, and ran it like this, and it worked:
MATLAB CODE
widx = B(:,1)
weekvec = accumarray(widx, B(:,1), [10, 1], @min) added this line
dayvec = accumarray(widx, B(:,2), [10 1], @min)
valvec = accumarray(widx, B(:,3), [10 1], @mean)
C = [(1:length(weekvec))', dayvec(:), valvec(:)] used weekvec here
is there a cleaner way of doing this?
Setting weekvec like that is not needed. Leave that line out and use
C = [(1:length(dayvec)).', dayvec(:), valvec(:)];
Michael
Michael 2014년 2월 6일
Ahh yes, that makes way more sense, thanks

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2014년 2월 4일

댓글:

2014년 2월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by