Creating input files for variables
10 views (last 30 days)
Show older comments
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?
Accepted Answer
Stephen23
on 15 Oct 2014
Edited: Stephen23
on 15 Oct 2014
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 Comments
Katherine Fehr
on 13 Feb 2023
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
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!