接着更新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)