In: Mechanical Engineering
Part 2: MATLAB
Exercise 1 (50 pts)
Write a program that tells the user if a city of their choice is in a tropical, temperate, or polar region. Use the cities.txt file provided in the Files section of this class. Your program should read the data in that file, find the city given by the user, and return a text message with the information. If the city is not found, your program should write a message accordingly. To decide which region each city falls into, use the table below.
Latitude | Region |
Above 66 N | Polar |
Between 35 N and 66 N | Temperate |
Between 35 S and 35 N | Tropical |
Between 35 S and 66 S | Temperate |
Below 66 S | Polar |
HINT: If you follow the file reading methods explained in our video tutorial, your data will be in cell format. There are a few functions that could be very useful in this case: strcmp compares two strings (one of which can be in a cell) to see if they match. Also, cell2mat converts a cell array into an ordinary array. Finally, find finds indices and values of any non-zero elements in an array.
See the output examples below:
What city are you interested in? Caracas Caracas is in a tropical region What city are you interested in? Merced City not found!
https://catcourses.ucmerced.edu/files/1587454/download?download_frd=1
clc
% declaring filename
filename = 'cities.txt';
% reading file
[data] = readFile(filename);
% declaring latitude array
latitude = [];
% getting cities
cities = lower(data{3});
%reading the latitudes and storing in the variables
for ii = 1:numel(data{1})
tokens = strsplit(char(data{1}(ii)), '°');
latitude = [latitude, str2num(tokens{1})];
end
% inputting city from user
cityName = input('What city are you interested in? ', 's');
% getting the index position from cities array
index = find(contains(cities, lower(cityName)));
% chacking whether city exist or not
if index ~= -1
% if yes then get citiy's latitude with that index
cityLat = latitude(index);
% getting the city type using sub-function
cityType = getRegionType(cityLat);
% printing
fprintf('%s is in a %s region\n', cityName, cityType)
else
% else if city not found then print this error
fprintf('City not found!\n')
end
% Sub-Function To read file and store the contents in a cell
% array and return it
function [data] = readFile(filename)
fid = fopen(filename, 'r');
if fid == -1
error(['Error! file ''', filename, ''' not found'])
end
data = textscan(fid, '%s%s%s%s%s', 'HeaderLines', 1,
'delimiter', '\t');
end
% Sub-Function to calculate and return the region
% type
function [type] = getRegionType(lat)
type = 'NA';
if lat > 66
type = 'Polar';
elseif (lat > 35 && lat <= 66)
type = 'Temperate';
elseif (lat >= 0 && lat <= 35)
type = 'Tropical';
end
end
output