CODY Contest 2020 MATLAB Onramp Practice 全15题

第一题 Problem 1. Times 2 - START HERE

Try out this test problem first.

Given the variable x as your input, multiply it by two and put the result in y.

Examples:

Input x = 2

Output y is 4

 

Input x = 17

Output y is 34

返回输入值的二倍

function y = times2(x) % Do not edit this line.

  % Modify the line below so that the output y is twice the incoming value x

  y = 2*x;

  % After you modify the code, press the "Submit" button, and you're on your way.

end % Do not edit this line.

 第二题 Problem 44943. Calculate Amount of Cake Frosting

Given two input variables r and h, which stand for the radius and height of a cake, calculate the surface area of the cake you need to put frosting on (all around the sides and the top).

Return the result in output variable SA.

给定蛋糕的半径r和高度h,求需要进行糖霜处理的表面积。只包括顶部的底面积和周围的侧面积。底面积等于pi*r^2,侧面积等于2*pi*r*h。

function SA = func_frosting(r,h)
  SA = 2*pi*r*h+pi*r*r;
end

第三题 Problem 44944. Convert from Fahrenheit to Celsius

Given an input vector F containing temperature values in Fahrenheit, return an output vector C that contains the values in Celsius using the formula:

将华氏度转化为摄氏度,并且公式已经给出:

C = (F–32) * 5/9

直接把公式复制进去就行。

function C = temp_convert(F)
  C=(F-32) * 5/9;
end

第四题 Problem 44947. 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.

给定姓名数组和对应的年龄数组,返回年龄最大人的姓名。使用find函数和max函数对age进行操作然后索引name数组即可。

function old_name = find_max_age(name,age)
    old_name=name(find(age==max(age)));
end

第五题 Problem 44951. Verify Law of Large Numbers

If a large number of fair N-sided dice are rolled, the average of the simulated rolls is likely to be close to the mean of 1,2,...N i.e. the expected value of one die. For example, the expected value of a 6-sided die is 3.5.

Given N, simulate 1e8 N-sided dice rolls by creating a vector of 1e8 uniformly distributed random integers. Return the difference between the mean of this vector and the mean of integers from 1 to N.

验证大数定律。给定N,返回1到N的均值(也就是N+1除以2)和1-N的随机数重复出现1e8次的均值的差值。

function dice_diff = loln(N)
    dice_diff = mean(randi(N, 1e8,1)) - (N+1)/2;
end

第六题 Problem 44946. Solve a System of Linear Equations

If a system of linear equations in x1 and x2 is:

2 x₁ +  x₂ = 2

x₁ - 4 x₂ = 3

Then the coefficient matrix (A) is:

2 1

1 -4

And the constant vector (b) is:

2

3

To solve this system, use mldivide ( \ ):

x = A\b

Problem:

Given a constant input angle θ (theta) in radians, create the coefficient matrix (A) and constant vector (b) to solve the given system of linear equations in x&#8321 and x&#8322.

cos(θ) x₁ + sin(θ) x₂ = 1

-sin(θ) x₁ + cos(θ) x₂ = 1

这道理意思大概为对于线性方程组,先找到其系数矩阵A和结果矩阵y,然后通过A\b返回方程组的解,然后对于上式,给定theta,返回解。

function x = solve_lin(theta)
    A=[cos(theta),sin(theta);-sin(theta),cos(theta)];
    b=[1;1];
    
    x = A\b; 
end

 第七题 Problem 44948. Calculate a Damped Sinusoid

The equation of a damped sinusoid can be written as

y = A.e^(-λt)*cos(2πft)

where A, λ, and f are scalars and t is a vector.

Calculate the output sinusoid y given the inputs below:

  • lambda - λ
  • T - maximum value of t
  • N - number of elements in t

Assume A = 1 and f = 1 . The vector t should be linearly spaced from 0 to T, with N elements.

题目给定了某函数y等于y = A.e^(-λt)*cos(2πft),输入T代表t的最大值,N代表t的元素数量,和函数的其他参数,要求返回y的向量值。先列出最大为T的共N个元素的向量t,然后代入公式即可。

function y = damped_cos(lambda, T, N)
  t=0:T/(N-1):T;
  y = exp(-lambda*t).*cos(2*pi*t);
end

第八题 Problem 44934. Plot Damped Sinusoid

Given two vectors t and y, make a plot containing a blue ( b ) dashed ( -- ) line of y versus t.

