matlab 代写 MATLAB Exercise Set 2

MATLAB Exercise Set 2 FEB22012(X)

September 13, 2018

Making the assignment

You should make this assignment individually. You are allowed and encouraged to discuss ideas necessary to solve the assignment with your peers, but you should write the code by yourself. We will employ fraud checking software specifically created for programming classes such as this.

In case we suspect fraud, we can invite you to explain your code. Due to university policy cases of (suspected) fraud must be reported to the exam committee. The exam committee will then decide on possible disciplinary actions.

The deadline for this assignment is Wednesday, 19th of September 2018, 22:00, CEST. Grade and Scores

The grade of your assignment will depend on two important criteria:
1. Correctness: does your code work according to the specification in the assignment? 2. Code Quality: is your code well written and understandable?

For this assignment you can earn 10 points in total and counts for 10% towards the final grade of the course. Specific parts of the assignment count as follows:

When we ask you to implement a function using a specific algorithm, you will get no points if you use a different algorithm. Your are also not allowed to use functions from MATLAB Toolboxes as these are not available in Autolab.

1

Part of Assignment

Points

Plotting
Growing a Maze
Selling Cheese
Optimal Buy and Sell Portfolio Picking Dollars

1 1 2 2 2

Code Quality

2

Total

10

Handing in your assignment

  • 􏰊  You need to hand in your assignments via Autolab. If you hand in an exercise more than 35 times, you wil l get a strike. After three strikes, you can only obtain 75% of the correctness score for subsequent exercises you hand in more than 35 times.
  • 􏰊  When Autolab tells you that your assignment is not working correctly, i.e. you get less than 100 points, you will get 0 points for that assignment towards your grade. Your code should produce the correct answer in all situations, not just in some.
  • 􏰊  The scores generated by Autolab only give an indication of your possible grade. Final grades will only be given after your code has been checked manually.
  • 􏰊  Deliberate attempts to trick Autolab into accepting answers that are clearly not a solution to the assignments will be considered fraud.

    Code Quality

    Part of your grade will also depend on the quality of your code.

    • 􏰊  Your code should be well structured with sensible methods and parameters.
    • 􏰊  Give clear, understandable names to methods and variables. Something like cost should be preferred to c.
    • 􏰊  Use consistent layout, formatting and indent style for your code.
    • 􏰊  Write comments where appropriate. In MATLAB, functions should be documented. Directly after the function signature you should write the name of the function in upper case, with a short description of the function. The second line of the comment should contain the function signature. Please look at the lecture slides for an example.
    • 􏰊  Try to keep code as clean and elegant as possible.
    • 􏰊  Avoid magic numbers, define constants.

      For an in-depth style guide on writing clean MATLAB code, Mathworks provides a document with many tips and suggestion you can adopt at this page: https://nl.mathworks.com/matlabcentral/ fileexchange/46056-matlab-style-guidelines-2-0. Note that you need a Mathworks account and login to obtain this document.

      General Remarks

  • 􏰊  For many operations, such as summing up the elements in a matrix or vector, you can either write a loop or use a standard function in MATLAB that does it for you. Clever use of such functions can save writing a lot of code.
  • 􏰊  The last two exercises this week are quite challenging. Please be aware that these are also the final exercises of the MATLAB module of the course and resemble some of the data processing problems you may run into when you need to program for a thesis project.
  • 􏰊  The Windows version of Octave can be very slow and unresponsive the first time you call a plotting function. If you wait some time (up to a minute), the plot will become visible and subsequent plotting calls will hapenn very fast.

    2

Plotting MATLAB Exercise Set 2 September 13, 2018 Plotting

In this exercise you will practice plotting in MATLAB. The goal is to create a function which generates several plots depending on the value of the input variable flag. The function should have the following signature:

