Efficient way to build a matrix
조회 수: 10 (최근 30일)
이전 댓글 표시
I am looking for a more elegant and efficient way to build a matrix that I need for some subsequent computations and plotting. I start with a matrix called IndexSunrise, which is 1:7000 and holds sequential values but spaced at irregular intervals, e.g. IndexSunrise = [12 45 93 141 194 ... 7000]. I want create a new matrix that includes these plus the 7 sequential values that preceed these, e.g. IndexSunriseFinal = [5 6 7 8 9 10 11 12 37 38 39 40 41 42 43 45 86 87 88 89 90 91 92 93 ... 7000].
Presently I have it like the below
Index1 = IndexSunrise;
Index2 = IndexSunrise-1;
Index3 = IndexSunrise-2;
Index4 = IndexSunrise-3;
Index5 = IndexSunrise-4;
Index6 = IndexSunrise-5;
Index7 = IndexSunrise-6;
IndexSunriseFinal = [Index1 Index2 Index3 Index4 Index5 Index6 Index7];
While this works, it's ugly and inneficient and makes debuging harder (i.e. if I want to look at the 8 or 9 preceeding values instead, I have to rebuild the above).
I'm sure there has to be a better way to do this without using something worse like eval.
Suggestion?
댓글 수: 0
채택된 답변
Atsushi Ueno
2021년 5월 19일
> I want create a new matrix that includes these plus the 7 sequential values that preceed these, e.g. IndexSunriseFinal = [5 6 7 8 9 10 11 12 37 38 39 40 41 42 43 45 86 87 88 89 90 91 92 93 ... 7000].
IndexSunrise = [12 45 93 141 194 7000];
n = 7;
IndexSunriseFinal = repelem(IndexSunrise, n+1) - repmat((n:-1:0), size(IndexSunrise));
>> repelem(IndexSunrise, n+1)
ans = 12 12 12 12 12 12 12 12 45 45 45 45 45 45 45 45 93 93 93 93 93 93 93 93 141 141 141 141 141 141 141 141 194 194 194 194 194 194 194 194 7000 7000 7000 7000 7000 7000 7000 7000
>> repmat((n:-1:0), size(IndexSunrise))
ans = 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
>> repelem(IndexSunrise, n+1) - repmat((n:-1:0), size(IndexSunrise))
ans = 5 6 7 8 9 10 11 12 38 39 40 41 42 43 44 45 86 87 88 89 90 91 92 93 134 135 136 137 138 139 140 141 187 188 189 190 191 192 193 194 6993 6994 6995 6996 6997 6998 6999 7000
추가 답변 (1개)
Steven Lord
2021년 5월 19일
Take advantage of implicit expansion.
IndexSunrise = [12 45 93 141 194 7000]
offsets = (-6:0).'
values = IndexSunrise + offsets
reshape the values array if desired.
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!