matlab cody学习笔记 day9

这篇博客探讨了两个编程问题:(1)计算2的幂次方的各位数字之和;(2)找出一组年龄数据中最高龄者的姓名。在第一个问题中,通过循环和取模运算实现数字累加;第二个问题通过查找最大值的索引获取最年长者的名字。这两个问题展示了基础数学和编程技巧如何结合解决实际问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(1)Summing digits

Given n, find the sum of the digits that make up 2^n.

Example:

Input n = 7

Output b = 11

since 2^7 = 128, and 1 + 2 + 8 = 11..

 

答:

function b = sumDigits(n)

pow = 2^n;

b = 0;

while pow~=0

b = b +mod(pow,10);

pow = floor(pow/10);

end

合理利用公式计算的求余,即可得到一个数字的累加。

(2) Find the Oldest Person in a Room

Given two input vectors:

  • name - user last names
  • age - corresponding age of the person

Return the name of the oldest person in the output variable old_name.

这道题目晃得一看有点蒙人,其实就是从一个矩阵中定位所选目标的位置,再从另一个矩阵中选取对应位置的内容。

答:

function old_name = find_max_age(name,age)

[M I]=max(age)

old_name = name(I)

(3)Maximum value in a matrix

Find the maximum value in the given matrix.

For example, if

A = [1 2 3; 4 7 8; 0 9 1];

then the answer is 9.

明明很简单的一道题目,我一开始用y=max(x)死活过不去,用[y,I] = max(x)或y=x(I)也过不去,后来才发现max(x)是选取x矩阵中每行的最大值,全曲整个矩阵的最大值应该加(:)。

答:

y = max(x(:));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值