How can I insert missing rows in a matrix

1 回表示 (過去 30 日間)
Mohammad Sayeed
Mohammad Sayeed 2015 年 3 月 30 日
コメント済み: Mohammad Sayeed 2015 年 3 月 30 日
Hi Guys I have a matrix like this: x=[1 4; 4 6;2 3;3 2;4 2;1 3]. where I am showing data of three days. The first row is like a serial number and second row contains the data. I should have 4 data in each day and the first row of the matrix should look like this: x(:,1)= (1 2 3 4 1 2 3 4 1 2 3 4)' But as I have missing data i don't have this matrix. Now I want to create a matrix where all the missing data will be shown with NaN or zero in the second column. So the output will look like : x=[1 4; 2 0;3 0;4 6;1 0;2 3;3 2;4 2;1 3;2 0;3 0;4 0]. That means I will show all the serial numbers in each day and 0 for the missing data. Can anyone help plz? Thank you.

採用された回答

Jos (10584)
Jos (10584) 2015 年 3 月 30 日
This is not really trivial. Here is one approach:
x=[1 4; 4 6;2 3;3 2;4 2;1 3]
Data = x(:,2) ;
SerialNumber = x(:,1) ;
StartNewDay = diff([Inf ; SerialNumber]) < 0
Day = cumsum(StartNewDay)
NewX(:,1) = repmat(1:max(SerialNumber),1,max(Day)).'
M = accumarray([SerialNumber Day],x(:,2)) % build a matrix with zeros
NewX(:,2) = reshape(M,[],1)
This assumes that the serial numbers are consecutive positive integers.
  2 件のコメント
Mohammad Sayeed
Mohammad Sayeed 2015 年 3 月 30 日
It worked perfectly Brother. Thank you very much. Yes the serial numbers are consecutive positive integers. But say, if I suppose to have consecutive time periods in the first row such as 12:01:00 AM and so on instead of consecutive numbers then is it possible solve the problem if I have missing data in some time periods? Please Let me if you can Help me. However, thanks again for the above codes.
Mohammad Sayeed
Mohammad Sayeed 2015 年 3 月 30 日
Dear @Jos, If I have more observations per day say I will have hourly data so I have serial number 1:24 in each day then how can I make required changes in your codes as I have different number of observations in different data set? Please let me know.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Preprocessing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by