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?
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