matlab cody学习笔记 day8

(1)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 ]

答:

b = zeros(n);
b(:) = (1:n.^2);
c = flipud(b);
b(:,2:2:size(b,2)) = c(:,2:2:size(b,2));
b=b';
end

答:

x=reshape(1:n*n,n,n)';
for i =2:2:n
x(i,:)=flip(x(i,:));
end
b=x;

虽然第二种方法有循环,但是速度更快。

(2)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

答:

[x,r]=min(sum(a==0,2));

[x,r]=max(sum(a~=0,2));

(3)Return the 3n+1 sequence for n

A Collatz sequence is the sequence where, for a given number n, the next number in the sequence is either n/2 if the number is even or 3n+1 if the number is odd. The sequence always terminates with 1.

So if

n = 13

then

c = [13 40 20 10 5 16 8 4 2 1]

答:

c=n;
while n>1
if mod(n,2)
n =3*n+1;
else
n =n/2;
end
c=[c n];
end

猜你喜欢

转载自blog.csdn.net/yxnooo1/article/details/113814593