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

接着更新Part 2. Problem 11 - Problem 20

Problem 11. Back and Forth Rows

% Given a number n, create an n-by-n matrix in which the integers from 1 to n^2 wind back and forth along the rows as shown in the examples below.
% 
% Examples:
% 
%  Input  n = 3
%  Output a = [ 1 2 3
%               6 5 4
%               7 8 9 ]
% 
%  Input  n = 4
%  Output a = [ 1     2     3     4
%               8     7     6     5
%               9    10    11    12
%              16    15    14    13 ]

function b = back_and_forth(n)
b = zeros(n, n); now = 1;
for k = 1:n
    if mod(k, 2)
        b(k,:) = now:now+n-1;
    else
        b(k,:) = now+n-1:-1:now;
    end
    now = now + n;
end
mod(n,m),求模运算。相对应还有rem(n,m),求余运算。

Problem 12. Fibonacci sequence

function f = fib(n)
a = 1; b = 1; f = 1;
for k = 3:n
  f = a + b; a = b; b = f;
end

Problem 13. Remove all the consonants

% Remove all the consonants in the given phrase.
% 
% Example:
% 
%  Input  s1 = 'Jack and Jill went up the hill'; 
%  Output s2 is 'a a i e u e i';

function s2 = refcn(s1)
s2 = [];
s1 = regexp(s1, '[aeiouAEIOU0-9_\W]', 'match');
for k = 1:length(s1)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值