MATLAB: How can i make the Temp matrix to contain all the values of T calculated in both conditions

zeros

I want to make a Temp matrix which contains the T values calculated for tow conditions (H<=11) and (H>11). This code which i have written doesnt give me a matrix but gives a value. Also MATLAB says 'Size vector must be a row vector with real elements'. How do i solve this

Best Answer

H = [ 1:10:100]
L = 0.0065 %K/m
T0= 288.15
Temp= zeros(j)
for j= 1:length(H)
for B = H<=11 % till 11 km
T = T0 - L*B %K
for C= H> 11
T = 216.65 %constatnt -56.5deg
end
end
Temp(j)= T
end
There are a couple of things about your code. First, are you aware that H is only [1 11 21 31 ... 81 91]? This does not seem like a very wide range to be covering for an accurate mach calculations, specifically at low altitudes.
Second, and really the answer to your question, you don't need the for loops for B and C, you would be much better suited to use an if statement. I would modify your code as follows:
for j = 1:length(H)
if H(j) <= 11
Temp(j) = T0 - L*H(j);
else % Covers H > 11
Temp(j) = 216.65;
end
end
This uses the principle of indexing, where we are drawing our input from a specific location in the input array, and outputting into a specific indexed position on the output array. I'm assuming you already know how to do this because it appears you were using it for indexing Tem(j) = T before.
Alternatively, you can simply remove the for loop all together and use vector math to complete the calculations in a greater swoop.
Temp = T0 - L*H(H<=11);
Temp = [Temp; 216.65+0*H(H>11)]; % Using 0*H(H>11) is intended to give the correct number of elements, there are alternative ways of accomplishing this
This method using logic indexing and vectorization, where we have identified the elements we want with a logic statement in our index, and then operated on all of the values at one time by treating them as a vector. For your case this removes the need for loops, and is often regarded as more computationally efficient.