Creating input files for variables

I'd like to be able to have an external file which gives all the inputs that a user decides, such as min and max values, directory locations and arrays of periods to use. Is there a way of reading in a file such as:
% Min period
1
% Max period
10
% Directory
'/home/Waves'
% Times
1:5:50
So that I get the equivalent of typing
pmin=1
pmax=10
dir='/home/Waves/'
times=1:5:50
into the code itself?

 採用された回答

Stephen23
Stephen23 2014 年 10 月 15 日
編集済み: Stephen23 2014 年 10 月 15 日

0 投票

Put this text in a text file named 'temp.txt':
% Min period
1
% Max period
10
% Directory
'/home/Waves'
% Times
1:5:50
Then run this code:
str = fileread('temp.txt');
val = regexp(str,'^%\s*(.+?)\n(.+?)$','tokens','lineanchors');
val = vertcat(val{:});
num = cellfun(@(s)sscanf(s,'%d:'),val(:,2),'UniformOutput',false);
len = cellfun('length',num);
vec = cellfun(@num2cell,num(len>1),'UniformOutput',false);
num(len>1) = cellfun(@(v)colon(v{:}),vec,'UniformOutput',false);
val(len>0,2) = num(len>0);
out = cell2struct(val(:,2),regexprep(val(:,1),' ','_'));
This reads the file as a string, splits the data into names and values, converts the values to numeric (where possible), creates numeric vectors for either of 'X:Y' or 'X:Y:Z', and then merges these numeric values back into the data array.
The final line is optional: it converts the data array (a cell array) to a struct, which would probably be more useful than the cell array.
Note:
  • The code does not use eval, avoiding any security risk associated with running arbitrary strings from the file.
  • Extends automatically as many input name + value pairs as you want.
  • Parameters must be exactly per your example: '% Name of Parameter' followed by a newline, then the parameter value (either a string, a numeric scalar, or colon-format vector).
  • If you use the struct conversion, the names get used as the struct fieldnames. This limits the choice of characters (read the documentation for more info).

3 件のコメント

Stephen23
Stephen23 2014 年 12 月 18 日
Replacing line three with
val = strtrim(vertcat(val{:}));
which will make it immune to trailing whitespace.
omar ahmed
omar ahmed 2022 年 8 月 25 日
what about if my input is decimal ow can I do it. for ex:
%min
5.5
Katherine Fehr
Katherine Fehr 2023 年 2 月 13 日
You can change the format in the sscan function from decimal to float:
Before:
num = cellfun(@(s)sscanf(s,'%d:'),val(:,2),'UniformOutput',false);
After:
num = cellfun(@(s)sscanf(s,'%f:'),val(:,2),'UniformOutput',false);
More info: https://www.mathworks.com/help/matlab/ref/sscanf.html

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

その他の回答 (0 件)

タグ

質問済み:

Cl
2014 年 10 月 15 日

コメント済み:

2023 年 2 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by