- using cell arrays
Appending arrays of different length
29 ビュー (過去 30 日間)
古いコメントを表示
Dear all,
My goal is to have an array with 8760 rows (number of hours in a year). Each row should now indicate the day-number of each month, which will mean that I have in the first rows 23x the number 1, then 23 times the number 2, ..... till the end of the month 23 times the number 31 (for January). Then it begins again with 23 times 1,...., till the end of February with 23 times 28.
I have created the following code:
n=23 ;
x31=(1:31)';
x30=(1:30)';
x28=(1:28)';
Jan=repmat(x31,1,n)';
Jan=Jan(:)';
Feb=repmat(x28,1,n)';
Feb=Feb(:)';
Mar=repmat(x31,1,n)';
Mar=Mar(:)';
Apr=repmat(x30,1,n)';
Apr=Apr(:)';
Mai=repmat(x31,1,n)';
Mai=Mai(:)';
Jun=repmat(x30,1,n)';
Jun=Jun(:)';
Jul=repmat(x31,1,n)';
Jul=Jul(:)';
Aug=repmat(x31,1,n)';
Aug=Aug(:)';
Sep=repmat(x30,1,n)';
Sep=Sep(:)';
Okt=repmat(x31,1,n)';
Okt=Okt(:)';
Nov=repmat(x30,1,n)';
Nov=Nov(:)';
Dez=repmat(x31,1,n)';
Dez=Dez(:)';
Now, I would like to append the rows to have one big array of 8760 rows (= time.day(8760,1)) that each indicate the day-number.
However, the code cat() does not allow me to append two arrays of different length.
I am very pleased for a hint.
With kind regards
1 件のコメント
Kevin Hellemans
2020 年 7 月 28 日
Hi Maria,
Matlab does not allow you to concatenate vectors of different lengths. I also don't understand why you would want to do this, but that's not for me to decide
So, you have two options:
[{Jan};{Feb}]
ans =
2×1 cell array
{1×713 double}
{1×644 double}
2. Filling up the short rows with NaN (or other) values to match the size of longer vectors
Feb(end:713) = NaN;
MyArray = [Jan;Feb];
Neither is a very elegant solution, but should get you on you way.
採用された回答
neil jerome
2020 年 7 月 28 日
didn't quite understand what output you really are looking for, but this shows how to use cat(). (note that with n=23, the result is not 8760 rows but 8395; do you want n=24?).
vertcat() and horzcat() are versions of cat() with implicit directions, so these three lines are all equivalent:
longList = cat(1, Jan',Feb',Mar',Apr',Mai',Jun',Jul',Aug',Sep',Okt',Nov',Dez'); % specify dimension in first input
longList1 = vertcat(Jan',Feb',Mar',Apr',Mai',Jun',Jul',Aug',Sep',Okt',Nov',Dez');
longList2 = horzcat(Jan,Feb,Mar,Apr,Mai,Jun,Jul,Aug,Sep,Okt,Nov,Dez)';
always useful to scroll to the bottom of the help pages for the 'See Also' section for any function :)
2 件のコメント
その他の回答 (1 件)
Steven Lord
2020 年 7 月 28 日
Use datetime, hours, and the colon operator : to build your array of dates and times all at once. Note that when doing so you will need to specify a year so MATLAB knows how long the year should be: 2020 is longer than 2019 by one day, for example.
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!