# How do I specify time increment in computation in for loop?

조회 수: 36(최근 30일)
zahraa alquraini 2021년 6월 12일
댓글: Steven Lord 2021년 6월 12일
I have plugged the equation below in MATLAB. I'm using the for loop to compute the function 10 times. I want to run the function from time 0 to 5 with time increment of 0.5. So I have total time: t = [ 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5 ]. The problem is that the "for end" command in MATLAB takes the number of index not the value of time so I set the time t with incr = 0.5 inside the function in the exponent but it doesn't happen to pick up the value either. How do I let it compute the time t using the values above instead of the index from 1:10 ?
any suggestion on this problem?  댓글을 달려면 로그인하십시오.

### 답변(2개)

Steven Lord 2021년 6월 12일
for loops can iterate over arbitrary vectors, not just 1:something.
x = 1:0.5:5;
for k = x
fprintf("The value of k is %f.\n", k)
end
The value of k is 1.000000. The value of k is 1.500000. The value of k is 2.000000. The value of k is 2.500000. The value of k is 3.000000. The value of k is 3.500000. The value of k is 4.000000. The value of k is 4.500000. The value of k is 5.000000.
Or you could iterate over the indices of a vector:
for n = 1:numel(x)
fprintf("The value of element %d of x is %f.\n", n, x(n))
end
The value of element 1 of x is 1.000000. The value of element 2 of x is 1.500000. The value of element 3 of x is 2.000000. The value of element 4 of x is 2.500000. The value of element 5 of x is 3.000000. The value of element 6 of x is 3.500000. The value of element 7 of x is 4.000000. The value of element 8 of x is 4.500000. The value of element 9 of x is 5.000000.
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Steven Lord 2021년 6월 12일
Can you show us the code you wrote using this technique that threw the error? It's possible that it just needs minor changes to get it working.

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

Mouhamed Niasse 2021년 6월 12일
Hello,
I just tried to plot your equation epsilon(t) for time range 0-5s assuming constant value for t0, and arrays Ei and tau_i.
Eps=sym('t')
t0=1;
time=0:0.5:5
n=length(time);
Ei=ones(1,length(time));
tau=ones(1,length(time));
Eps(t)=0;
for k=1:n
Eps=Eps+(t0/Ei(k))*(t+tau(k)*(-1+exp(-t/tau(k))));
end
Eps
plot(time,Eps(time))
##### 댓글 수: 1표시숨기기 없음
zahraa alquraini 2021년 6월 12일
I tried it and it worked for me it is graphing the right shape that the function should give. Thank you!
However It's giving me an answer in terms of equation is there a way to simplify the solution so I can track the values? 댓글을 달려면 로그인하십시오.

R2020a

### Community Treasure Hunt

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

Start Hunting!