read matrix from txt. files

14 次查看(过去 30 天)
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 个评论
polo Mahmoud
polo Mahmoud 2019-10-31
编辑:polo Mahmoud 2019-10-31
i want some how to read where the start of this [ begins and all the numbers between until ] and then the same for the next matrix ?
Or maybe read all numbers from 1 head line to next head line and ect.
Met V
Met V 2019-10-31
importdata('filename.txt')

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2019-10-31
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 个评论
Walter Roberson
Walter Roberson 2019-11-5
named = regexp(S, '^\s*(?<varname>[A-Za-z]+)\s*=\s*(?<value>[^;\n]*)', 'lineanchors', 'names');
to_replace = cellfun(@(s) ['(?<=\W)' s '(?=\W)'], {named.varname}, 'UniformOutput', false);
replace_with = {named.value};
Smod = regexprep(S, {'^\s*[A-Za-z]+.*$', to_replace{:}}, {'', replace_with{:}}, 'lineanchors', 'dotexceptnewline');
parts_text = regexp(Smod, '(?<=\[).*?(?=\])', 'match');
parts_value = cellfun(@(txt) textscan(txt, '', 'collectoutput', true), parts_text);
Sorry, I renamed the variable as I worked so I still had the old variable name in memory so it passed my testing...
{named.varname} and {named.value} are output from the regexp(), so you do not need to fill in anything.
The code finds all replacements of the form
name = value;
(with no % at the beginning of the line) in the file, and records them all first. Their position in the file is not taken into account. If any name is used twice, then the first of them will have effect.
The code then removes those defining lines, and substitutes the replacements textually without any attempt to understand them. If the line were
A = 10 20] 30 40;
then it would substitute '10 20] 30 40' for each occurance of 'A', whether or not it made sense to do so.
After the substitutions are done, it breaks up into parts according to the [ ] and then it runs textscan on each part to try to convert whatever is there into numeric.
polo Mahmoud
polo Mahmoud 2019-11-5
Thank you very much :D

请先登录,再进行评论。

更多回答(0 个)

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by