How do I generate a matrix from a function?

조회 수: 52 (최근 30일)
Nolan Bell
Nolan Bell 2019년 11월 16일
편집: the cyclist 2019년 11월 16일
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?

답변 (2개)

the cyclist
the cyclist 2019년 11월 16일
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 2019년 11월 16일
편집: the cyclist 2019년 11월 16일
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.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by