Convert a vector/array/matrix of values into a comma-separated string

Converts input of unknown size/type into compact single-line string suitable for log files & uitable
Updated 9 Feb 2009

No License

Vec2str converts an input of unknown size/type into a compact single-line comma-delimited string which is suitable for log files and uitable cells. Accepts any dimension & combination of numbers, logicals, cells, Java/COM handles etc.

[str, errMsg] = vec2str(vec, format, numericFlag, encloseFlag)

- vec - vector/array/matrix of values (mandatory)
- format - optional format/precision argument accepted by the num2str() function
- numericFlag - optional flag indicating whether to keep scalar (non-vectors) numeric value as-is (default = 0 or false)
- encloseFlag - optional flag indicating whether to enclose numeric vectors with [], cells with {} (default = 1 or true)

- str - string representation of vec (or numeric value if numericFlag was requested)
- errMsg - contains a non-empty string if an error occured during processing

vec2str('abcd') => 'abcd' (string input always returns as-is)
vec2str(pi) => '3.1416'
vec2str(pi,'=> %f <=') => '=> 3.141593 <=' (see SPRINTF for format explanation)
vec2str(pi,8) => '3.1415927' (8 significant digits)
vec2str(pi,8,0) => '3.1415927' (default numericFlag=0 so same result as above)
vec2str(pi,8,1) => 3.14159265358979 (keeps numeric type, overrides format request)
vec2str(pi,[],[],1) => '3.1416' (scalar values are NEVER enclosed with [])
vec2str(magic(3)) => '[8,1,6; 3,5,7; 4,9,2]'
vec2str(magic(3) > 4) => '[true,false,true; false,true,true; false,true,false]'
vec2str(1:4) => '[1,2,3,4]'
vec2str(1:4,[],[],1) => '[1,2,3,4]' (default encloseFlag=1 so same result as above)
vec2str(1:4,[],[],0) => '1,2,3,4'
vec2str({3,2:4,'ryt',NaN, -inf,sqrt(-i),{2,1},java.lang.String('ert')})
=> '{3,[1x3 double],'ryt',NaN,-Inf,[0.707106781186548-0.707106781186548i],{1x2 cell},[1x1 java.lang.String]}'
vec2str({3,2:4,'ryt',NaN, -inf,sqrt(-i),{2,1},java.lang.String('ert')},3,'',0)
=> ' '3','2 3 4','ryt','NaN','-Inf','0.707-0.707i',{1x2 cell},[1x1 java.lang.String]'

See also: num2str, int2str, sprintf

Cite As

Yair Altman (2024). Convert a vector/array/matrix of values into a comma-separated string (, MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2008b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Find more on Characters and Strings in Help Center and MATLAB Answers

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
Version Published Release Notes