Creating one big loop from smaller ones
2 views (last 30 days)
Show older comments
Hi, I'm trying to come up with a loop for the following:
SP = 2778x1 array
w = 1x252 array
alpha = 1x252 array
beta = 1x252 array
ss = zeros(2527,252);
ss(1,:) = 0;
I need to create one loop which would produce a 2527x252 array for the results for the following 252 smaller loops:
for i = 1:2526
ss(i+1) = w(1,1) + alpha(1,1).*SP(i) + beta(1,1).*ss(i);
end
for i = 2:2527
ss(i+1) = w(1,2) + alpha(1,2).*SP(i) + beta(1,2).*ss(i);
end
..........
for i = 252:2577
ss(i+1) = w(1,252) + alpha(1,252).*SP(i) + beta(1,252).*ss(i);
end
The code I've used is as follows:
for j = 1:252
for i = j:2526+j-1
ss(i+1,j) = w(1,j) + alpha(1,j).*SP(i) + beta(1,j).*ss(i);
end
This code works but it doesn't present the results the way I want i.e. it produces not 2527x252 array but a 2778x252 array and it looks like this:
1) 0 0 0 ... 0
2) # 0 0 ... 0
3) # # 0 ... 0
4) # # # ... 0
... ... ... ... ... ...
2527) # # # ... #
2528) 0 # # ... #
2529) 0 0 # ... #
... ... ... ... ... ...
2778) 0 0 0 ... #
What I need is for this array to have only one initial zero on top of every column. First column was perfect up to observation 2527. I need column two, three and so on to be pulled up, so that each has one zero on top and then another 2526 observations (that makes it 2527 in total). I would appreciate any help I can get on this one.
0 Comments
Accepted Answer
Jan
on 19 Jun 2011
Before I give an advice about a much faster vectorized approach - does this create the wanted output:
EDITED: Index of ss adjusted to Julia's comments:
for j = 1:252
for i = j:2526+j-1
ss(i-j+2, j) = w(j) + alpha(j) * SP(i) + beta(j) * ss(i-j+1, j);
end
end
This takes 0.06 sec on my old 1.5GHz Pentium-M. A vectorization would be useful only if you run this funciton thousands of times. Do you?
13 Comments
Jan
on 19 Jun 2011
@Julia: With the joined power of Matlab and Walter anything is possible - if it is at least deterministic and can be defined by a primitive recursive function.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!