Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am trying to display variable names and num2str representations of their values in matlab

I am trying to produce 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 it gave num2str instead of the appropriate values. What should I do?

like image 326
cuabanana Avatar asked Dec 27 '22 14:12

cuabanana


1 Answers

Like Colin mentioned, one option would be converting the numbers to strings using num2str, concatenating all strings manually and feeding the final result into disp. Unfortunately, it can get very awkward and tedious, especially when you have a lot of numbers to print.

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

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

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

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

like image 58
Eitan T Avatar answered Jan 25 '23 22:01

Eitan T