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

Up to this point, we have been writing MATLAB programs in the form of scripts, w

ID: 3671697 • Letter: U

Question

Up to this point, we have been writing MATLAB programs in the form of scripts, which we save to an m-file. However, an m-file can also contain another kind of MATLAB code called a "user-defined function". Here is a link to information about the differences between scripts and functions in MATLAB: http://www.mathworks.com/help/matlab/matlab_prog/scripts-and-functions.html 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 [xl yl x2 y2]. 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

program:

function distance=two_point_distance(points)
if ~isvector(points)
error('Input must be a vector')
end
distance=sqrt(((points(1)-points(2))^2)+((points(3)-points(4))^2));
end

output:

>> dist=two_point_distance([-3 2 2 -10])

dist =

13

>>

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