MATLAB: Help to find the mistake in the code, or tell me what’s wrong.

interpolationMATLAB

So here's code:
clc
clear
T0 = [5; 7.5; 10; 12.5; 15; 17.5; 20; 22.5; 25; 27.5; 30];
h0 = [3.3; 7.5; 41.8; 51.8; 61; 101.1; 132.9; 145.5; 171.4; 225.8; 360];
T = 5:0.5:30;
[m n] = size (T);
i=1;
for j=1:n
if T(1,j)<=T0(i+1,1)
h(j,1)=h0(i,1)+ ((h0(i+1,1)-h0(i,1))/(T0(i+1,1)-T0(i,1)))*(T(1,j)-T0(i,1));
fprintf(' %11.5f %11.5f\n',T(1,j), h(j,1))
end
if T(1,j)>T0(i+1,1)
i=i+1;
end
end
plot(T,h)
What I doing here is linear interpolation. Code works fine, and it even print everything out:
5.00000 3.30000
5.50000 4.14000
6.00000 4.98000
6.50000 5.82000
7.00000 6.66000
7.50000 7.50000
8.50000 21.22000
9.00000 28.08000
9.50000 34.94000
10.00000 41.80000
11.00000 45.80000
11.50000 47.80000
12.00000 49.80000
12.50000 51.80000
13.50000 55.48000
14.00000 57.32000
14.50000 59.16000
15.00000 61.00000
16.00000 77.04000
16.50000 85.06000
17.00000 93.08000
17.50000 101.10000
18.50000 113.82000
19.00000 120.18000
19.50000 126.54000
20.00000 132.90000
21.00000 137.94000
21.50000 140.46000
22.00000 142.98000
22.50000 145.50000
23.50000 155.86000
24.00000 161.04000
24.50000 166.22000
25.00000 171.40000
26.00000 193.16000
26.50000 204.04000
27.00000 214.92000
27.50000 225.80000
28.50000 279.48000
29.00000 306.32000
29.50000 333.16000
30.00000 360.00000
but when I print out h at the end of the code it's like this:
3.3000
4.1400
4.9800
5.8200
6.6600
7.5000
0
21.2200
28.0800
34.9400
41.8000
0
45.8000
47.8000
49.8000
51.8000
0
55.4800
57.3200
59.1600
61.0000
0
77.0400
85.0600
93.0800
101.1000
0
113.8200
120.1800
126.5400
132.9000
0
137.9400
140.4600
142.9800
145.5000
0
155.8600
161.0400
166.2200
171.4000
0
193.1600
204.0400
214.9200
225.8000
0
279.4800
306.3200
333.1600
360.0000
where does those zeros appear from? Any ideas?
Thank you in advance 🙂

Best Answer

clc
clear
T0 = [5; 7.5; 10; 12.5; 15; 17.5; 20; 22.5; 25; 27.5; 30];
h0 = [3.3; 7.5; 41.8; 51.8; 61; 101.1; 132.9; 145.5; 171.4; 225.8; 360];
T = 5:0.5:30;
[m n] = size (T);
i=1;
for j=1:n
if T(1,j)<=T0(i+1,1),
h(j,1)=h0(i,1)+ ((h0(i+1,1)-h0(i,1))/(T0(i+1,1)-T0(i,1)))*(T(1,j)-T0(i,1));
fprintf(' %11.5f %11.5f\n',T(1,j), h(j,1));
end
if T(1,j)>=T0(i+1,1) %%%%%>= instead >
i=i+1;
end
end
plot(T,h)