首页 > 解决方案 > Matlab从元胞数组到矩阵数组的转换

问题描述

我构建了一个脚本(来自我工作组的不同脚本)来从文件夹中读取数据。问题是最后我得到了一个 1x49 单元格的数据数组。我需要矩阵数组中的数据以使用 matlab 进行瀑布图。

我需要的最终矩阵在第一列中有变量“wave”,从第 2 列到 i(我的数据数组中的单元格数)是我的数据数组中的数据。

我不知道如何进入单个数组字段。

这是我为获取数组中的数据而编写的:

clc;clear;      
selpath = uigetdir; 
filelist = dir(selpath);  
filelist = {filelist.name};
filter = cellfun(@(u) contains(u, '.txt'),filelist);    

data = []; 
for i = 1:numel(filelist)   
    filename = filelist{i};
    filename = [selpath '/' filename];
    delimiter = '\t';

    formatSpec = '%q%q%q%q%q%q%q%[^\n\r]';
    fileID = fopen(filename,'r');
    dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'TextType', 'string',  'ReturnOnError', false);
    fclose(fileID);
    tmp_data =(dataArray{1});
    data{i} = tmp_data; 
 end

有什么聪明的方法可以进入循环吗?还是我需要一个新的循环来改造它?

我试过了: data = cell2mat(data)

但这不会改变我的数据。

编辑:这是我的一个文件的外观:

Data from cystein_21101181_01.txt Node

Date: Thu Apr 08 12:37:33 CEST 2021
User: admin
Spectrometer: 211-0118
Scans to average: 16
cleanPeaks enabled: false
laserRefSpectrum enabled: true
Raster (0) enable: true
Integration Time (sec): 1.000000E0
XAxis mode: Raman Shifts
Number of Pixels in Spectrum: 1152
>>>>>Begin Spectral Data<<<<<
201.679 783.5
203.772 813.94
205.865 825.62
207.956 843
210.046 860.44
212.135 882.44
214.223 900.25
216.311 912.31

我只是将它们保存为.txt一个文件夹中的文件。选择脚本中的文件夹,然后脚本应导入所有光谱并将它们放在一个矩阵中。

标签: arraysmatlabloopsfor-loop

解决方案


鉴于您所有的文件都具有相同的结构,我认为最好使用readtable().

% The start is the same as before
clc;clear;      
selpath = uigetdir; 
filelist = dir(selpath);
filelist = {filelist.name};
filter = cellfun(@(u) contains(u, '.txt'),filelist);    

data = []; 

% Initialize the settings to read your files
opts = delimitedTextImportOptions("NumVariables", 2);
opts.DataLines = [14, Inf]; % Skip the first 13 header lines
opts.Delimiter = " "; % data columns are delimited by spaces
opts.VariableTypes = ["double", "double"]; % specify the variable type for your each columns
opts.ExtraColumnsRule = "ignore"; % ignore any other column
opts.EmptyLineRule = "read"; % read lines even if they're empty
opts.ConsecutiveDelimitersRule = "join"; % treat multiple spaces as only one delimiter
opts.LeadingDelimitersRule = "ignore"; % ignore leading spaces

% Now loop through your files
for i = 1:numel(filelist)
    filename = filelist{i};
    filename = [selpath '/' filename];

    % Read the file and append the data to your array
    data = [data; table2array(readtable(filename, opts))];
    % or maybe? unsure what your wanted:
    % data{i} = table2array(readtable(filename, opts));
end

推荐阅读