I have a vector x = (1, 2, 3)
and I want to display (print) it as Answer: (1, 2, 3)
.
I have tried many approaches, including:
disp('Answer: ') strtrim(sprintf('%f ', x))
But I still can't get it to print in format which I need.
Could someone point me to the solution, please?
EDIT: Both the values and (length of) x
are not known in advance.
You can create a vector both by enclosing the elements in square brackets like v=[1 2 3 4 5] or using commas, like v=[1,2,3,4,5]. They mean the very same: a vector (matrix) of 1 row and 5 columns.
To display a text in MATLAB, we use 'disp function' which displays the text or value stored in a variable without actually printing the name of the variable.
fprintf uses the encoding scheme specified in the call to fopen . example. fprintf( formatSpec , A1,...,An ) formats data and displays the results on the screen. example. nbytes = fprintf(___) returns the number of bytes that fprintf writes, using any of the input arguments in the preceding syntaxes.
I prefer the following, which is cleaner:
x = [1, 2, 3]; g=sprintf('%d ', x); fprintf('Answer: %s\n', g)
which outputs
Answer: 1 2 3
You can use
x = [1, 2, 3] disp(sprintf('Answer: (%d, %d, %d)', x))
This results in
Answer: (1, 2, 3)
For vectors of arbitrary size, you can use
disp(strrep(['Answer: (' sprintf(' %d,', x) ')'], ',)', ')'))
An alternative way would be
disp(strrep(['Answer: (' num2str(x, ' %d,') ')'], ',)', ')'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With