Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display (print) vector in Matlab?

Tags:

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.

like image 741
Edward Ruchevits Avatar asked Feb 17 '13 17:02

Edward Ruchevits


People also ask

How do you represent a vector in MATLAB?

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.

How do you display text and variables in MATLAB?

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.

What is the fprintf command in MATLAB?

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.


2 Answers

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 
like image 187
Uri Cohen Avatar answered Oct 04 '22 05:10

Uri Cohen


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,') ')'], ',)', ')')) 
like image 28
H.Muster Avatar answered Oct 04 '22 07:10

H.Muster