Creating input files for variables

17 次查看(过去 30 天)
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
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 个评论
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 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by