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

Stephen23
Stephen23 2023년 11월 2일
"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.

댓글을 달려면 로그인하십시오.

 채택된 답변

Walter Roberson
Walter Roberson 2023년 11월 2일
편집: Walter Roberson 2023년 11월 2일

0 개 추천

str2num preferably with restricted
coordinates = '[446 154;445 155;444 156;443 156;442 156]';
C = str2num(coordinates, 'Evaluation', 'restricted')
C = 5×2
446 154 445 155 444 156 443 156 442 156
T = array2table(C, 'VariableNames', {'X', 'Y'})
T = 5×2 table
X Y ___ ___ 446 154 445 155 444 156 443 156 442 156

추가 답변 (2개)

Stephen23
Stephen23 2023년 11월 2일

1 개 추천

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
446 154 445 155 444 156 443 156 442 156
Voss
Voss 2023년 11월 2일

0 개 추천

If you have a char vector like this,
coordinates = '[446 154;445 155;444 156;443 156;442 156]';
disp(coordinates)
[446 154;445 155;444 156;443 156;442 156]
then one way to get the numbers out is
C = split(coordinates,';');
C = regexp(C,'[\d+-Ee.]+','match');
C = vertcat(C{:})
C = 5×2 cell array
{'446'} {'154'} {'445'} {'155'} {'444'} {'156'} {'443'} {'156'} {'442'} {'156'}
Then you can do whatever conversion you need. For instance, converting to a matrix makes sense to me:
M = str2double(C)
M = 5×2
446 154 445 155 444 156 443 156 442 156
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)
446,154 445,155 444,156 443,156 442,156
Of course, you can also convert to a table and use writetable, if you prefer:
T = array2table(M) % a table of numbers
T = 5×2 table
M1 M2 ___ ___ 446 154 445 155 444 156 443 156 442 156
filename = 'table_of_numbers.csv';
writetable(T,filename)
% show the file's contents:
type(filename)
M1,M2 446,154 445,155 444,156 443,156 442,156
T = cell2table(C) % a table of char vectors
T = 5×2 table
C1 C2 _______ _______ {'446'} {'154'} {'445'} {'155'} {'444'} {'156'} {'443'} {'156'} {'442'} {'156'}
filename = 'table_of_chars.csv';
writetable(T,filename)
% show the file's contents:
type(filename)
C1,C2 446,154 445,155 444,156 443,156 442,156

카테고리

도움말 센터File Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품

질문:

Asi
2023년 11월 2일

편집:

2023년 11월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by