How to display (print) vector in Matlab?

2020-05-20 04:41发布

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.

6条回答
甜甜的少女心
2楼-- · 2020-05-20 05:06

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,') ')'], ',)', ')'))
查看更多
一纸荒年 Trace。
3楼-- · 2020-05-20 05:25

You might try this way:

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

I hope this helps.

查看更多
时光不老,我们不散
4楼-- · 2020-05-20 05:26

To print a vector which possibly has complex numbers-

fprintf('Answer: %s\n', sprintf('%d ', num2str(x)));
查看更多
祖国的老花朵
5楼-- · 2020-05-20 05:27

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)

查看更多
我只想做你的唯一
6楼-- · 2020-05-20 05:27

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))
查看更多
Fickle 薄情
7楼-- · 2020-05-20 05:30

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
查看更多
登录 后发表回答