Creating input files for variables
13 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Cl
el 15 de Oct. de 2014
Comentada: Stephen23
el 14 de Feb. de 2023
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?
Respuesta aceptada
Stephen23
el 15 de Oct. de 2014
Editada: Stephen23
el 15 de Oct. de 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 comentarios
Katherine Fehr
el 13 de Feb. de 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
Más respuestas (0)
Ver también
Categorías
Más información sobre Data Type Conversion en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!