Efficient Output Organization for MATLAB Three-Point Derivative Approximation

  • Context: MATLAB 
  • Thread starter Thread starter Providence88
  • Start date Start date
  • Tags Tags
    Matlab Output
Click For Summary
SUMMARY

The discussion centers on optimizing MATLAB code for a three-point derivative approximation of the sine function. Eric initially faced issues with outputting results as individual one-row matrices. The solution provided involves modifying the function to store results in a single matrix, A, initialized with zeros and updated within the loop. This approach effectively organizes the output into a clean matrix format with 30 rows and 4 columns, representing iteration number, step size, approximation, and error.

PREREQUISITES
  • Understanding of MATLAB programming and syntax
  • Familiarity with numerical methods for derivative approximation
  • Knowledge of matrix operations in MATLAB
  • Basic concepts of error analysis in numerical computations
NEXT STEPS
  • Explore MATLAB matrix manipulation techniques
  • Learn about numerical differentiation methods in MATLAB
  • Investigate error analysis for numerical approximations
  • Study optimization techniques for MATLAB code performance
USEFUL FOR

MATLAB programmers, numerical analysts, and anyone interested in improving the efficiency of numerical methods and output organization in MATLAB.

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!
 

Similar threads

  • · Replies 9 ·
Replies
9
Views
5K
  • · Replies 4 ·
Replies
4
Views
8K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
4K
Replies
1
Views
2K