How do I generate a matrix from a function?

58 views (last 30 days)
Nolan Bell
Nolan Bell on 16 Nov 2019
Edited: the cyclist on 16 Nov 2019
for wind_speed = 15:5:115
for air_temp=-60:5:10
Wind_Chill(air_temp,wind_speed)
end
fprintf('\n')
end
Wind_Chill.m
function wind_chill = Wind_Chill(air_temp,wind_speed)
%calculates the wind chill factor
wind_chill= 13.12 + 0.6215*air_temp-11.37*(wind_speed)^0.16+0.5965*(air_temp)*wind_speed^0.16;
end
This is the code I have so far. It loops through the differnt values of wind speed and air temperature to generate values of the wind chill factor. It is giving me all of the data I need in ans= xxxx form. Is there an easy way to create a matrix of the data?

Answers (2)

the cyclist
the cyclist on 16 Nov 2019
Here is one way to do it, via similar for loops to what you set up.
wind_speed_range = 15:5:115;
air_temp_range = -60:5:10;
numberWindSpeeds = numel(wind_speed_range);
numberAirTemps = numel(air_temp_range);
wc = zeros(numberAirTemps,numberWindSpeeds)
for nw = 1:numberWindSpeeds
for na = 1:numberAirTemps
wind_speed = wind_speed_range(nw);
air_temp = air_temp_range(na);
wc(na,nw) = Wind_Chill(air_temp,wind_speed); % After the loops are done, this will be your matrix
end
end

the cyclist
the cyclist on 16 Nov 2019
Edited: the cyclist on 16 Nov 2019
Here is a better way to do it, without for loops at all:
wind_speed_range = 15:5:115;
air_temp_range = -60:5:10;
[ww,aa] = meshgrid(wind_speed_range,air_temp_range);
wc = Wind_Chill(aa,ww);
function wind_chill = Wind_Chill(air_temp,wind_speed)
%calculates the wind chill factor
wind_chill= 13.12 + 0.6215*air_temp-11.37*(wind_speed).^0.16+0.5965*(air_temp).*wind_speed.^0.16;
end
Note that I slightly changed the function, to handle the elementwise array operation.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!