How to label Matlab output and graphs
Contents
How to display and label numerical output
You can print out numerical values as follows:
- omit the semicolon to print the name of the variable and its value
- use the disp command to print values of variables (also for arrays and strings)
- The format command changes the way how these two methods display numbers: format short (default) displays vectors and arrays using a 'scaled fixed point' format which is often not useful. format short g displays each entry with 5 significant digits. format long g displays each entry with 15 significant digits.
- use the fprintf command to print out text together with numerical values. Use %g as placeholder for numerical values (displays 5 significant digits). Use %.15g to display 15 significant digits.
format % use default format (same as 'format short') r = 3; area_circle = pi*r^2 fprintf('radius = %g, area of circle = %g\n',r,area_circle) % 5 significant digits fprintf('radius = %g, area of circle = %.15g\n',r,area_circle) % 15 significant digits disp(' ') x = (-20:5:20)'; % column vector with -20,-15,...,20 % default 'scaled fixed point format', not very useful disp('Values of exp(x) (using default format):') disp([x,exp(x)]) format short g % show 5 significant digits for each entry disp('Values of exp(x) (using format short g):') disp([x,exp(x)]) format long g % show 15 significant digits for each entry disp('Values of exp(x) (using format long g):') disp([x,exp(x)])
area_circle = 28.2743 radius = 3, area of circle = 28.2743 radius = 3, area of circle = 28.2743338823081 Values of exp(x) (using default format): 1.0e+08 * -0.0000 0.0000 -0.0000 0.0000 -0.0000 0.0000 -0.0000 0.0000 0 0.0000 0.0000 0.0000 0.0000 0.0002 0.0000 0.0327 0.0000 4.8517 Values of exp(x) (using format short g): -20 2.0612e-09 -15 3.059e-07 -10 4.54e-05 -5 0.0067379 0 1 5 148.41 10 22026 15 3.269e+06 20 4.8517e+08 Values of exp(x) (using format long g): -20 2.06115362243856e-09 -15 3.05902320501826e-07 -10 4.53999297624848e-05 -5 0.00673794699908547 0 1 5 148.413159102577 10 22026.4657948067 15 3269017.37247211 20 485165195.40979
How to label graphs
Use the title, xlabel, ylabel, legend commands:
x=0:.1:10; y1=sin(x); y2=cos(x); plot(x,y1,'-',x,y2,'--') title('Trigonometric functions') % title on top of graph xlabel('x') % label x-axis ylabel('y') % label y-axis legend('sin(x)','cos(x)') % label each curve