Need to run two counters in a foor loop
2 次查看(过去 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!