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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值