Neros
Neros

Reputation: 59

Matlab: is it possible to import data from ascii file and put them in a struct?

I have a file like this (param.txt):

JSS 2
ADEV 1
VERS 770
JSD 1

And I want to put the data from this file into a struct with a variable in my workplace.

Let say I call it "P", then P is the struct of:

Field    Value
_____  |_______
JSS    |2  
ADEV   |1  
VERS   |770  
JSD    |1  

Then:

>>> P.JSS
ans = 
2

Is it possible?

Thanks!

Upvotes: 2

Views: 152

Answers (1)

Suever
Suever

Reputation: 65430

Yes, you can use textscan to grab all of the parts and then create your cell using the struct constructor.

fid = fopen('filename.txt', 'r');

% Parse out the fieldnames and numbers
data = textscan(fid, '%s %d');

% Put the strings in the first row and the numbers in the second
alldata = [data{1}, num2cell(data{2})].';

% Pass fieldnames and values to struct()
P = struct(alldata{:});

fclose(fid);

Upvotes: 4

Related Questions