How do I specify time increment in computation in for loop?
8 次查看(过去 30 天)
显示 更早的评论
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?
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/650755/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/650760/image.png)
0 个评论
回答(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
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
2 个评论
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.
Hope it can help you.
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))
另请参阅
类别
在 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!