vector conversion from a vector of numbers to a vector cell of chars.

Hello,
In MATLAB I have this vector: Y=[0 4 6] and I need to convert it to this format X={'0' '4' '6'}.
Not sure how to do it.
Thank you

6 commentaires

@Pierre Not sure if this is what you want
Y=[0 4 6]
Y = 1×3
0 4 6
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
X = {string(Y)}
X = 1x1 cell array
{["0" "4" "6"]}
There is a real difference between {["0" "4" "6"]} and {'0' '4' '6'} ... and a difference again for {"0" "4" "6"}.
In the case of {["0" "4" "6"]} you get out a 1 x 1 cell that contains a 1 x 3 string array. In the case of {'0' '4' '6'} you get out a 1 x 3 cell each entry of which is 1 x 1 char vector.
cell arrays containing strings are not recognized as being in "cellstr" format.
"cell arrays containing strings are..."
for good reasons discouraged by the documentation:
which states: "When you have multiple strings, store them in a string array, not a cell array... String arrays are more efficient than cell arrays for storing and manipulating text.... Avoid using cell arrays of strings. When you use cell arrays, you give up the performance advantages that come from using string arrays. And in fact, most functions do not accept cell arrays of strings as input arguments, options, or values of name-value pairs."
I need to provide a commercial code (COMSOL) X={'0' '4' '6'}. I would like to be able to have something like an input file where these numbers (0, 4 & 6) are read and coverted in the format required by COMSOL.
Use any of the techniques indicated by @Stephen23

Connectez-vous pour commenter.

 Réponse acceptée

Y = [0,4,6];
X = cellstr(string(Y))
X = 1x3 cell array
{'0'} {'4'} {'6'}
X = arrayfun(@num2str,Y,'uni',0)
X = 1x3 cell array
{'0'} {'4'} {'6'}
X = compose('%u',Y(:)).'
X = 1x3 cell array
{'0'} {'4'} {'6'}
X = split(num2str(Y)).'
X = 1x3 cell array
{'0'} {'4'} {'6'}
X = num2cell(char(Y+'0')) % unlikely to be what you want
X = 1x3 cell array
{'0'} {'4'} {'6'}
X = sprintfc('%u',Y) % undocumented
X = 1x3 cell array
{'0'} {'4'} {'6'}

Plus de réponses (1)

Matt J
Matt J le 3 Fév 2025
Modifié(e) : Matt J le 3 Fév 2025
Y=[0 4 6];
X=Y+"";
X={X{:}}
X = 1x3 cell array
{'0'} {'4'} {'6'}

2 commentaires

unless I am missing something this is not what I need.
{'0'} {'4'} {'6'} is not {'0' '4' '6'}.
To be sure I tried it in COMSOL and it crashed
Matt J
Matt J le 3 Fév 2025
Modifié(e) : Matt J le 3 Fév 2025
They are the same, as you can see at the command line,
>> {'0' '4' '6'}
ans =
1×3 cell array
{'0'} {'4'} {'6'}
So, you will have to review what it is you think you need.

Connectez-vous pour commenter.

Catégories

Produits

Version

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by