Nested For Loops & Creating An Array
Show older comments
I had a question about how to successfully get this piece of code working properly. I start with an initial s value. The basic formula for calculating s is: s(k+1)=s(k)-u(k)+w(k). u may be any value between 0 and 20 in increments of 5 for any k. w is defined for each k as in the array I created below. What I need to end up with is an array of 5 elements in a row with a different value for each different u value used per w at that k and 9 columns (for k between 0 and 8 or k=1:9 in MATLAB terms). The initial value of s in each case will always be 70.
I'm thinking I can simply make a 1xn matrix and reshape it at the end, but the problem for me now is actually in my for loops. I need to generate the values for each s as I've described above before I can do that though. Obviously what I have now is probably incorrect although it may be close. I've tried my best and am simply stuck.
Any help would be much appreciated!
% initial s
s(1)=70;
w=[5 20 -5 5 5 15 -5 5];
u=[0 5 10 15 20];
% constraints
smin=0;
smax=140;
for k=1:8
for i=1:4
s(i+1)=s(i)-u(i+1)+w(k);
% indicate whether s is inplausible
if s(i+1)<smin || s(i)>smax
s(i+1)=-1;
end
end
end
Answers (3)
Walter Roberson
on 21 Feb 2011
Sounds sort of like,
cumsum( [repmat(70,size(u),1), bsxfun(@plus, -u.', w) ], 2)
except for that bit about setting s(i+1) to -1 in some cases, which would affect the sum for the rest of the row. Is it really intended to affect the rest of the row ??
Joseph Chrzan
on 21 Feb 2011
0 votes
1 Comment
Matt Fig
on 21 Feb 2011
Why don't you post the corrected code and give the output you want to see so we can understand better. Give the s you think you should get.
Joseph Chrzan
on 22 Feb 2011
0 votes
Categories
Find more on Entering Commands 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!