[matlab] How to display (print) vector in Matlab?

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.

This question is related to matlab printf disp

The answer is


You might try this way:

fprintf('%s: (%i,%i,%i)\r\n','Answer',1,2,3)

I hope this helps.


To print a vector which possibly has complex numbers-

fprintf('Answer: %s\n', sprintf('%d ', num2str(x)));

Here's another approach that takes advantage of Matlab's strjoin function. With strjoin it's easy to customize the delimiter between values.

x = [1, 2, 3];
fprintf('Answer: (%s)\n', strjoin(cellstr(num2str(x(:))),', '));

This results in: 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,') ')'], ',)', ')'))

Here is a more generalized solution that prints all elements of x the vector x in this format:

x=randperm(3);
s = repmat('%d,',1,length(x));
s(end)=[]; %Remove trailing comma

disp(sprintf(['Answer: (' s ')'], x))