Convert Array of Float to comma delimited string

33 visualizzazioni (ultimi 30 giorni)
Hi I would like to convert an array of floats to a single string, with commas separating the numbers, as below:
data = [1 2 3 4];
output = "1, 2, 3, 4"
However, I cannot seem to get the commas implemented - here is my attempt:
data2 = cellstr(num2str(data));
output = strjoin(data2, ', ');
i then get an output of;
'1 2 3 4'
What am I doing wrong?

Risposta accettata

Stephen23
Stephen23 il 16 Nov 2020
Modificato: Stephen23 il 16 Nov 2020
data = [1,2,3,4];
strjoin(compose("%d",data),", ") % provides formatting control
ans = "1, 2, 3, 4"
strjoin(""+data,", ") % default formatting
ans = "1, 2, 3, 4"
  2 Commenti
Ted Baker
Ted Baker il 16 Nov 2020
Thank you very much Stephen.
RST
RST il 3 Ago 2023
And for 2D arrays we can do:
data = rand(3,4);
csvData = strjoin( join( compose('%.3f', data), ', '), newline())
csvData =
'0.979, 0.700, 0.043, 0.264 0.007, 0.619, 0.588, 0.401 0.695, 0.447, 0.679, 0.236'

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Data Type Conversion in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by