Read equations from a text file and create a cell array in MATLAB

8 ビュー (過去 30 日間)
Tiasa Ghosh
Tiasa Ghosh 2018 年 5 月 7 日
回答済み: Walter Roberson 2018 年 5 月 7 日
Hello everybody! I have a text file with 8000 equations and I want to create a cell array of 8000x1 for the equations as strings. I have considered textscan for this purpose, but all the equations doesn't have same number of variables and hence I cannot specify the number of columns. How do I go about it? Example:
equations.txt:
1. a=b+c
2. d=e+f+g+h
3. y=2+x*z
  4 件のコメント
Walter Roberson
Walter Roberson 2018 年 5 月 7 日
Are the line numbers present in the file? If they are do you want them read in or discarded?
Tiasa Ghosh
Tiasa Ghosh 2018 年 5 月 7 日
the line numbers are not present in the file. I wrote them just to number the equations. the equations ma contain special characters too.

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2018 年 5 月 7 日
Provided there are no UNICODE or UTF-8 characters in the file:
filename = 'equations.txt';
S = fileread(filename);
equations = regexp(S, '\r?\n', 'split');
if isempty(equations{end}); equations(end) = []; end %last entry is often empty due to the way regexp split works
If the file does include Unicode that is UTF encoded, then potentially more steps would need to be used to read it properly.

その他の回答 (1 件)

Ameer Hamza
Ameer Hamza 2018 年 5 月 7 日
編集済み: Ameer Hamza 2018 年 5 月 7 日
The following lines will read the lines from the text file and return a cell array of function handles
f = fopen('test.txt');
q = textscan(f, '%s');
fclose(f);
funHandles = cell(1, length(q{1}));
for i=1:length(q{1})
splitAtEqualSign = strsplit(q{1}{i}, '=');
rhs = splitAtEqualSign{2};
funHandles{i} = matlabFunction(str2sym(rhs));
end
  3 件のコメント
Ameer Hamza
Ameer Hamza 2018 年 5 月 7 日
編集済み: Ameer Hamza 2018 年 5 月 7 日
Then don't run for loop. q{1} contain cell array of strings.
Ameer Hamza
Ameer Hamza 2018 年 5 月 7 日
Since you mentioned that line numbers are not present. I have updated the answer.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by