Info

This question is closed. Reopen it to edit or answer.

What's wrong with my for loop?

1 view (last 30 days)
Jahsiah Toby
Jahsiah Toby on 3 Oct 2019
Closed: MATLAB Answer Bot on 20 Aug 2021
I want to calculate the temperature of an object at certain times and record them all in a matrix. I cant get seem to get reasonable temperatures or get them in matrix for. The T_i and T_new values shouldnt excede 160. i would like to recall T values for 0 to 200 seconds in an array but use a 0.01 time step to plot the data eventually.
Thank you

Answers (2)

Shubham Gupta
Shubham Gupta on 3 Oct 2019
Edited: Shubham Gupta on 3 Oct 2019
You don't need final 2 lines inside the 'for' loop to update 't'. t is automatically updated because of 'for' loop statement.
Define t vector as :
dt = 0.01; %sample time
tend = 200; %end time
t = 0:dt:tend; % t array
use for loop as follows:
T_new = zeros(size(t));
T_new(1) = T_inf;
for i = 1:size(t,2)-1
T_new(i+1) = T_new(i) + (q./t(i)./1000)/(m*c) - (h*A/m/c)*((q./t(i)./1000)/(m*c)) + T_new(i) -T_inf;
end
T_new

Cris LaPierre
Cris LaPierre on 3 Oct 2019
Edited: Cris LaPierre on 3 Oct 2019
You are currently overwriting your loop counter variable (t). This is incremented automatically by the for loop. You don't need the last 2 lines of code in your for loop.
You are also overwriting your value for T_new everytime. Instead, use your loop counter to store each temperature value in a unique column or row of T_new.
T_new(t) = ...
I also don't think you need to do this symbolicaly. You can remove the syms t at the top as well.
BTW, to create a vector of times from 0 to 200 with a 0.01 step size, you could just do the following code:
t = 0:0.01:200

Products

Community Treasure Hunt

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

Start Hunting!