Create a for cycle over an array

In my case I have X different job with Y different duration
D = [2 3 4 4 5 6 7 3 ];
so job X=1 will last Y=2.
I need to write a code that give me the following result:
tin1= 0 , tfin1=2, tin2= 2 , tfin2=2+3=5, tin3= 5 , tfin3=5+4=9, tin4=9 , tfin4=9+4=13........ So "tinx" means the inital time of job x, while "tfinx" means the final time of job x. if job one finish at 2, the job two will finish at 2 plus the duration of the job 2 (3) obtaining 5, and so on.
I want to write a code that is able to generate all this value
Does someone help me? the length of D should be variable so I would like to obtain a code that is independent from its length

2 commentaires

Jan
Jan le 4 Sep 2019
I've cleaned the tags. It is not useful to use a pile of tags, which have no relation to your problem.
Steven Lord
Steven Lord le 4 Sep 2019
I'm trimming more of the tags.

Connectez-vous pour commenter.

 Réponse acceptée

Jan
Jan le 4 Sep 2019
Modifié(e) : Jan le 4 Sep 2019

0 votes

Do not create a bunch of variables with an index hidden in the names: See TUTORIAL: Why and how to avoid Eval
I assume all you need is:
D = [2 3 4 4 5 6 7 3 ]
T = cumsum([0, D])
Now e.g. T(1) and T(2) contain everything you want. This is much better than tin(1) and tfin(1). If you really need 2 variables:
Tini = T(1:end-1);
Tfin = T(2:end);

5 commentaires

I would like to obtain this values with a for loop, instead of CUMSUM
k = size(M,2)
for k=1:k
tin1(1)=0
tfin1(1)=M(1)
....
tink(k)=tfink-1(k-1) % of the last element
tfin(k)=M(k)
end
but I don't know how to solve it.
Fabio Freschi
Fabio Freschi le 4 Sep 2019
why?
Jan
Jan le 4 Sep 2019
Modifié(e) : Jan le 4 Sep 2019
Len = size(D, 2);
s = 0;
for k = 1:Len
tini(k) = s;
tfin(k) = D(k) + s;
s = tfin(k);
end
Again: Do not hide indices in the names of the variables, but use indices for this job.
Or:
Len = numel(D);
tini = zeros(1, Len); % Pre-allocation
tfin = zeros(1, Len);
s = 0;
for k = 1:Len
tini(k) = s;
s = s + D(k);
tfin(k) = s;
end
luca
luca le 4 Sep 2019
Cause this is a general case, then I have to implement the for loop that I've asked for in a more complicated case
luca
luca le 4 Sep 2019
thanks !

Connectez-vous pour commenter.

Plus de réponses (2)

darova
darova le 4 Sep 2019

0 votes

It is a job for cumsum() function:
D = [2 3 4 4 5 6 7 3 ];
tin1 = [0 2 5 9 13 18 24 31];
tin2 = [2 5 9 13 18 24 31 34];]
Fabio Freschi
Fabio Freschi le 4 Sep 2019

0 votes

Try this
>> tfin = cumsum(D)
tfin =
2 5 9 13 18 24 31 34
>> tin = [0 tfin(1:end-1)]
tin =
0 2 5 9 13 18 24 31

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Produits

Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by