Convert char to table
48 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Asi
le 2 Nov 2023
Modifié(e) : Walter Roberson
le 2 Nov 2023
Hi,
I have a series of coordinates as char type (disp output):
[446 154;445 155;444 156;443 156;442 156]
How can I convert them to table so can be save like this using writetable:
446 154
445 155
444 156
443 156
442 156
Thanks
1 commentaire
Stephen23
le 2 Nov 2023
"I have a series of coordinates as char type (disp output)"
Best solution: avoid the indirection of printing numeric data to text and then converting from text back into numeric.
Réponse acceptée
Walter Roberson
le 2 Nov 2023
Modifié(e) : Walter Roberson
le 2 Nov 2023
str2num preferably with restricted
coordinates = '[446 154;445 155;444 156;443 156;442 156]';
C = str2num(coordinates, 'Evaluation', 'restricted')
T = array2table(C, 'VariableNames', {'X', 'Y'})
0 commentaires
Plus de réponses (2)
Stephen23
le 2 Nov 2023
If you already have a character vector and the goal is to print it to file, then avoid the indirection of converting to numeric just so that you can use WRITEMATRIX:
txt = '[446 154;445 155;444 156;443 156;442 156]';
spl = split(replace(txt,["]","["],""),";");
writelines(spl,'test.txt')
Check the file content:
type test.txt
0 commentaires
Voss
le 2 Nov 2023
If you have a char vector like this,
coordinates = '[446 154;445 155;444 156;443 156;442 156]';
disp(coordinates)
then one way to get the numbers out is
C = split(coordinates,';');
C = regexp(C,'[\d+-Ee.]+','match');
C = vertcat(C{:})
Then you can do whatever conversion you need. For instance, converting to a matrix makes sense to me:
M = str2double(C)
in which case you would use writematrix to write it to a file:
filename = 'matrix.csv';
writematrix(M,filename)
% show the file's contents:
type(filename)
Of course, you can also convert to a table and use writetable, if you prefer:
T = array2table(M) % a table of numbers
filename = 'table_of_numbers.csv';
writetable(T,filename)
% show the file's contents:
type(filename)
T = cell2table(C) % a table of char vectors
filename = 'table_of_chars.csv';
writetable(T,filename)
% show the file's contents:
type(filename)
0 commentaires
Voir également
Catégories
En savoir plus sur Data Type Conversion dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!