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

User-defined functions can be called (and they generally behave) the same way as

ID: 1720852 • Letter: U

Question

User-defined functions can be called (and they generally behave) the same way as MATLAB's built-in functions. except that you must write them. To create a new m-file that contains a function, go to the "Editor" tab, click on the "New" drop-down menu, and click "Function". An untitled m-file will then be displayed in the Editor window that contains a template for a user-defined function, which, of course, you may edit to create your own function. The first line of this m-file is called the function declaration. It tells MATLAB that this m-file contains a function, not a script. For this problem you will write a MATLAB function (not a script) that calculates the difference between any two points (x_1, y_1) and (x_2, y_2) on a Cartesian coordinate plane. The distance between the points is given by the following equation: d = [(x_1 - x_2)^2 + (y_1 - y_2)^2]^1/2 To clarify, you are expected to write a MATLAB function that accepts a single input argument (a vector containing the coordinates of the two points) and returns (in a single output argument) the distance between the two inputted points. This is how you must declare your function: function distance = two_point_distance (points) As mentioned above, this is called a function declaration. It is what the first line of your function m-file should look like. For this problem, the function must be named two_point_distance and the input argument points must be a vector that contains all four coordinates (two for each point) in the order [x_1 y_1 x_2 y_2]. Also, the name of the function's m-file must be the same name as the function: two_point_distance.m. So, for example, if you wanted to calculate the distance between the points (-3, 2) and (2, -10), you could call your function using the following command: >> dist = two_point_distance ([-3 2 2 -10]) Of course, after the command is executed, the result of the function call is assigned to dist.

Explanation / Answer

function distance = two_point_distance(points)
    distance = sqrt((points(1)-points(3))^2+(points(2)-points(4))^2);
end

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote