Impossible to set VariableTypes as 'double' for complete array and readtable function
13 ビュー (過去 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 Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!