I am currently opening a file and parsing arguments in the following way:
ReadParam = 'h0 = %f f0 = %f';
fid = fopen(file);
params = textscan(fid, readParam, 'Delimiter', '\n');
fclose(fid);
h0 = params{1};
f0 = params{2};
disp(h0);
disp(f0);
However, this method assumes a specific order to h0 and f0, by the way readParam and params are defined. How would I parse the argument in such a way that order doesn't matter? This is because in "file", they can be switched (and there are more variables, this is just an example). Thanks!

6 Kommentare

TADA
TADA am 16 Nov. 2018
Bearbeitet: TADA am 16 Nov. 2018
I'd say go regexp
But without knowing the nature of your parameters I can't plan the pattern.
Are they all numeric scalars?
IF so it's pretty simple
g
g am 16 Nov. 2018
They are all numeric scalars. Would regexp handle this, or do you recommend something else?
TADA
TADA am 16 Nov. 2018
Regexp Will Handle For Sure
Is It One Parameters Per Line?
What Are The Delimiters?
DO Parameters Names repeat?
Stephen23
Stephen23 am 16 Nov. 2018
Convert to a structure. Then the import order is totally irrelevant.
g
g am 16 Nov. 2018
One parameter per line, no parameter name repeats.
as for delimiters, I’m not sure what that means, but the current scheme is what I have above.
thanks!
g
g am 16 Nov. 2018
Assumimg my data is of this form:
a = 2
b = 3
How would I create a structure/parse this?

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Stephen23
Stephen23 am 16 Nov. 2018
Bearbeitet: Stephen23 am 16 Nov. 2018

2 Stimmen

It would help most if you uploaded a sample file, so we have something to work with. But here is a simple working example of how to read a file matching your description (you did not upload a sample data file, so I had to create my own test file (attached)) and convert its contents into a structure. Then the order of the contents is irrelevant:
fmt = '%s%f';
opt = {'Delimiter','='};
[fid,msg] = fopen('temp2.txt','rt');
assert(fid>=3,msg)
C = textscan(fid,fmt,opt{:});
fclose(fid);
D = [strtrim(C{1}),num2cell(C{2})].';
S = struct(D{:});
Giving:
>> S.h0
ans = 1.2300
>> S.f0
ans = 4.5600
>> S.z
ans = 6.7890

Weitere Antworten (0)

Gefragt:

g
g
am 16 Nov. 2018

Bearbeitet:

am 16 Nov. 2018

Community Treasure Hunt

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

Start Hunting!

Translated by