Using table() to show output

68 Views Asked by At
clc
clearvars
close all

hVec = [2^(-1) 2^(-2) 2^(-4) 2^(-8) 2^(-16) 2^(-32) 2^(-64)];   %step size

x1Vec = [1]; %x value
y = @(x) exp(x);   %main function
dy = @(x) exp(x);  %first derivative
ddy = @(x) exp(x); %second derivative

for i = 1:1
    for j=1:7
          x1 = x1Vec(i);
          h = hVec(j);
          d1 = dy(x1);
          d2 = ddy(x1);
          
          %Forward Differencing
          f1 = (y(x1+h) - y(x1))/h;
          
          %Central Differencing
          c1 = (y(x1+h) - y(x1-h))/(2*h); 
          c2 = (y(x1+h)-2*y(x1)+y(x1-h))/(h.^2);
          
          % Relative Errors
          ForwardError1(i,j) = (f1 - dy(x1))/dy(x1); % Forward difference err for u'
        
          CentralError1(i,j) = (c1 - dy(x1))/dy(x1); % Central difference err (second order) for u'(1)
       
          CentralError2(i,j) = (c2 - ddy(x1))/ddy(x1); % Central difference err (second order) for u''(1)
          
      end
end

How do I use table() to have my output in the form of https://i.stack.imgur.com/lzahM.png ?

The error I kept getting was "A table variable must not be a function handle. Use a cell array to contain function handles. "

1

There are 1 best solutions below

0
On BEST ANSWER

Here is a way to create a table (without table() !) by writing the successive results into a text file.

Let us see it on a similar example:

fid = fopen('expp.txt','w');
for k=0:2
   e=exp(k/5);a=1+k/5+k^2/50+k^3/750;er=e-a;       
   fprintf(fid,'exp of %d/5 : %8.5f ; approx : %8.5f ; error : %8.5f\n',k,e,a,er) 
end
fclose(fid);
type expp.txt

Result :

exp of 0/5 :  1.00000 ; approx :  1.00000 ; error :  0.00000
exp of 1/5 :  1.22140 ; approx :  1.22133 ; error :  0.00007
exp of 2/5 :  1.49182 ; approx :  1.49067 ; error :  0.00116

The file is "invoked" three times : see prefix "f" in "fopen, fprintf (second f for "formatted") and fclose.

  • fopen establishes the correspondence between 2 namings for the file (say one internal and the other external) and opens this file in writing mode ('w').

  • fwrite does the big part of the job by writing the newly created formatted string into the file.

  • fclose places (in particular) an "end of file".

Remarks:

  • "type" is a display order for a text file.

  • Please note the 'linefeed' symbol \n at the end of the format string.