read matrix from txt. files

2 views (last 30 days)
polo Mahmoud
polo Mahmoud on 30 Oct 2019
Commented: polo Mahmoud on 5 Nov 2019
Hi, if I have a txt. file with 2 different matrix in the text. file and i want them to be read into matlab, eg:
this is from the txt. file:
% A =
[ 1 2 3 4
5 6 7 8]
% B =
[9 10 11 12
13 14 15 16]
and i want matlab to know the diffrent between these two element when it reads the file. so i can make them longer or shorter and it should still be able to take both matrix out.
  2 Comments
Met V
Met V on 31 Oct 2019
importdata('filename.txt')

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 31 Oct 2019
S = fileread('YourFile.txt');
parts_text = regexp(S, '\[[\]*\]', 'match');
parts_value = cellfun(@(txt) textscan(txt, '', 'collectoutput', true), parts_text);
parts_value will now (if all went well) be a cell array of numeric arrays, with one entry for each [] delimited block. In this code, it is not required that each block has the same number of rows or columns as the other blocks.
  15 Comments
polo Mahmoud
polo Mahmoud on 5 Nov 2019
Thank you very much :D

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by