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

33 ビュー (過去 30 日間)
zahraa alquraini
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
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 件のコメント
Steven Lord
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
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))
  1 件のコメント
zahraa alquraini
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!

Translated by