matlab cody学习笔记 day11

想到要开学,要离开家,哭了一晚上,我想我妈妈!

(1)Problem 30. Sort a list of complex numbers based on far they are from the origin.

Given a list of complex numbers z, return a list zSorted such that the numbers that are farthest from the origin (0+0i) appear first.

So if z is

z = [-4 6 3+4i 1+i 0]

then the output zSorted would be

zSorted = [6 3+4i -4 1+i 0]

这道题目我一开始想的是先将z求abs,这样可以得到每个数离原点的相对距离,之后对这些距离进行排序,得到按大小排列的序号值,之后将这些序号值带入到原数组,得到最终的结果。不仅过程复杂,还容易出错,其实可以直接用排大小的函数"sort",将数组从小到大排序,如果要从大到小排序,需要 sort(z, 'descend')。

答:

function zSorted = complexSort(z)

zSorted = sort(z, 'descend');

(2)Problem 247. Arrange Vector in descending order

If x=[0,3,4,2,1] then y=[4,3,2,1,0]

这道题目与上述相似,甚至更简单更好理解,同样用sort函数即可解决。

答:

function y = desSort(x)

y = sort(x, 'descend');

(3)Roll the Dice!

Description

Return two random integers between 1 and 6, inclusive, to simulate rolling 2 dice.

Example

[x1,x2] = rollDice();

x1 = 5;

x2 = 2;

一开始用的是rand函数,但是报错,后来发现用randi函数:

randi()函数生成均匀分布的伪随机整数,范围为imin--imax,如果没指定imin,则默认为1。

r = randi(imax,n):生成n*n的矩阵

r = randi(imax,m,n):生成m*n的矩阵

r = randi(imax,[m,n]):同上

r = randi(imax,m,n,p,...):生成m*n*p*...的矩阵

r = randi(imax,[m,n,p,...])同上

r = randi(imax):1*1的矩阵

r = randi(imax,size(A)):和size(A)同维的矩阵

r = randi([imin,imax],...)

答:

function [x1,x2] = rollDice()

x1 = randi(6,1);

x2 = randi(6,1);

猜你喜欢

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