Mark the minimum value m of the vector y by adding a point to the plot. This point should be a red asterisk marker, and it must be added after the blue line.

Return the minimum value of y as output m.

意思是根据y值,用plot绘制处y,用蓝色虚线表示,并且用红色星号标注出最低值的位置,并且要在蓝色虚线之后。

function m = plot_cos(y, t)
[m,pos] = min(y);
plot(t,y,'b--',t(pos),m,'r*');
end

第九题 Problem 44945. Calculate BMI

Given a matrix hw (height and weight) with two columns, calculate BMI using these formulas:

  • 1 kilogram = 2.2 pounds
  • 1 inch = 2.54 centimeters
  • BMI = weight(kg) / [height(m)]^2

The first column is the height in inches. The second column is the weight in pounds.

上式给出了镑和千克的转化公式、英尺和厘米的转化公式、以及bmi的计算公式。注意bmi计算公式种的高度的单位为米,并且输入的格式为英尺和镑。输入的为向量,分别对向量操作转化到千克和米后向量计算即可(用到点除和点平方)。

function bmi = bmi_calculator(hw)
    hw(:,1)=hw(:,1)*2.54/100;
    hw(:,2)=hw(:,2)/2.2;
    bmi=hw(:,2)./(hw(:,1).^2);
  % Convert the height values from inches to meters

  
  
  % Convert the weight values from lbs to kilograms

  
  
  % Calculate the bmi for height and weight combination and return the output variable 'bmi'
  
  
end

第十题 Problem 44958. Crop an Image

A grayscale image is represented as a matrix in MATLAB. Each matrix element represents a pixel in the image. An element value represents the intensity of the pixel at that location.

Create a cropped image matrix Icrop using inputs given in the following order:

  1. I - Grayscale input image
  2. Rmin - Lowest row number to retain
  3. Cmin - Lowest column number to retain
  4. Rpix - Number of pixels along rows to retain
  5. Cpix - Number of pixels along columns to retain

给定灰度图I,要求对图进行裁剪,裁剪图像的左上角坐标为Rmin Cmin,裁剪大小为Rpix*Cpix。因为测试样例不存在裁剪的图像右下角坐标超出图像范围的,所以不需要考虑的这么周到。

裁剪图像的坐标分别为Rmin到Rmin+Rpix-1、Cmin到Cmin到Cpix-1。

function Icrop = crop_image(I, Rmin, Cmin, Rpix, Cpix)
  Icrop = I(Rmin:Rmin+Rpix-1,Cmin:Cmin+Cpix-1);
end

第十一题 Problem 44949. Find the Best Hotels

Given three input variables:

  • hotels - a list of hotel names
  • ratings - their ratings in a city
  • cutoff - the rating at which you would like to cut off

return only the names of those hotels with a rating of cutoff value or above as a column vector of strings good.

输入为两个向量hotels和ratings和一个值cutoff,要求返回所有ratings评分大于给定值cutoff的酒店名(存放在hotels中)。通过查找ratings满足条件的索引然后作为hotels的索引即可。

function good = find_good_hotels(hotels,ratings,cutoff)
  good = hotels(find(ratings>=cutoff));
end

第十二题 Problem 44952. Find MPG of Lightest Cars

The file cars.mat contains a table named cars with variables Model, MPG, Horsepower, Weight, and Acceleration for several classic cars.

Load the MAT-file. Given an integer N, calculate the output variable mpg.

Output mpg should contain the MPG of the top N lightest cars (by Weight) in a column vector.

测试样例均值从matlab自带的mat里读取得到,分为 Model, MPG, Horsepower, Weight, and Acceleration四个变量,输入N,返回前N个最轻(从Weight判断)的mpg值。

function mpg = sort_cars(N)
    load cars.mat
    sorted = sortrows (cars,4);
    mpg = sorted(1:N,2);
    mpg=mpg{:,:};
end

先按照对cars的第四列(weight)值对cars的行进行排序,返回前N个的第二列(mpg)值,做最后一步操作的原因是此时的mpg仍然是一个N*1的table格式,做此操作后将mpg转为了列向量。

第十三题 Problem 44950. Calculate Inner Product

Given two input matrices, x and y, check if their inner dimensions match.

  • If they match, create an output variable z which contains the product of x and y
  • Otherwise, z should contain a custom string message

Example:

