Need to run two counters in a foor loop
조회 수: 5 (최근 30일)
이전 댓글 표시
Here is my problem.
I have two lists of the same length = A. The lists are P and T.
I anticipate to be running a for loop (for ls=1:A) embedded in another foor loop (for i = 1:ls).
Below is what I would like to get when the loops are running:
ls = 1
i = 1
P(1) + T(1);
ls = 2
i = 1
P(1) + T(2);
i = 2
P(2) + T(1);
ls = 3
i = 1
P(1) + T(3);
i = 2
P(2) + T(2);
i = 3
P(3) + T(1);
ls = 4
i = 1
P(1) + T(4);
i = 2
P(2) + T(3);
i = 3
P(3) + T(2);
i = 4
P(4) + T(1);
....... and so on until the lenght of A
I need help in making the counter with T go backwards from the value of ls. Create a dynamic vector in the loop is not a good idea
for ls=1:A
K = ls:-1:1
for i=1:ls
P(i)+T(K(i))
end
end
Id appreciate for someone's help as I have spent 3 hours trying to come up with a solution for this and got to no where. Maybe a formula instead of the "????" below.
for ls=1:A
for i=1:ls
P(i)+T(????)
end
end
Thank you.
댓글 수: 0
답변 (3개)
David Fletcher
2021년 5월 1일
One way of recreating your original sequence via the loops would be:
A=ones(1,5);
for iterator=1:length(A)
sub=0;
fprintf('outer loop: %d\n',iterator)
for ls=1:iterator
fprintf('P(%d) + T(%d)\n',ls,iterator-sub)
sub=sub+1;
end
iterator=iterator+1;
end
This gives:
outer loop: 1
P(1) + T(1)
outer loop: 2
P(1) + T(2)
P(2) + T(1)
outer loop: 3
P(1) + T(3)
P(2) + T(2)
P(3) + T(1)
outer loop: 4
P(1) + T(4)
P(2) + T(3)
P(3) + T(2)
P(4) + T(1)
outer loop: 5
P(1) + T(5)
P(2) + T(4)
P(3) + T(3)
P(4) + T(2)
P(5) + T(1)
댓글 수: 0
Steven Lord
2021년 5월 1일
F = 3;
S = 4;
for first = 1:F
fprintf("Counting up, first is %d\n", first)
for second = S:-1:1
fprintf("Counting down, second is %d\n", second)
fprintf("The equivalent counting up inner counter would be %d\n", S-second+1)
end
fprintf(" \n")
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!