Nested For Loops & Creating An Array
显示 更早的评论
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
回答(3 个)
Walter Roberson
2011-2-21
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
2011-2-21
0 个投票
1 个评论
Matt Fig
2011-2-21
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
2011-2-22
0 个投票
类别
在 帮助中心 和 File Exchange 中查找有关 Entering Commands 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!