Trying to fix output from matlab code for derivative

3 views (last 30 days)
I want to generalize my code "derivative" to make sure it works for all general functions. Then I want my df function to display the derivative while being surrounded by however many NaN in the array needed.
function df = firstDerCentered(f,h)
% Compute the 5 point centered finite difference vector df.
% Make sure the first and last two values of df are NaN.
h = 0.1;
H = h * 12; % 12h denominator
x = 0:h:0.7;
f = 1 + x + x.^4; % a vector of function values computed at uniformly spaced -values
A = f(1:end-4); % First Function of f (point 1)
B = f(2:end-3); % Second Function of f (point 2)
C = f(4:end-1) ; % Third Function of f (point 3)
D = f(5:end) ; % Fourth Function of f (point 4)
derivative=(f(1:end-4)-8*f(2:end-3)+8*f(4:end-1)-f(5:end))/(12*h);
%diff = (A-8*B+8*C-D)/(H); % Equation to Recieve Point 5 for ans
df = [NaN NaN derivative NaN NaN];
df = nan(size(f)); % fix function for output to be [1 63]/ what function matrix needed
end

Answers (1)

Walter Roberson
Walter Roberson on 25 Nov 2022
remove
df = [NaN NaN derivative NaN NaN];
but leave the assignment of nan to df
Now
offset = floor((numel(f) - numel(derivative)) / 2)
df(offset+1:offset+numel(derivative)) = derivative;
  7 Comments
Walter Roberson
Walter Roberson on 28 Nov 2022
My Answer has exact code for that. You keep the assignment of nan to df and then the code centers the derivative vector within df, without assuming that there will be exactly two nan before and after.
If you can assume exactly two then
df(3:end-2)=derivative
Torsten
Torsten on 28 Nov 2022
Edited: Torsten on 28 Nov 2022
The difference formula for the first derivative at x_i uses x_(i-1),x_(i-2), x_(i+1) and x_(i+2) in its computation. Thus at the two boundaries of the interval, there will always be two points where the derivatives cannot be computed using the formula from above. The author of the code used two NaN values at both sides to make the lengths of input and output arrays the same.
This is simply achieved by the two lines
function df = firstDerCentered(f,h)
derivative=(f(1:end-4)-8*f(2:end-3)+8*f(4:end-1)-f(5:end))/(12*h);
df = [NaN NaN derivative NaN NaN];
end
I don't know what you mean by
I was hoping to use the line df = nan(size(f));
Of course you could preallocate df, but it's not necessary.

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!