How to "keep" a variable for some rows within a for loop

Hi,
My problem is the following:
I've created a for-loop in which I calculate SOMETHING(i) for each row (see code below). But I'm not able to keep the variable "SOMETHING" for some rows since i updates this variable in each row.
My goal is not to use the current variable SOMETHING of (i) in each row, I rather wanna calculate c with the same "SOMETHING" for 10 rows.
For example:
In the first 10 rows I would like to use SOMETHING(1) for my calculation of variable c and in row 11 I would like to use
SOMETHING(11) = SOMETHING(1) + c(1) + c(2) + c(3) + c(4) + c(5) + c(6) + c(7) +c(8) + c(9) + c(10)
With SOMETHING(11) I would like to calculate c for the next 10 rows again and so on...
Is there a way to achieve this?
Would I need to use another for loop?
MANY THANKS!!!
WRONG CODE:
for i = length(a)
c(i) = a(i) + b(i) * SOMEHING(i)
SOMETHING(i) = c(i) + SOMETHING(i)
end

 채택된 답변

Ameer Hamza
Ameer Hamza 2020년 4월 22일
편집: Ameer Hamza 2020년 4월 22일
Try something like this
for i = 1:length(a)
idx = floor((i-1)/10)*10 + 1;
c(i) = a(i) + b(i) * SOMEHING(idx);
if mod(i,10)==1
SOMETHING(idx) = c(idx-9:idx) + SOMETHING(idx);
end
end

댓글 수: 8

This approach seems really promising but I'm still confused:
Consider we are in row 10 (i = 10) then idx would be equal to idx = 11.
As c needs to be calculated, I would use SOMETHING(11) which is not calculated in row 10?
I missed that point. Check the updated answer.
Thank you so much for your help but the only change I've noticed is that you replaced 10 by 9 within the if-clause. Since this is only relevant when i = 11 it does not solve my problem. If i would be equal to 10 then idx would be 11.
But c(10) could not be calculated since it would use SOMETHING(11) which is not existent at this step or am I wrong?
No, I chaged this line
idx = floor((i-1)/10)*10 + 1;
Now
i = 10 => idx = 1;
i = 11 => idx = 11;
Sorry, my bad! Now it makes (almost) sense to me, BUT:
Even if i = 11 and idx = 11, c cannot be calculated since SOMETHING(11) is not existent (the if clause is "not used" before).
I would need a calculation for SOMETHING in the last row before the "switch" happens (e.g. row 10) so that the latest value (SOMETHING(1)+c(1:10)) is filled in SOMETHING(11).
Why not move it in this order?
for i = 1:length(a)
idx = floor((i-1)/10)*10 + 1;
if mod(i,10)==1
SOMETHING(idx) = c(idx-9:idx) + SOMETHING(idx);
end
c(i) = a(i) + b(i) * SOMEHING(idx);
end
Oops! Unfortunately I was out of my mind...this little tweak makes totally sense!
Thank you so much!!!
I am glad to be of help.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2020년 4월 22일

댓글:

2020년 4월 22일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by