26

Say I had a variable called "x" and x=5.

I would like to do:

disp('x is equal to ' + x +'.');

and have that code print:

x is equal to 5.

This is how I am used to doing things in Java, so their must be a similar way to do this in MATLAB.

Thanks

zellus
  • 9,617
  • 5
  • 39
  • 56
JJJ
  • 597
  • 2
  • 7
  • 14

3 Answers3

69

If you want to use disp, you can construct the string to display like so:

disp(['x is equal to ',num2str(x),'.'])

I personally prefer to use fprintf, which would use the following syntax (and gives me some control over formatting of the value of x)

fprintf('x is equal to %6.2f.\n',x);

You can, of course, also supply x as string, and get the same output as disp (give or take a few line breaks).

fprintf('x is equal to %s\n',num2str(x))
Jonas
  • 74,690
  • 10
  • 137
  • 177
1

printing out a few scalar variables in matlab is a mess (see answer above). having a function like this in your search path helps:

function echo(varargin)
str = '';
for k=1:length(varargin)
    str = [str ' ' num2str(varargin{k})];
end 
disp(str)
johannes_lalala
  • 561
  • 4
  • 12
0

just nest a sprintf() inside the disp().

    disp(sprintf("X is equal to %d.",x));
Sir_Zorg
  • 331
  • 1
  • 2
  • 5