MATLAB: I would like to create a for-loop for a vector T1 consisting of 21 elements where all are zero except the first, in order to get T2, which also has 21 elements, (temperature elements).

for loop

This with the formula: Ti(t+0.28) = 0.5*(T(i+1)-2*Ti+T(i-1)). My code right now is:T1=zeros(21); T1(1)=22; T2=linspace(0,0.3,21); But I got no clue how to write the for-loop in this case. Greatful for help

Best Answer

Dear Gustaf, still I have confusions in understanding the problem. However as I understood I wrote a small code which you can run and then tell me you need this or something else:
T1 = zeros(1,21);
T2 = T1;
T1(1) = 22;
for i = 1:length(T1)
if i == 1
T2(i) = 0.5 * (T1(i + 1) - 2 * T1(i));
else if i < length(T1)
T2(i) = 0.5 * (T1(i+1) - 2 * T1(i) + T1(i-1));
else
T2(i) = 0.5 * (-2 * T1(i) + T1(i-1));
end
end
end
disp(T1)
disp(T2)
Related Question