Efficient way to build a matrix
Show older comments
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?
Accepted Answer
More Answers (1)
Take advantage of implicit expansion.
IndexSunrise = [12 45 93 141 194 7000]
offsets = (-6:0).'
values = IndexSunrise + offsets
reshape the values array if desired.
1 Comment
David Velasco
on 19 May 2021
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!