Using loops, print a table showing wind chill factors
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
jarvan
am 9 Nov. 2014
Kommentiert: jarvan
am 9 Nov. 2014
hi guys,
I am writing a function that need to print a table showing wind chill factors,which temperatures is -25:5:55(in column), ind speed is 0:5:55(in row). Now I have to calculate the value in the table, the forumla is 35.7 + 0.6*t- 35.7*(v^0.16) + 0.43*t*(v^0.16);
0 5 10 15 20 25 30 35 40 45 50
-25
-20
-15
-10
-5
0
5
10
15
20
25
30
35
40
45
50
55
So far , I got
function y = wcf(t,v)
y = 35.7 + 0.6*t- 35.7*(v^0.16) + 0.43*t*(v^0.16);
for i= -25:5:55;j= 0:5:55;
A(i,j) = wcf(t*(i),v*(j));
end
end
I know I can use a function wcf(x,y) to produce a matrix of values A(i, j) = f( x(i), y(j) ), for i=1:length(x), j= 1:length(y), by using a nested for-loop. However, I still don't know how to calculate in middle part of the table.
0 Kommentare
Akzeptierte Antwort
Geoff Hayes
am 9 Nov. 2014
Jarvan - if your function is to return a table (or matrix) of wind chill values using temperature and wind speed, then it seems that you function should be defined as
function A = wcf(t,v)
where A is the table of wind chill values, t is the temperature vector, and v is the wind speed vector. This would mean that you wouldn't hard code the temperatures and speeds in the code (as you have done) but instead use the two vectors as inputs to your wind chill equation. So if
t = -25:5:55;
v = 0:5:50;
then
A = wcf(t,v);
The trick then is how to calculate A. Your function need not be recursive (as you have shown), but the nested loop idea is a good starting point (there are other ways to simplify the calculation using element-wise operations, but for now let's keep your method). We would want to iterate over each temperature and speed pair, so let us do the following
function A = wcf(t,v)
% get the number of temperature and speed elements
numTemps = length(t);
numSpeeds = length(v);
% size A
A = zeros(numTemps,numSpeeds);
% populate A
for m=1:numTemps
for n=1:numSpeeds
A(m,n) = 35.7 + 0.6*t(m)- 35.7*(v(n)^0.16) + 0.43*t(m)*(v(n)^0.16);
end
end
The above code is not all that much different from what you have. I replaced the indices with m and n because i and j are also used to represent the imaginary number (and so it is good practice to avoid using them as indices for looping). Try it and see what happens!
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!