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!