Part 7. Problem 61 - Problem 70.
Problem 61. Find state names that end with the letter A
% Given a list of US states, remove all the states that end with the letter A.
%
% Example:
%
% Input s1 = 'Alabama Montana Nebraska Vermont Nevada';
% Output s2 is ' Vermont ';
function s2 = refcn(s1)
s2 = [];
s1 = regexp(s1, 'New \w*a\>|North \w*a\>|West \w*a\>|\w*a\>', 'split');
for k = 1:length(s1)
s2 = [s2 s1{k}];
end
UPD: 用regexprep改写。
function ans = refcn(s)
regexprep(s, '\<((New|North|West) )?\w*a\>', '');
end
Problem 62. Elapsed Time
% Given two date strings d1 and d2 of the form yyyy/mm/dd HH:MM:SS (assume hours HH is in 24 hour mode), determine how much time, in decimal hours, separates them. Assume d2 is always later than d1.
%
% Example:
%
% Input d1 = '2010/12/14 12:00:00'
% Input d2 = '2010/12/14 13:06:36'
% Output elapsed is 1.11
function elapsed = elapsed_time(d1, d2)
elapsed = 24*(datenum(d2) - datenum(d1));
datenum可以将一个日期格式的字符串转换为距离0/0/0 0:00:00的时间,单位是小时。
Problem 63. Encode Roman Numerals
% Create a function taking a non-negative integer as its parameter and returning a string containing the Roman Numeral representation of that integer.
%
% By convention, "modern" Roman numerals are written by expressing each digit separately starting with the leftmost digit and skipping any digit with a value of zero.
%
% Examples
%
% If n is 1990 then romStr = 'MCMXC' since 1000=M, 900=CM, 90=XC.
% If n is 2008 then romStr = 'MMVIII' since 2000=MM, 8=VIII.
% If n is 1666 then romStr = 'MDCLXVI'.
% If n is 0 then romStr is empty ([] and '' are both acceptable)
%
% n will always be an integer between 0 and 3999 (inclusive).
%
% This problem is adapted from Rosetta Code.
function romStr = dec2rom(n)
roman = {'M', 'CM', 'D', 'C