Impossible to set VariableTypes as 'double' for complete array and readtable function
Mostrar comentarios más antiguos
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 comentarios
Alexander
el 25 de Mzo. de 2024
It is always helpful to supply a executable script which shows the error you are dealing with.
xavier soltner
el 25 de Mzo. de 2024
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Data Type Conversion en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!