Function Name: myDiff % Inputs (1): - (double) A 1xN vector of numbers % Outputs
ID: 3527875 • Letter: F
Question
Function Name: myDiff % Inputs (1): - (double) A 1xN vector of numbers % Outputs (1): - (double) A 1xN-1 vector of the differences between vector % elements % % Function Description: % Write a function called "myDiff" that takes in a vector and returns a % vector of differences between each consecutive element in the vector, % starting with the last element. For example, say we have a % vector of numbers as follows: % % vec = [3 4 2 6 7] % % the difference between the 5th element and the 4th element is 1, the % difference between the 4th element and the 3rd element is 4, and % so on until we reach the last element. The final result would be: % % differences = [1 -2 4 1] % % Notes: % - The length of the resultant vector will always be one less than the % original vector. % - The differences are always calculated from right to left. % - You may *not* use the diff() function for this problem. % % Test Cases: % diff1 = myDiff([5 6 7 8 9]); % diff1 => [1 1 1 1] % % diff2 = myDiff([4 2 0 -2 -4]); % diff2 => [-2 -2 -2 -2] % % diff3 = myDiff([2 7 3 1 4 8 0]); % diff33 => [5 -4 -2 3 4 -8] %Explanation / Answer
function diff=myDiff(Arr) n=length(Arr); diff(n-1)=0; for i=1:n-1 diff(i)=Arr(i+1)-Arr(i); end
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.