2

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!

Suever
  • 64,497
  • 14
  • 82
  • 101
Neros
  • 59
  • 1
  • 5

1 Answers1

4

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);
Suever
  • 64,497
  • 14
  • 82
  • 101