Part 4. Problem 31 - Problem 40.
Problem 31. Remove all the words that end with "ain"
% Given the string s1, return the string s2 with the target characters removed.
%
% For example, given
%
% s1 = 'the main event'
%
% your code would return
%
% s2 = 'the event'
%
% Note the 2 spaces between "main" and "event" Only the four letters in the word "main" were deleted.
function s2 = remAin(s1)
s2 = [];
s1 = regexp(s1, '\w*ain\>', 'split');
for k = 1:length(s1)
s2 = [s2 s1{k}];
end
去掉以ain结尾的单词。'\>'表示单词结尾。'split'参数表示以匹配的字符串为分割。
UPD: 同样可以用regexprep写。
function ans = remAin(s1)
regexprep(s1, '\w*ain\>', '');
Problem 32. Most nonzero elements in row
% Given the matrix a, return the index r of the row with the most nonzero elements. Assume there will always be exactly one row that matches this criterion.
%
% Example:
%
% Input a = [ 1 2 0 0 0
% 0 0 5 0 0
% 2 7 0 0 0
% 0 6 9 3 3 ]
% Output r is 4
function r = fullest_row(a)
r = 1; mxlen = 0; sa = size(a);
for k = 1:sa(1)
now = length(find(a(k,:) ~= 0));
if now > mxlen
mxlen = now;
r = k;
end
end
UPD: 可以改写成避免loop的形式.
function r = fullest_row(a)
[~, r] = max(sum(a ~= 0, 2));
Problem 33. Create times-tables
% At one time or another, we all had to memorize boring times tables. 5 times 5 is 25. 5 times 6 is 30. 12 times 12 is way more than