问题
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.
回答1:
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
回答2:
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,') ')'], ',)', ')'))
回答3:
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)
回答4:
You might try this way:
fprintf('%s: (%i,%i,%i)\r\n','Answer',1,2,3)
I hope this helps.
回答5:
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))
回答6:
To print a vector which possibly has complex numbers-
fprintf('Answer: %s\n', sprintf('%d ', num2str(x)));
来源:https://stackoverflow.com/questions/14924181/how-to-display-print-vector-in-matlab