I am trying to show variable names and num2str represent their values ​​in matlab

I am trying to create the following: The new values ​​of x and y are -4 and 7, respectively, using the disp and num2str commands. I tried to do this disp ("The new values ​​of x and y are num2str (x) and num2str (y) respectively"), but he gave num2str instead of the corresponding values. What should I do?

+4
source share
2 answers

As Colin mentioned, one option will convert numbers to strings using num2str , combining all the strings manually and feeding the final result into disp . Unfortunately, this can become very inconvenient and tedious, especially when you have many print numbers. A.

Instead, you can use the power of sprintf , which is very similar to MATLAB in its C programming language counterpart. This leads to shorter, more elegant statements, for example:

 disp(sprintf('The new values of x and y are %d and %d respectively', x, y)) 

You can control the display of variables using format specifiers. For example, if x not necessarily an integer, you can use %.4f , for example, instead of %d .

EDIT: as Jonas pointed out, you can also use fprintf(...) instead of disp(sprintf(...)) .

+6
source

Try:

 disp(['The new values of x and y are ', num2str(x), ' and ', num2str(y), ', respectively']); 

You can also omit commas, but IMHO they make the code more readable.

By the way, what I did here concatenates 5 lines together to form a single line, and then sent that single line to the disp function. Note that I essentially concatenated the string using the same syntax you can use with numeric matrices, i.e. [x, y, z] . The reason I can do this is because matlab stores character strings inside AS numeric string vectors, with each character representing an element. Thus, the above operation essentially combines 5 numeric row vectors horizontally!

One more point: your code did not work, because Matlab processed your num2str (x) as a string, and not as a function. In the end, you may legitimately want to type "num2str (x)" rather than evaluate it with a function call. In my code, the first, third, and fifth lines are defined as lines, and the second and fourth are functions that evaluate the lines.

+5
source

Source: https://habr.com/ru/post/1444965/


All Articles