How can I add ' ' to each number in a column?

9 visualizzazioni (ultimi 30 giorni)
Eric
Eric il 31 Ott 2016
Commentato: dpb il 31 Ott 2016
Hi everybody,
I have a struct containing names and a number in two separate columns (like findings.labels and findings.number) and I would like to add ' ' around each number in the column findings.number (to convert it to a cell-array).
Is there an easy way to do this?
Best,
Eric
  1 Commento
jupiter
jupiter il 31 Ott 2016
Maybe you can try using num2str() function to convert it to text and then concatenate ' at the starting and at the end.

Accedi per commentare.

Risposte (2)

Walter Roberson
Walter Roberson il 31 Ott 2016
If you just want to convert to cell array, you can use num2cell(findings.number)
If you want to convert the numbers into corresponding strings, then you can use cellstr(num2str(findings.number))
If you specifically need apostrophes to appear for display purposes, then you can use
cellstr(num2str(findings.number, '''%g'''))
where you should change %g to an appropriate format for your values.

dpb
dpb il 31 Ott 2016
"...add ' ' around each number ... (to convert it to a cell-array)."
Adding quotes doesn't "convert" to a cell array; the single quotes around a cellstr array element are simply a fignewton of the Matlab display to differentiate cell strings from character arrays; they do not exist other than as part of the presentation.
To convert a numeric field to cell string, use something like
findings.number={num2str(findings.number};
If findings is a struct array, you may need to use structfun; I didn't test for certain...
  2 Commenti
Walter Roberson
Walter Roberson il 31 Ott 2016
Note: num2str() of a column vector produces a character array with multiple rows. {} around that produces a 1x1 cell array with the entire character array as its content. But cellstr() applied to the character array will turn it into a cell array with as many cells as rows in the character array, with each entry being one string that has had trailing blanks removed.
dpb
dpb il 31 Ott 2016
Valid points, Walter...from the way was written I assumed each array member had a single value, not an array.
I should have mentioned cell2struct rather than structfun to do the assignment (as the latter is applied to all fields of a structure, not as an iterator over the array members for a given field) altho I'm not sure one can modify an existing structure array that way; may have to loop and store the elements individually.

Accedi per commentare.

Categorie

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

Community Treasure Hunt

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

Start Hunting!

Translated by