MATLAB Answers

0

What's wrong with my for loop?

Asked by Jahsiah Toby on 3 Oct 2019
Latest activity Edited by Shubham Gupta on 3 Oct 2019
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

  0 Comments

Sign in to comment.

2 Answers

Answer by Shubham Gupta on 3 Oct 2019
Edited by 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

  0 Comments

Sign in to comment.


Answer by Cris LaPierre
on 3 Oct 2019
Edited by 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

  0 Comments

Sign in to comment.