0

I'm trying to read a line from a text file. This line would be broken down into words by using textscan. The output from textscan would be stored inside an array of structures. Where each structure stores one word and the location it was at in the text file.

For example, the text file may look like this:

Result Time Margin Temperature

And I would like an array of structures where:

headerRow(1).header = Result
headerRow(1).location = 1  
headerRow(2).header = Time    
headerRow(2).location = 2

and so on. This is my code:

headerRow = struct( 'header', 'location' );
headerLine = fgets(currentFile)
temp_cellArray = textscan(headerLine, '%s', ' ')
for i = 1:size(temp_cellArray),
    headerRow(i).header = temp_cellArray{i,1}
    headerRow(i).location = i
end

But this only stores the whole 4x1 cell into the first element of the array. How can I make the code work as I would like it to?

Eitan T
  • 32,660
  • 14
  • 72
  • 109

2 Answers2

1

The line temp_cellArray = textscan(headerLine, '%s', ' ') is returning a cell array of cell arrays. You'll need to get the first element of the cell array, which then has the data you're after.

Before:

temp_cellArray = 

    {4x1 cell}

Modified Code:

temp_cellArray = temp_cellArray{1};
for ii=1:length(temp_cellArray)
  headerRow(ii).header = temp_cellArray{ii};
  headerRow(ii).location = ii;
end

After:

temp_cellArray = 

    'Result'
    'Time'
    'Margin'
    'Temperature'


>> headerRow(:).header

ans =

Result


ans =

Time


ans =

Margin


ans =

Temperature

>> headerRow(:).location

ans =

     1


ans =

     2


ans =

     3


ans =

     4
macduff
  • 4,655
  • 18
  • 29
1

I think it would be better to read the entire file at once with textscan and then using cell2struct, but I cannot suggest anything unless you share more details about the exact structure of your input file. As to your solution, how about the following fix:

headerLine = fgets(currentFile);
H = textscan(headerLine, '%s', ' ');                              %// Headers
L = num2cell(1:numel(H);                                          %// Locations
headerRow = cell2struct([H(:), L(:)], {'header', 'location'}, 2);
Eitan T
  • 32,660
  • 14
  • 72
  • 109