Creating input files for variables
조회 수: 21 (최근 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
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
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 Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!