Combining several loops in one big loop
1 view (last 30 days)
Show older comments
Sascha Winter
on 15 Feb 2017
Commented: Sascha Winter
on 16 Feb 2017
Hello everyone,
i need help with the creation of a loop. I have to create a variable which can be described as follows. For each fiscal year, consisting of 12 months from July of one year to July of the next year, i have to put in the same value. Then i have to move one year forward and repeat it, and so on. The matrix should be created from July 1965 till December 2014 (606x16505 double matrix). I have data available for July 1963 to December 2014 (618x16505 double matrix).
For a better understanding of my problem, i have posted the first 5 loops. As you can see this is not an elegant way to deal with this.
% January 1965-June-1965
for t=1:6
NI(t,:) = (log(sasho(13,:)) - log(sasho(1,:)));
end
% July 1965-June 1966 (this is one fiscal year)
for t=7:18
NI(t,:) = (log(sasho(25,:)) - log(sasho(13,:)));
end
% July 1966-June 1967
for t=19:30
NI(t,:) = (log(sasho(37,:)) - log(sasho(25,:)));
end
% July 1967-June 1968
for t=31:42
NI(t,:) = (log(sasho(49,:)) - log(sasho(37,:)));
end
% July 1968-June 1969
for t=43:54
NI(t,:) = (log(sasho(61,:)) - log(sasho(49,:)));
end
...
% July 2014-December 2014
for t=595:600
NI(t,:) = (log(sasho(613,:)) - log(sasho(601,:)));
end
I hope you got my problem and are able to get a better way coding this than I had.
Thanks in advance.
0 Comments
Accepted Answer
Geoff Hayes
on 15 Feb 2017
Sascha - let's first size the NI array appropriately.
NI = zeros(606,16505);
I'm not sure if this is the size you really want since you mention that you only want to collect data from July 1965 until December 2014 (which I think is more like 594 months). Also, your first for loop copies data from January 1965 until June 1965..
Anyway, let's look at your first for loop. We can reduce it to a single line of code if we use repmat as
NI(1:6,:) = repmat((log(sasho(13,:)) - log(sasho(1,:))),6,1);
We repeat the same data six times and copy it directly into the first six rows of NI. And we can do something similar to every other for loop too if we know where to do the appropriate copy. For example,
m = 7;
n = m + 12 - 1;
u = 13;
v = u + 12;
NI(m:n,:) = repmat((log(sasho(v,:)) - log(sasho(u,:))),n - m + 1,1);
We can then put this into a loop as
u = 13;
for m=7:12:595
n = min(600, m + 12 - 1); % since we don't want to exceed 600 which is Dec. 2014
v = u + 12;
NI(m:n,:) = repmat((log(sasho(v,:)) - log(sasho(u,:))),n - m + 1,1);
u = v;
end
I haven't tested the above but I'm hoping that you can follow it and see how we've reduced the many loops to just one by considering the common parts of each.
More Answers (0)
See Also
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!