In this function, the flag variable can be an integer from 1 to 7. For each number, a different plot has to be created with the plot command. Unless otherwise specified, no additional styling of the plot should be done. Note that the plot can be marked as incorrect by Autolab if the plot style differs from the expected plot style. The expected plots for each value of flag are:

  1. A plot of the function f(x) = x2 − 3x + 8, with x ∈ [−5, 5]. Use 11 evenly spaced points on the interval for x.
    Hint: You may want to use the linspace function. See help linspace for help.
  2. A plot of the polar function r = sin(θ) + sin3(5θ/2) for θ ∈ [0, 4π] in 500 evenly spaced points. First compute the r for each θ, and then convert the pairs of polar coordinates (r,θ) to regular coordinates (x,y) using the equations x = rcos(θ) and y = rsin(θ). Note: your plot should have rectangular axes, which means that specialized functions for polar plots can not be used for this question.
  3. A plot of the function B(t) = 103 · 1.05t with t ∈ [0, 10], using 31 evenly spaced points for t. Label the horizontal axis time (days), the vertical axis bacteria, and give the plot the title Bacteria growth over time.
  4. A plot of the functions f(x) = x2 + 1, g(x) = sin(4x) + 1 and h(x) = −exp(−x2/3) on the 284

    interval x ∈ [−5, 5], using 101 points for x. Make sure that the vertical axis is restricted to the interval [−1,1] and the horizontal axis to [−5,5]. Style the lines as follows: f(x) is a red solid line, g(x) is a green dashed line, and h(x) is a black dash-dotted line. Hint: Note that ‘.−’ and ‘−.’ are different line styles in MATLAB.

  5. A three dimensional surface plot of the function f(x,y)= 4×2 −x2y2 −1,

    (x2 +y2 +1)2
    with x, y ∈ [−10, 10]. Use 101 evenly spaced points for both x and y.

  6. A histogram of all the primes below 106, using 100 equally sized bins. Hint: you are allowed to use the primes function.
  7. For a constant r and a starting point y1 = 1, we can iterate the function yt = r · yt−1 · 2

    (1 − yt−1) to compute y2, y3, y4, and so on. This function is called the logistic map, and

    it shows very different behavior for different values of r. For example, the next two values

    for r = 1.5 and y1 = 1, we get y2 = 0.375 and y3 = 0.3515625, and for r = 1 the next 2

    two values are y2 = 0.25 and y3 = 0.1875. Create four subplots of the first 15 steps of this process where the x-axis contains the steps 1 to 15 and the y-axis contains the y corresponding to that step. In the top-left subplot use r = 0.7, in the top-right subplot use r = 2.3, in the bottom left subplot use r = 3.4 and in the bottom right subplot use r = 3.7. If you want to learn more about the logistic map, you can watch the following Numberphile video:

    https://www.youtube.com/watch?v=ETrYE4MdoLQ.

function plotting(flag)

Grow Maze MATLAB Exercise Set 2 September 13, 2018 Growing a Maze

A cellular automaton consists of a grid of cells where each cell is either on or off. In a single time step a new generation is computed based on the previous generation and a fixed rule. The most famous example of a cellular automaton is Conway’s Game of Life. In this exercise we will implement a variation which results in maze-like structures.

Create a function with the following signature

The input A is a matrix with the initial state of each cell, where a value of 0 indicates a cell is off and a 1 indicates a cell is on. The input steps indicates how many new generations need to be computed.

A new generation can be computed with the following rules:

Survival If a cell is on and it has at least one and at most four neighbors which are on, it will be on in the new generation.

Birth If a cell is off and it has precisely three neighbors which are on, it will be on in the new generation.

Death All other cells will be off in the new generation.

The neighbors of a cell are all cells which are directly adjacent to it, including the diagonal cells. Most cells have eight neighbors, while those at the sides of the grid have five neighbors and the cells in the corners only three neighbors.

Hint: If you need far more than 30 lines of code for this problem, you may need to reconsider your approach. Also, make sure to take special care at the boundaries of the matrix. One way to deal with this is to make use of the min and max functions in MATLAB.

For testing purposes, you can create a random 0-1 matrix using the following code:

When you’ve finished writing your program, you can animate the process in MATLAB with the following code (note that animation works slightly different in Octave):

function [B] = grow maze(A, steps)

A = randi([0, 1], 10, 10)

B = [];
iter = 0;
while ̃isequal(A,B) && iter < 50

B = A;
A = grow maze(A,1); imshow(A,’InitialMagnification’,’fit’); drawnow;
pause(0.25);
iter = iter + 1;

end

This exercise must be handed in through Autolab. More information about handing in your exercise through Autolab can be found on Blackboard.

Selling Cheese MATLAB Exercise Set 2 September 9, 2018 Selling Cheese

The cheeses of Trendy Cheese Inc. are extremely popular at the moment. Every Saturday of the week, they can sell their cheeses at a local market. Unfortunately the van they use to transport the cheeses to the market cannot take the full stock: the weight of all cheeses would overload the van. So every week they need to make a selection. Since they can safely assume that their cheeses will sell out, they want to select the cheeses which will maximize profit. If a cheese would not fit fully into the van, it can be cut to an arbitrary weight.

You need to implement a function with the following signature:

Here the input weights is a vector of length n that contains for every cheese the amount of weight currently in stock. The input profit is a vector of length n containing for every cheese the profit that the company will receive when the full stock of that cheese is sold. The input capacity is the capacity of the van in units of weight. The output profit should contain the maximized profit the company can make with the cheeses transported by the van. The output cheeses should contain a vector of length n which contains for every cheese the amount of weight that should be put in the van.

Example: The call select cheese([4 3 3 2], [6 4 7 1], 6) should yield a profit of 11.5 and a selection of cheese equal to [3 0 3 0]. This implies that the van will carry 3 weight units of cheese type 1 and 3 weight units of cheese type 3.

Hint: to find the correct answer, you need to fill up the capacity of the van in descending order of profit per unit of weight. The function sortrows can be very useful to do this.

Hint: After sorting the matrix it can be difficult to know which ratio belonged to which cheese. It can be useful to include indices of the cheeses in the matrix before sorting. Approaches that try to look up the original cheeses based on just their weight, profit or ratio will be extremely difficult to implement correctly and are thus discouraged.

Remark: You need to implement the greedy algorithm for this assignment. It is not allowed to use a Linear Programming based approach. The Optimization Toolbox is not available within Autolab.

