matlab cody学习笔记 day9

(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(:));

猜你喜欢

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