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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值