I need help formatting a table with disp and fprintf for a few Taylor Series outputs
4 views (last 30 days)
Show older comments
syms x
f = 4*(-exp(-2*x)+exp(-x));
approx2 = taylortable(f,0,[0,0.5])
function approx2 = taylortable(f,x0,dom)
% set up the domain:
a = dom(1); b = dom(2);
if (x0 < a) || (x0 > b), x0 = a;
end
x = linspace(a,b,11)';
%
% convert f and its derivatives to functions, and calculate their values at
% x = x0
F = matlabFunction(f); Fx0 = F(x0);
FP = matlabFunction(diff(f)); FPx0 = FP(x0);
FPP = matlabFunction(diff(f,2)); FPPx0 = FPP(x0);
FPPP = matlabFunction(diff(f,3)); FPPPx0 = FPPP(x0);
%
approx2 = zeros(11,3);
% find the exact and approximate values of f
for n = 1:11,
approx2(n,1) = F(x(n));
approx2(n,2) = Fx0 + (x(n)-x0)*FPx0;
approx2(n,3) = approx2(n,2) + (((x(n)-x0)^2)/2)*FPPx0;
approx2(n,4) = approx2(n,3) + (((x(n)-x0)^3)/3)*FPPPx0;
end
disp(' x Exact Taylor-1 Taylor-2 Taylor-3')
fprintf('%5.3f, %5.3f, %5.3f, %5.3f, %5.3f\n', x, approx2(:,1), approx2(:,2), approx2(:,3), approx2(:,4))
end
The values for approx2 are not being taken by the disp or the fprintf commands
0 Comments
Answers (1)
Walter Roberson
on 7 Sep 2019
fprintf('%5.3f, %5.3f, %5.3f, %5.3f, %5.3f\n', [x(:), approx2].')
When you use fprintf(), it goes down columns in the input, using all of the first input (x) before it outputs any of the second variable, then goes down the columns of that, using all of that before outputing any of the next variable, and so on.
The trick I used here [x(:), approx2].' creates columns of data but then transposes them to become rows, so that the first entry in the temporary array is x(1), the second entry is approx2(1,1), the third is approx2(1,2) and so on.
0 Comments
See Also
Categories
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!