MATLAB: How to use fprintf function

floating pointfprintfscientific notation

I have to print the values of f(x) = sin(x^3) at the points x = 5.201, −8323.6, 0.0003 in floating point (f format) with 8 digits after the decimal and in scientific notation (e format) with 10 digits after the decimal.
Any help at all would be appreciated. I have no clue how to do this.

Best Answer

The fprintf function optionally requires a ‘fileID’ variable as its first argument, with 1 indicating ‘stdout’, that being the Command Window. Otherwise it will be to the file you want to write to. (I used it in the first fprintf call but not in the second.)
To print the values of ‘x’ and f(x), this works:
x = [5.201, -8323.6, 0.0003];
f = @(x) sin(x.^3);
fprintf(1, 'f(%f) = %.8f\n', [x; f(x)])
fprintf('f(%f) = %.10e\n', [x; f(x)])
f(5.201000) = 0.63076123
f(-8323.600000) = -0.52794696
f(0.000300) = 0.00000000
f(5.201000) = 6.3076122538e-01
f(-8323.600000) = -5.2794696417e-01
f(0.000300) = 2.7000000000e-11
The (\n) is a newline character.
Related Question