13

Lets say I have a variable A=5 and i want to output it, but with some text added in front and after it. Something like this: "There are 5 horses." (mind that 5 should be changable variable A)

If I write: disp("There are "),disp(A),disp(" horses.") I get:

There are 
5
 horses.

BUT I want everything in one line.

How do I do that?

user1926550
  • 539
  • 5
  • 10
  • 18

2 Answers2

22

You can use:

A = 5
printf("There are %d horses\n", A)

output:

There are 5 horses

or even

disp(["There are ", num2str(A), " horses"])

or even

disp(strcat("There are ", num2str(A), " horses"))

but you will have to add something because octave/matlab don't let the white space at the end of a string, so the output is:

ans = There are5 horses
ThiS
  • 947
  • 8
  • 16
  • 1
    None of your examples is to actually display, they all generate a string which are only printed as side effect of not being assigned anywhere. That's why you get the `ans =` also printed. The only correct answer is to use `printf` (I edited your answer), or to use display around your other examples) (you should edit your answer for those). – carandraug Mar 07 '13 at 10:03
  • 1
    @ThiS How to display a string and matrix using the same disp() call for e.g. disp("Matrix is - ", M); where M is a matrix. – Ashutosh Chamoli Dec 31 '18 at 02:43
2

As per official documentation,

Note that the output from disp always ends with a newline.

so to avoid the newline, you should use an alternative to output data for each string, or first concatenate a single string and then disp it.

ThiS listed options.