MATLAB Efficient Output Organization for MATLAB Three-Point Derivative Approximation

  • Thread starter Thread starter Providence88
  • Start date Start date
  • Tags Tags
    Matlab Output
AI Thread Summary
The discussion revolves around a code snippet for approximating the derivative of the sine function using a three-point formula. The original code outputs individual matrices for each iteration, which is cumbersome. The user seeks a solution to consolidate the results into a single matrix with 30 rows and 4 columns, containing iteration number, step size, approximation of the derivative, and error. A revised function is provided that initializes a zero matrix and populates it in a loop, successfully achieving the desired output format. The user confirms that the solution works effectively.
Providence88
Messages
7
Reaction score
0
So I have this code:

Code:
function ApproxSinDeriv(x,n)
h=.5;
for i = 0:n
    h;
    approx = (1/(2*h))*(sin(x+h)-sin(x-h));
    error = abs(approx-cos(x));
    h = h/2;
    A=[i,h,approx,error]
end

Basically, it's a three-point formula for approximating a derivative, where the variables n = the number of iterations, x = the input value for the sin function, i = iteration number, approx=the approximation of the derivative, and error = the difference between the actual derivative and the approximation.

I put A equal to a matrix of these values, but the output comes out in 30 clunky, individual, one-row matrices.

How would I go about putting this data in an array? That is, one nice clean matrix with 30 rows and 4 columns [i,h,approx,error]?

Thanks!

-Eric.
 
Last edited:
Physics news on Phys.org
Code:
function [A] = ApproxSinDeriv(x,n)
A = zeros(n+1,4)
h=.5;
for i = 0:n
    approx = (1/(2*h))*(sin(x+h)-sin(x-h));
    error = abs(approx-cos(x));
    h = h/2;
    A(i+1,:)=[i,h,approx,error];
end
 
Thank you! That worked great!
 
Back
Top