Impossible to set VariableTypes as 'double' for complete array and readtable function
2 次查看(过去 30 天)
显示 更早的评论
Hi everyone,
I'm having trouble to set the VariableTypes for the 'opts' of the readtable function.
Either I can convert only the first column properly, either I get an error. Please see the different try in the code below (line 35 to 48).
I tried the solution of the different post, but it seem that I can't wrap my head around it.
Log file example : "test_log_1.csv"
Matlab code : Execute the function below with [data, xl]= AA_getSamplerData_Mat("test_log_1.csv");
function [data, xlHeader] = AA_getSamplerData_Mat(filename)
%Constant
EXCPECTED_PARAM = 26;
% Check if file exist
%todo
%% import and convert data ONLY FOR HEADER
opts = detectImportOptions(filename);
opts.Delimiter = ' ';
opts.DataLines = [2 EXCPECTED_PARAM+2];
opts.VariableNamingRule = 'preserve';
xlHeader = readtable(filename,opts);
xlHeader = table2array(xlHeader);
%Remove last column, empty for some reason
xlHeader (:,end) = [];
%% import and convert data ONLY FOR DATA
%Check if sampler header as been updated since last script writting
line=1;
while strfind(xlHeader{line,1},'#') == 1
line = line + 1;
end
if (EXCPECTED_PARAM + 1) ~= line
warning("Parameter of the sample file was modified, please edit function");
end
%Read data
opts = detectImportOptions(filename);
opts.Delimiter = ' ';
%Try 1 (uncomment as needed)
% tempVar = repmat("double", 1, length(xlHeader(end,:)));
% opts.VariableTypes = tempVar; %give "Cell array of types must be a vector of length 1"
%Try 2 (uncomment as needed)
opts.VariableTypes = 'double';
T = preview(filename,opts);%Only convert the first column...
%Try 3 (uncomment as needed)
% opts = setvartype(opts, xlHeader(end,:), 'double'); % give "Unknown variable name: 'target-position-x'."
%Try 4 (uncomment as needed)
% opts = setvartype(opts, 'double');
% T = preview(filename,opts);%Same result as try 2
opts.CommentStyle = '#';
opts.DataLines = line + 2;
opts.VariableNamesLine = line + 1;
opts.VariableNamingRule = 'preserve';
xlData = readtable(filename,opts);
%Remove last column, empty for some reason
xlData(:,end) = [];
end
Thanks you in advance for any help
2 个评论
Alexander
2024-3-25
It is always helpful to supply a executable script which shows the error you are dealing with.
采纳的回答
Stephen23
2024-3-25
编辑:Stephen23
2024-3-25
Try something simpler and let READTABLE do the work for you:
T = readtable('test_log_1.csv', 'CommentStyle','#', 'VariableNamingRule','preserve')
And for reading the header numeric parameters:
H = readtable('test_log_1.csv', 'Delimiter',':', 'MissingRule','omitrow',...
'ExpectedNumVariables',2, 'NumHeaderLines',3)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import from MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!