[matlab]mathworks上的cody challenge题解及一些常用函数的总结(4)

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 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值