This exercise must be handed in through Autolab. More information about handing in your exercise through Autolab can be found on Blackboard.

function [profit, cheeses] = select cheese(weights, profits, capacity)

Buy & Sell Portfolio MATLAB Exercise Set 2 September 9, 2018 Buy & Sell Portfolio

Last week your Wall Street boss asked you to figure out the optimal buy and sell times on historic stock price data, and the maximum profit that could have been obtained. This week, he’s back with another problem: find out the optimal buy and sell times and the maximum profit on a whole portfolio of stock prices! There’s just one problem though, the data he has prepared for you will need some formatting because not all stock prices start and end at the same date.

You are given three filenames which correspond to existing CSV files. Each of these CSV files contains data in the following format:

16679,602.36
16678,627.54
16675,632.82
16674,639.4
16673,610.35
16672,614.91
16671,573.0
16668,639.78
16667,655.46

In this data the first column is a day ID and the second column is the price of the stock on that day. Note that in this data the day column is a translation of an actual date to a day ID1. On some days (such as weekends and special days) the market is closed, and there can be missing lines in the data.

Your job is to write a function which does the following:

  • 􏰊  Reads the data from each CSV file into a 2-column matrix
  • 􏰊  Finds the largest common sequence of days among all files (i.e. the range of days for which there are stock prices in all files)
  • 􏰊  Calculates the maximum profit that could be obtained from buying all three stocks si- multaneously at one point in time, and selling all three stocks simultaneously at another point in time. Just like last week, you must buy and sell once.

    Your MATLAB function must have the following signature:

    Here, the buyday and sellday variables must correspond to the ID of the day on which the stocks must be bought or sold to obtain the maximum profit. For this exercise you can use the function optimal buysell which you created last week. Make sure to include an optimal buysell function in your buysell portfolio program.

    Hint: Make sure you download the handout available on Autolab (on the left, under Options), and save the three .csv files in your working directory, so you can test your function locally. You should then be able to test your program with:

    1For instance, 16679 corresponds to Sep. 1, 2015. If you’re curious, you can convert dates using this website.

function [buyday, sellday, profit] = buysell portfolio(file1, file2, file3)

buysell portfolio(‘AAPL.csv’, ‘FB.csv’, ‘GOOG.csv’)

Buy & Sell Portfolio MATLAB Exercise Set 2 September 9, 2018

Hint: To compute the common range for the series you can assume that the same weekend days are left out in all files. Therefore, you only need to find a common start time and end time to define a range.

Remark: We recommend to plot the data in the CSV files to get a feeling of what it looks like.

This exercise must be handed in through Autolab. More information about handing in your exercise through Autolab can be found on Blackboard.

Picking Dollars MATLAB Exercise Set 2 September 13, 2018

Note: as this is your final MATLAB assignment, you have more freedom compared to the previous exercises. For this exercise, you are encouraged to think yourself what kind of program to write, and to discuss possible strategies to win this game with your fellow students. It can be very useful to work out some ideas on paper and maybe try to play the game with a fellow student, before you sit down and program your solution.

Picking Dollars

Consider a simple two player game, where one or more piles of dollars lie on the table. In every turn, one of the two players has to select a single pile and takes 1 or more dollars out of that pile, possibly taking the entire pile of dollars. Then the other players gets the turn. The player that takes the last dollars from the table wins, and gets to keep all dollars.

In this exercise, you will create a function that acts as a player of this simple game. The expected signature of the function is as follows:

In this function, the piles of dollars that are currently lying on the table are provided as a row vector game state, where each element of the vector represents one of the piles on the table. Thus all numbers in this vector are non-negative, but possibly zero as some player may have already removed all dollars from a pile during the game.

Your function should make a move and return the new state vector of the piles on the table as output response. This means you have to decrease precisely one element of the input vector, while making sure that all elements in the vector remain non-negative. If your function returns any other vector, your move is considered invalid and you will be disqualified. Also, the vector you return should have exactly the same number of elements as the vector that was given to your function. If you want to take all dollars from a single pile, you change that element to zero.

As an example, the game state where there is one pile with 5 dollars and another pile with 1 dollar is expressed as [5 1]. In this case, it would make sense to take 4 dollar from the first pile, and thus pick dollars([5 1]) should return [1 1].

Furthermore, you should try to win the game. If you return a zero-vector as a valid move, you win the game. To pass this exercise, you function should win in all game states with one or two piles on the table (assuming that it is possible to win). You should also be able to win at least 25% of winnable games where there are three piles on the table.

Hint: determine a good strategy for the case where two piles have the same amount of dollars.

Just for fun, Autolab will also run a competition to compare your strategy with that of your fellow students. To do this, Autolab will let your function play against a relentless computer opponent which will make sure it wins if it is able to do so. However, all games presented to your function are winnable. Try to come up with a strategy that can win as many games as possible.

Note: To stimulate competition, the limit on the number of times that you can hand in your program in Autolab does not apply for this exercise.

This exercise must be handed in through Autolab. More information about handing in your exercise through Autolab can be found on Blackboard.

function [response] = pick dollars(game state)