Home > database >  Matlab How to display a series of numbers from a vector as a string?
Matlab How to display a series of numbers from a vector as a string?

Time:09-21

I know that num2str can be used like:

tested = 3.53;
X=[The mean of the data set is:', num2str(tested)];
disp(X);
Output: The mean of the data set is: 3.53

My question is how do I use a similar method to display a vector? Essentially I have a vector given by Concentration=[3.5, 3.8, 3.2, 3.9] and would like to print out something along the lines of "The concentrations of the data set are: 3.5, 3.8, 3.2, 3.9"

CodePudding user response:

The obvious answer is:

disp(['The concentrations of the data set are: ' mat2str(Concentration)])

But it doesn't give the output you require:

The concentrations of the data set are: [3.5 3.8 3.2 3.9]

Here are two hacky options:

fprintf('The concentrations of the data set are: ')
fprintf('%.1f, ', Concentration)
fprintf('\b\b\n')

Output:

The concentrations of the data set are: 3.5, 3.8, 3.2, 3.9

Note that the middle fprintf works with any number of elements. The \b\b removes the trailing space and comma.

Also:

outstr = strrep(mat2str(Concentration), ' ', ', ')
disp(['The concentrations of the data set are: ' outstr(2:end-1)])

Output:

The concentrations of the data set are: 3.5, 3.8, 3.2, 3.9

CodePudding user response:

You can use strjoin to build the string and fprintf to include it in a sentence.

conc = [3.5, 3.8, 3.2, 3.9]; 
concStr = arrayfun( @num2str, conc, 'uni', 0 ); % convert to cell of chars

% Join all values with the separator ', ' and then use this single string with fprintf
fprintf( 'The concentrations of the data set are: %s', strjoin( concStr, ', ' );

CodePudding user response:

Try the new compose() function! It's like an array-oriented sprintf().

strjoin(compose("%0.2f", Concentration), ", ")

Gives you:

ans = 
    "3.50, 3.80, 3.20, 3.90"
  • Related