create an array with an output from a loop
조회 수: 12 (최근 30일)
이전 댓글 표시
Is there a way to create an entirely new array with an output from a loop?
For example:
- If a condition is met, increase or decrease N by 1
- Repeat 1000 times
- Example result: N = 1,2,3,2,1,2,3,4,3,2,3,4,5,4....
- Then, create an array size 1x1000 with resulting N values at each iteration.
- So, final output should be M = [1,2,3,2,1,2,3,4,3,2,3,4,5,4,...]
Thank you
댓글 수: 3
Rik
2020년 10월 28일
A bit more context can be found in the now-deleted question: http://web.archive.org/web/20201028101830/https://webcache.googleusercontent.com/search?q=cache%3Aja8PiVWSBLwJ%3Ahttps%3A%2F%2Fwww.mathworks.com%2Fmatlabcentral%2Fanswers%2F628778-conditional-count-up-and-down-using-matrix-comparison+&cd=1&hl=en&ct=clnk&gl=nl
Where I had posted a comment:
You can avoid a loop if you can find a way to figure out when each customer is leaving. If you manage that, you can mark those times with -1, mark all times where a customer arrives with 1, after which you can use cumsum to generate the N array for all times.
This looks a bit like homework. You can find guidelines for posting homework on this forum here. If you have trouble with Matlab basics you may consider doing the Onramp tutorial (which is provided for free by Mathworks).
Daniel, please don't delete questions if you get a response.
답변 (1개)
Rishabh Mishra
2020년 11월 6일
Hi,
Try out the code given below. I have mentioned appropriate comments to help you get through the code.
% N is the looping variable
N = 1;
% j is used to store value in array
j = 1;
% value of j remains between low & hi
% low & hi are changed within loop as per the description given
low = 1;
hi = 3;
% array to store the required values
arr = [];
% loops & conditional statements
while(N <= 1000)
if j <= hi
arr(N) = j;
j = j+1;
N = N+1;
else
j = j-2;
while(j >= low)
arr(N) = j;
j = j-1;
N = N+1;
low = low+1;
hi = hi+1;
end
end
end
Hope this helps.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!