for loop for two particular days of a week

조회 수: 3(최근 30일)
Hi,
I am trying to make a for loop counting each monday and thursay for some period of time like one year. I want to start with coming Monday, 08/08/2022 counting it as 1 then Thursday 4, next monday 8, next Thursday 11 and upto a total of 100 Monday plus Thursday.
The vector looks like this V=[1 4 8 11 ......................]. It is going to be inconvinent to write all elements of this vector if a long period of time like 2 years choosen. I am trying to use a for loop and generalize above vector.
Any suggestions will be highly apperciated.
Thanks
Dharma

채택된 답변

sudobash
sudobash 2022년 8월 7일
Hi!
As per my understanding, you want to create a vector of the following sequence: 1, 4, 8, 11, 15, 18,...
This is how you could do it using a while loop:
vec = [1];
while length(vec) < 100
% Check if previous element was Monday
if mod(length(vec),2) == 1
% Add 3 to last element to get Thursday
vec = [vec vec(end)+3];
else
% Add 4 to last element to get back Monday
vec = [vec vec(end)+4];
end
end
vec
vec = 1×100
1 4 8 11 15 18 22 25 29 32 36 39 43 46 50 53 57 60 64 67 71 74 78 81 85 88 92 95 99 102
Hope this solves your problem.
  댓글 수: 1
Dharma Khatiwada
Dharma Khatiwada 2022년 8월 7일
Thank you!
I just have one more question.
I need to write a for loop below vector 'vec' such that loop picks only for the element of 'vec'.
For example, for i=1, 4, 8, 11, 15, ...........
c2(i)=...............
Could you please help me?
Dharma

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

추가 답변(1개)

Voss
Voss 2022년 8월 7일
n_weeks = 50;
vec = reshape((0:n_weeks-1)*7+[1;4],1,[]);
  댓글 수: 1
Dharma Khatiwada
Dharma Khatiwada 2022년 8월 8일
Thank you!
It worked perfectly.

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

Community Treasure Hunt

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

Start Hunting!

Translated by