Search code examples
matlabtextboxscientific-notation

Matlab: apply scientific notation in textbox


I want to add a textbox to a plot in which a number is displayed in scientific notation. Here my code:

fano = 74585849.3443; figure; plot(x,y) annotation('String',['fano =',num2str(fano)],'FitBoxToText','on'); Here fano is displayed as decimal number. How can I change the format to scientific notation?


Solution

  • You can just create the desired string with the function sprintf. Here are three examples with a different number of decimal places printed. When formatting the text with %M.Nd, M specifies the field width, N the precision (number of decimal places) and d means decimal (signed). Below are three different examples with 2, 5 and 8 decimal places. dim is an array with the location and size of the textbox in normalized units with respect to the figure size, formatted as [x_location y_location width height]. In your case width and height don't matter, since you are using the 'FitBoxToText' property.

    fano = 74585849.3443;
    figure;
    x = 0:0.01:10;
    y = sin(2*pi*1*x);
    plot(x,y);
    dim = [.5 .85 .0 .0];
    str = sprintf('fano = %0.2d',fano);
    annotation('textbox',dim,...
        'String',str,...
        'FitBoxToText','on',...
        'BackgroundColor','white');
    dim = [.5 .65 .0 .0];
    str = sprintf('fano = %0.5d',fano);
    annotation('textbox',dim,...
        'String',str,...
        'FitBoxToText','on',...
        'BackgroundColor','white');
    dim = [.5 .45 .0 .0];
    str = sprintf('fano = %0.8d',fano);
    annotation('textbox',dim,...
        'String',str,...
        'FitBoxToText','on',...
        'BackgroundColor','white');
    

    Here is the output:

    enter image description here