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

Implementing the diff function by using array subtraction and vector indexing. D

ID: 3833805 • Letter: I

Question

Implementing the diff function by using array subtraction and vector indexing. Do NOT use the in-built diff function here. The row vector X will be randomized (size and values) at each submission, and will be created by the auto grader. Do not modify the given vector X. Recall that diff (X) is [X(2)-X(1) x(3)-x(2) ... x(n)-X(n - 1)], where n = length(X). Try help diff, look at the first few lines of documentation. Create a variable named vec_prev to store the 1st to the second to last elements of X. Create a variable named vec_next to store the 2nd to last elements of X. Create a variable named result to store the resultant vector equivalent to that returned by diff(X).

Explanation / Answer

function result=NewDiff(X);
%%NewDiff takes a row vector X and implements the
%%Diff function without using the built in function.
vec_prev=X(:,1:length(X)-1);%store 1st to second last element
vec_next=X(:,2:length(X));%store 2nd to last element
result=vec_next-vec_prev;%vector equivalent to diff(X)