Filter löschen
Filter löschen

How to read text line and assign value to variable?

4 Ansichten (letzte 30 Tage)
John
John am 15 Okt. 2018
Bearbeitet: Stephen23 am 16 Okt. 2018
Many tech files have header like this:
int display_order = 1;
int bigendian = 0;
float imagescale = 1.000000000;
float psi = 359.9580;
float phi = 0.0000;
float theta = 90.0000;
float orientation[] = {-1.0000,0.0007,-0.0000,-0.0000,-0.0000,1.0000,0.0007,1.0000,0.0000};
How can each line be assigned to the variable with value (after fgetl)?
For example: the line float
psi = 359.9580;
becomes
psi = float(359.9580);
  1 Kommentar
dpb
dpb am 15 Okt. 2018
float is not valid Matlab data type; either single or double; double is default and Matlab also is un-typed for numeric classes; integers are by default stored as double as well.
You could almost turn it into an m-file as is simply by dropping the first word of each line and rewriting; the empty [] in the array are the only thing preventing that in that sample although the curlies "{}" instead of parenetheses would create a cell array instead of a base numeric array.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

KSSV
KSSV am 16 Okt. 2018
fid = fopen('data.txt','r') ;
S = textscan(fid,'%s','delimiter','\n') ;
fclose(fid) ;
% GEt the line where psi lies
S = S{1} ;
idx = contains(S,'psi') ;
S = S(idx) ;
S = strsplit(S{1}) ;
psi = str2num(S{4})
  2 Kommentare
John
John am 16 Okt. 2018
Thanks, KSSV!
How can we assign the 'psi' which it may not be known ahead as variable name 'psi' (and all other names) ?
Stephen23
Stephen23 am 16 Okt. 2018
Bearbeitet: Stephen23 am 16 Okt. 2018
@John: In general it is a bad idea to magically access a variable name. Read this to know why:
You could write a function and use inputname.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by