x = [1 2;3 4]

y = [5;6]

z = [17;39]

x = [1 2 3;4 5 6]

y = [2 5;3 6]

z = "Have you checked the inner dimensions?"

OR

z = "The inner dimensions are 3 and 2. Matrix multiplication is not possible"

-------------------------------------------------------------------------------------------------------------------------------------------------------------

NOTE - An example of combining numbers and strings together is shown below:

x = "The sum of " + 4 + " and " + 3 + " equals " + 7

 

x =

 

"The sum of 4 and 3 equals 7"

计算两个矩阵x和y的乘积z,如果不能乘(x的列数不等于y的行数),那么z为字符串,内容为提示不能乘积,但内容可以是任意的,所以z设为任意字符串即可。

function z = in_prod(x,y)
    [m,n]=size(x);
    [a,v]=size(y);
    if(n==a)
        z=x*y;
    else
        z="c";
    end
end

 第十四题 Problem 44960. Rescale Scores

Each column (except last) of matrix X contains students' scores in a course assignment or a test. The last column has a weighted combination of scores across all the assignments and tests.

Replace the elements in the last column of this matrix with a GPA calculated based on the following scale:

Score GPA

90 - 100 3 - 4

80 - 90 2 - 3

70 - 80 1 - 2

60 - 70 0 - 1

Below 60 0

Assume that no student in this class has scored below 60. Also note that the mapping in the range [60, 100] is linear.

See <https://www.mathworks.com/help/matlab/ref/rescale.html>

Example

Input:

100 90 95 95

70 50 60 60

80 70 90 80

Output:

100 90 95 3.5

70 50 60 0.0

80 70 90 2.0

题目把60-100分为了四个段,对应0-4分,比如60-70分对应的gpa为0-1,由于是线性的,所以可以很快的写出公式,得到分数和gpa的线性映射关系(题目假设所有人都大于60分):成绩为x,那么gpa-(x-60)/10。

题目要求是对输入的矩阵的最后一列映射到gpa,所以:

function X = rescale_scores(X)
    X(:,end)=(X(:,end)-60)/10;
end

第十五题 Problem 672. Longest run of consecutive numbers

Given a vector a, find the number(s) that is/are repeated consecutively most often. For example, if you have

a = [1 2 2 2 1 3 2 1 4 5 1]

The answer would be 2, because it shows up three consecutive times.

If your vector is a row vector, your output should be a row vector. If your input is a column vector, your output should be a column vector. You can assume there are no Inf or NaN in the input. Super (albeit non-scored) bonus points if you get a solution that works with these, though.

返回连续重复在向量出现所有数。如果输入是行向量,那么返回的也应该是行向量,如果是列向量那么也应该返回列向量。先不管是列还是行,设max_num为最大重复次数,val为返回的向量,j为下一个的val下标,item_num为当前数字的重复次数,last_item为上一个数字。

初始化后,遍历向量,如果当前值a(i)和上一个数字last_num相等,那么item_num更新+1,如果item_num值等于当前最大重复次数max_num,那么将a(i)加入val的尾部;如果大于最大重复次数,那么val清空,j变为1,val存入当前值a(i),j更新为2。如果当前值和上一个数字不等,last_item更新为当前值a(i),last_num也初始化为1。对于第一次a(1),虽然和last_num(初始化为nan)不等,但也应该将a(1)放入val中,并且更新max_num为1,所以在和上个数字不等时加入判断max_num是否小于等于1,如果小于1说明当前值是a(1);如果等于说明数组从头开始出现[1,2,3,4,5,6]这种情况,如果连续两个都不同,那么所有值都应该保存。

默认val为行向量,对输入的a进行判断是否为列向量(行数是否大于1)判断,如果为列则转置即可。

function val=longrun(a)
max_num=0;
val=[];
j=1;
last_item=nan;
item_num=0;
for i=1:length(a)
    if a(i)==last_item
        item_num=item_num+1;
        if item_num==max_num
            j=j+1;
            val(j)=a(i);
            
        elseif item_num>max_num
            max_num=item_num;
            j=1;
            val=[];
            val(j)=a(i);
        end
    
    else
        if max_num<=1
            max_num=1;
            val(j)=a(i); 
            j=j+1;
        end
        last_item=a(i);
        item_num=1;
    end
end
[m,n]=size(a);
if m>1
    val=val';
end
end

 

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值