matlab cody study notes day11

Thinking of starting school, leaving home, crying all night, I miss my mother!

(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]

What I thought about this question at first was to find z abs first, so that we can get the relative distance of each number from the origin, and then sort these distances to get the serial number values ​​arranged by size, and then bring these serial number values ​​into Original array, get the final result. Not only is the process complicated, but it is also error-prone. In fact, you can directly use the row size function "sort" to sort the array from small to large. If you want to sort from large to small, you need sort(z,'descend').

answer:

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]

This problem is similar to the above, even simpler and better to understand, and can also be solved with the sort function.

answer:

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;

The rand function was used at the beginning, but an error was reported, and then I found that the randi function was used:

The randi() function generates uniformly distributed pseudo-random integers in the range of imin--imax. If imin is not specified, the default is 1.

r = randi(imax,n): generate n*n matrix

r = randi(imax,m,n): generate m*n matrix

r = randi(imax,[m,n]): Same as above

r = randi(imax,m,n,p,...): Generate a matrix of m*n*p*...

r = randi(imax,[m,n,p,...]) Same as above

r = randi(imax): 1*1 matrix

r = randi(imax,size(A)): a matrix with the same dimension as size(A)

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

answer:

function [x1,x2] = rollDice()

x1 = rand (6.1);

x2 = randi (6,1);

Guess you like

Origin blog.csdn.net/yxnooo1/article/details/113995703