Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

MATLAB Help: Create a 1 by 15 row vector of random integers between 1 and 20, th

ID: 3731538 • Letter: M

Question

MATLAB Help:

Create a 1 by 15 row vector of random integers between 1 and 20, then create one random integer between 5 and 15. Sort your vector according to how far away each of its elements is from that scalar integer, in the descending order of the absolute distance. Hint: use the sort() function.

example run:

The original vector is [12 10 1 7 4 16 7 11 4 13 6 14 14 15 10]]

Sorted by the distance away from 5,

from far to near, the new vector is [16 15 14 13 12 11 10 10 1 7 7 4 4 6]

-----

Thank you for the help!

Explanation / Answer

The following code for the above problem can be either put in a separate matlab script file or can be run in command window line by line. Choose as per your convenience.

------------------------------------code to solve above problem is given below------------------------------------

%code starts here

%create a random distance variable whose value is between 5 and 15

dist = randi(10,1)+5

%create a vector of random integers between 1 and 20 of size 15

vec = randi(20, 1, 15)

%create another vector that stores distances from the random value generated above

%and sort this vector according to magnitude

vec2 = sort(vec-dist,2,'descend','ComparisonMethod','abs');


%the final sorted vector will be obtained by adding the distance value to each element of the sorted array

res = vec2 + dist

%above line prints the final vector sorted according to the distance from the random number

%code ends here

----------------------------------------------------end of solution code---------------------------------------------

Add or remove the semicolons at the end of the statements as you like according to whether you want the results to be printed or not.

Notify me in the comments if there is any problem with the code.    : )