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 Comments

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

Sign in to comment.

 Accepted Answer

Jan
Jan on 6 Sep 2021
Edited: Jan on 6 Sep 2021
% 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 Comments

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

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2020b

Tags

Community Treasure Hunt

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

Start Hunting!