convert strings of multiple numbers into matrices

Hello,
I am trying to convert the output log of a software into a ready-to-use matrix.
The output of the software is a txt file that contains a serie of strings like this one:
[[-0.4888 -0.4661 -0.7374 54.5679]
[-0.4835 0.8483 -0.2157 25.8953]
[ 0.7262 0.2511 -0.64 58.3138]
[ 0. 0. 0. 1. ]]
I am trying to read in these strings and extract the numbers in order to obtain the following format AKA a normal matlab matrix double precison :
[-0.4888 -0.4661 -0.7374 54.5679;
-0.4835 0.8483 -0.2157 25.8953;
0.7262 0.2511 -0.64 58.3138;
0 0 0 1 ];
I have been able to read in the txt file but I do not understand how to extract all numbers and put it in a normal matrix.
Thanks for your help!
Giacomo

댓글 수: 2

How are you reading the txt file?
with the function "readlines"

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

 채택된 답변

Jan
Jan 2021년 9월 6일
편집: Jan 2021년 9월 6일
% Contents of the text file:
% [[-0.4888 -0.4661 -0.7374 54.5679]
% [-0.4835 0.8483 -0.2157 25.8953]
% [ 0.7262 0.2511 -0.64 58.3138]
% [ 0. 0. 0. 1. ]]
% Code:
C = fileread(FileName);
C(C == '[' || C == ']') = []; % Remove [ and ]
D = sscanf(C, '%g', [4, 4]); % [EDITED]

댓글 수: 3

Thanks for the answer! It gives me an error when running sscanf "too many inputs arguments"
D = sscanf(C, '%g', 4, 4);
Error using sscanf
Too many input arguments.
what can it be? The "C" variuabile is a 4x32 char
@Giacomo Bertazzoli: This was a typo. You can examine such problems by reading the documentation:
doc sscanf
"Too many input arguments" mean, that sscanf accepts less then 4. So check, what the 3rd argument must be: The size of the imported data. I've written "4,4", but it must be "[4, 4]". See my edited code.
Just solved it the same way. Thank you very much! accepting your answer now

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

릴리스

R2020b

태그

질문:

2021년 9월 6일

댓글:

2021년 9월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by