home

Scientific Computing (Psychology 9040a)

Fall, 2021


Getting user input and printing output

In MATLAB you can ask the user to enter information using the input() function:

>> v = input('enter a value: ');
enter a value: 123.456
>> v

v =

  123.4560

You can print the value of a variable to the screen using the disp() function:

>> disp(v)

which outputs:

  123.4560

You can display formatted output using the fprintf() function:

>> fprintf('the value of v is %.4f and the value of pi is %.8f\n', v, pi)

which outputs:

the value of v is 123.4560 and the value of pi is 3.14159265

You can also use the sprintf() function along with disp():

>> s = sprintf('the value of v is %.4f and the value of pi is %.8f', v, pi);
>> disp(s)

which outputs:

the value of v is 123.4560 and the value of pi is 3.14159265

In the examples above, the formatting operator %.4f is a placeholder that tells the fprintf() function that there is a value to be inserted here, and that it is a floating-point value (hence the f) and that 4 decimal places are to be used when printing the floating-point value (hence the .4). The second formatting operator %.8f tells the fprintf() function that there is a second value to be plugged in at that point in the string, and that it is a floating-point value to be shown using 8 decimal places. The \n code at the very end of the string is a newline character which means insert a new line after the string, when printing it to the screen.

There are other codes that you can use with fprintf() or sprintf() that indicate characters, strings, integers, etc. See the MATLAB help page for fprintf() for a table of all the formatting operators you can use and for some other examples of the kinds of formatted output you can produce in MATLAB.