Matlab 将数据从单元格数组复制到结构数组中
我正试图从文本文件中读取一行。使用Matlab 将数据从单元格数组复制到结构数组中,matlab,structure,cell-array,Matlab,Structure,Cell Array,我正试图从文本文件中读取一行。使用textscan将此行分解为单词。textscan的输出将存储在一个结构数组中。其中每个结构存储一个单词及其在文本文件中的位置 例如,文本文件可能如下所示: Result Time Margin Temperature 我想要一组结构,其中: headerRow(1).header = Result headerRow(1).location = 1 headerRow(2).header = Time headerRow(2).location
textscan
将此行分解为单词。textscan
的输出将存储在一个结构数组中。其中每个结构存储一个单词及其在文本文件中的位置
例如,文本文件可能如下所示:
Result Time Margin Temperature
我想要一组结构,其中:
headerRow(1).header = Result
headerRow(1).location = 1
headerRow(2).header = Time
headerRow(2).location = 2
等等。这是我的代码:
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
但这只将整个4x1单元存储到数组的第一个元素中。
如何使代码按我所希望的方式工作?行
temp\u ceralray=textscan(headerLine,'%s','')
正在返回一个单元格数组的单元格数组。您需要获取单元格数组的第一个元素,该元素包含您要查找的数据
之前:
temp_cellArray =
{4x1 cell}
修改代码:
temp_cellArray = temp_cellArray{1};
for ii=1:length(temp_cellArray)
headerRow(ii).header = temp_cellArray{ii};
headerRow(ii).location = ii;
end
之后:
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
我认为最好是一次读取整个文件,然后使用,但我不能提出任何建议,除非您共享有关输入文件确切结构的更多详细信息。对于您的解决方案,以下修复如何:
headerLine = fgets(currentFile);
H = textscan(headerLine, '%s', ' '); %// Headers
L = num2cell(1:numel(H); %// Locations
headerRow = cell2struct([H(:), L(:)], {'header', 'location'}, 2);