How to convert a char array field in a struct array to a string field in a vectorized fashion.
111 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
William Bahn
le 29 Oct 2021
Commenté : William Bahn
le 29 Oct 2021
I have a struct array in which one of the fields is a character array. I need to convert it to a string scalar for all stuctures in the array. I have been unable to find a way to do this in a vectorized manner.
Example:
myArray = [struct("code", 'CO128'), struct("code", 'TX457'];
This is a toy data structure -- the real thing has dozens of fields in each element and tens of thousands of elements in the array. I have no control over the array format up to this point.
What I am trying to accomplish is the same thing that is performed by the following loop:
for i = 1:size(myArray,2)
myArray(i).code = string(myArray(i).code);
end
I am restricted to the functionality of the basic MATLAB R2021a installation (no optional toolboxes).
0 commentaires
Réponse acceptée
Stephen23
le 29 Oct 2021
S = struct('code',{'CO128','TX457'});
S.code % checking
tmp = num2cell(string({S.code}));
[S.code] = tmp{:};
S.code % checking
Plus de réponses (1)
Fangjun Jiang
le 29 Oct 2021
It can be done but not sure if it is more efficient than the simple for-loop
myArray=struct('code',{'a','ab','abc'})
myString=string({myArray.code})
myCell=mat2cell(myString,ones(1,size(myString,1)),ones(1,size(myString,2)))
myArray=struct('code',myCell)
0 commentaires
Voir également
Catégories
En savoir plus sur Data Type Conversion dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!