Output Text in MATLAB

MATLAB is a versatile computer program capable of all levels of math, figure plotting, programming, and signal processing. You may want to output some text to the screen. MATLAB offers several programming functions to accomplish this, each slightly different in its intended application. Select the method that best suits your programming situation.

  1. Disp Function

    • You can display any text, or a "string" in programming nomenclature, on the screen by putting it inside MATLAB's "disp" function. "Disp" is shorthand for "display." For example, if you want to output to the screen the words "Jack is 10 years old today," type the following code at MATLAB's command prompt:

      disp('Jack is 10 years old today.')

      Press "Enter." MATLAB will output your sentence to the screen. It outputs the text, but doesn't store the string.

    Multiple Strings Directly

    • if you type an expression, for example the number "3," MATLAB will only output "3." You can force MATLAB to output only a string that you type. For example, you can type the following at MATLAB's prompt:

      str = ['Jack is 10', 'years old today']

      MATLAB repeats everything typed except for the brackets and single-quotes. Unlike the "disp" function, MATLAB stores the string in a variable. In this example, the variable's name is "str." With this syntax, you can combine multiple strings into a single string.

    Sprintf then Disp

    • MATLAB's "sprintf" is another way to generate a string and store it in a variable. Type this code at the command prompt:

      str = sprintf('Jack is 10 years old today');

      With this function, the semicolon at the end tells MATLAB to perform the action, but to not output the result. Now that you have created the string of text and stored its contents in a variable, you can use the "disp" function to put it on the screen. Use this code:

      disp(str)

    Fprintf Function

    • If you want to create the string, store it and display it with one function, use MATLAB's "fprintf" function. Type the following code at MATLAB's command prompt:

      str = fprintf('Jack is 10 years old today

      All in one action, MATLAB will store your text string in a variable, print it to the screen and not include the "str =" part in front of it, as it did when storing and outputting multiple strings directly.

Related Searches:

References

Resources

Comments

Related Ads

Featured