No data found in the file

2 views (last 30 days)
JÚLIA
JÚLIA on 23 Apr 2025
Answered: Harsh on 4 Jun 2025
I have a main folder, and within it, I have several subfolders containing .csv Excel files. These .csv files are divided into two types of data (TUG and walk). I created a script where the TUG data is placed in one cell, the walk data in another cell, and then it combines the data into a single cell. When I test this script for each of the folders, it correctly creates the cell with the combined data. For this reason, I created a function abcd: function [valoresCombinados] = abcd(mainFolder).
The problem arises in another script where I want to design a large table with all the data from all the folders. It creates a table with the TUG and walk data for one folder, and for the others, only the walk data is present. It shows the message: "No data found in the file." How can I solve this? Thanks
My script for the large table is:
% SCRIPT PRINCIPAL - Procesar carpetas y unir resultados
rootFolder = 'C:\gener nozip'; % <-- Ajusta si lo necesitas
carpetas = dir(rootFolder);
carpetas = carpetas([carpetas.isdir]); % solo carpetas
carpetas = carpetas(~ismember({carpetas.name}, {'.', '..'})); % quitar puntos
datosTotales = {}; % Aquí guardaremos los datos combinados
for k = 1:length(carpetas)
nombreCarpeta = carpetas(k).name;
rutaCompleta = fullfile(rootFolder, nombreCarpeta);
fprintf('📂 Procesando carpeta: %s\n', rutaCompleta);
try
datosCarpeta = abcd(rutaCompleta);
if ~isempty(datosCarpeta)
datosTotales = [datosTotales; datosCarpeta(2:end,:)]; % sin encabezado
if k == 1
encabezados = datosCarpeta(1,:);
end
else
fprintf('⚠️ Sin datos válidos en carpeta: %s\n', nombreCarpeta);
end
catch ME
fprintf(' Error en carpeta %s: %s\n', nombreCarpeta, ME.message);
end
end
% Unir todo
if ~isempty(datosTotales)
tablaFinal = [encabezados; datosTotales];
% Convertir la celda en tabla y usar la primera fila como nombres de columnas
encabezados = matlab.lang.makeValidName(encabezados); % hace válidos los nombres
encabezados = matlab.lang.makeUniqueStrings(encabezados); % asegura que no se repitan
tablaFinal = cell2table(tablaFinal(2:end,:), 'VariableNames', encabezados);
% Guardar en archivo Excel
filename = fullfile(rootFolder, 'RESULTADOS.xlsx');
writetable(tablaFinal, filename);
fprintf(' Resultado guardado en: %s\n', filename);
else
fprintf('🚫 No se encontraron datos para exportar.\n');
end
abcd function:
function [valoresCombinados] = abcd(mainFolder)
excelFiles = dir(fullfile(mainFolder, '*.csv'));
cd(mainFolder)
% Verificar si se encontraron archivos CSV
if isempty(excelFiles)
disp(['No se encontraron archivos CSV en la carpeta: ', mainFolder]);
valoresCombinados = [];
return;
end
valoresCell = cell(ceil(length(excelFiles)/2)+1, 6); % Ajusta el tamaño de la celda
valoresCell(1,:) = {'ID','Measure', 'Sit to Stand - Duration (s)', 'Sit to Stand - Lean Angle (degrees)', 'Stand to Sit - Duration (s)', 'Stand to Sit - Lean Angle (degrees)'};
cellindex = 1;
for j = 1:2:length(excelFiles)
dataTUG = readtable(excelFiles(j).name);
fid = fopen(excelFiles(j).name, 'r');
scan = textscan(fid, '%s', 'Delimiter', '\n');
fclose(fid);
scan = scan{1};
fila_2 = 'No data';
fila_9 = 'No data';
if length(scan) >= 2
fila_2 = scan{2}; % Segunda fila
end
if length(scan) >= 9
fila_9 = scan{9}; % Novena fila
end
% Calcular la fila donde deben guardarse los valores
cellindex = (j + 1) / 2 + 1; % Ajustar índice según iteración de archivos
% Guardar en la celda valoresCell en la fila correcta
valoresCell(cellindex, 1) = {fila_2}; % Segunda fila en la primera columna
valoresCell(cellindex, 2) = {fila_9};
% 1. Agafar la primera fila
newVarNames = dataTUG{1, :};
% 2. Si són cadenes tipus cell, convertir-les a text net
if iscell(newVarNames)
newVarNames = strrep(newVarNames, '"', ''); % Treure cometes si n'hi ha
newVarNames = matlab.lang.makeValidName(newVarNames); % Fer noms vàlids
end
% 3. Assignar els nous noms de columna
dataTUG.Properties.VariableNames = newVarNames;
% 4. Eliminar la primera fila (ja s'ha fet servir com a noms)
dataTUG(1, :) = [];
rowNames = {'Sit to Stand - Duration (s)', 'Sit to Stand - Lean Angle (degrees)', 'Stand to Sit - Duration (s)', 'Stand to Sit - Lean Angle (degrees)'};
selectedRows = ismember(dataTUG{:, 1}, rowNames);
selectedColumn = ismember(dataTUG.Properties.VariableNames, 'Mean'); % Cambiar a Properties.VariableNames
% Asegurarse de que los datos extraídos sean del mismo tipo
extractedData = dataTUG{selectedRows, selectedColumn};
if iscell(extractedData)
extractedData = cellfun(@num2str, extractedData, 'UniformOutput', false);
end
% Verificar si extractedData contiene datos antes de asignar
if ~isempty(extractedData)
valoresCell(cellindex, 3:end) = extractedData;
else
disp(['No se encontraron datos en el archivo: ', excelFiles(j).name]);
end
end
%% Procesar archivos seleccionados para valoresCellwalk
selectedFiles = excelFiles(2:2:end);
valoresCellwalk = cell(length(selectedFiles), 63); % 63 columnas
valoresCellwalk(1, 1) = {'ID'};
valoresCellwalk(1, 2) = {'Measure'};
for j = 1:length(selectedFiles)
fileName = fullfile(mainFolder, selectedFiles(j).name); % Construye la ruta completa del archivo
fid = fopen(fileName, 'r'); % Abrir el archivo en modo de solo lectura
scan = textscan(fid, '%s', 'Delimiter', '\n'); % Leer el archivo línea por línea
fclose(fid); % Cerrar el archivo
scan = scan{1}; % Extraer las líneas leídas en una celda
rowsToExtract = 20:80; % Filas de la A20 a A80
rowsToExtract = rowsToExtract(rowsToExtract <= length(scan)); % Ajustar si el archivo tiene menos filas
extractedData = cell(length(rowsToExtract), 3); % 3 columnas para las 3 palabras separadas
for i = 1:length(rowsToExtract)
row = rowsToExtract(i);
line = scan{row}; % Obtener la línea de texto correspondiente
parts = strsplit(line, '","');
words = strsplit(parts{1}, '-');
extractedData{i, 1} = strtrim(words{1}); % Primer palabra
extractedData{i, 2} = strtrim(words{2}); % Segunda palabra
extractedData{i, 3} = strtrim(words{3}); % Tercer palabra
for k = 2:length(parts)
numStr = strrep(parts{k}, ',', '.'); % Reemplazar comas decimales por puntos
numStr = strrep(numStr, '"', ''); % Eliminar comillas
extractedData{i, k+2} = str2double(numStr);
end
end
% Guardar ID y Measure
if length(scan) >= 2
valoresCellwalk{j + 1, 1} = scan{2};
else
valoresCellwalk{j + 1, 1} = 'No data';
end
if length(scan) >= 9
valoresCellwalk{j + 1, 2} = scan{9};
else
valoresCellwalk{j + 1, 2} = 'No data';
end
% Guardar datos
for i = 1:min(length(rowsToExtract), 61) % Máximo 61 valores
valoresCellwalk{1, i+2} = extractedData{i, 3};
if size(extractedData, 1) >= i % Verifica que haya suficientes filas en extractedData
valoresCellwalk{j + 1, i+2} = extractedData{i, 6}; % Guardar en la fila j+1, columna i+2
else
valoresCellwalk{j + 1, i+2} = NaN; % Si no hay datos, asigna NaN
end
end
end
% Asegurar que las dimensiones coincidan antes de combinar
numRowsCell = size(valoresCell, 1);
numRowsCellwalk = size(valoresCellwalk, 1);
maxRows = max(size(valoresCell,1), size(valoresCellwalk,1));
% Asegurar que ambas celdas tengan el mismo número de filas
if size(valoresCell,1) < maxRows
valoresCell(end+1:maxRows, :) = {[]}; % Rellena con celdas vacías
end
if size(valoresCellwalk,1) < maxRows
valoresCellwalk(end+1:maxRows, :) = {[]}; % Rellena con celdas vacías
end
% Crear una celda para los datos combinados (2 columnas ID + Measure + 4 columnas de valoresCell + 61 columnas de valoresCellwalk)
valoresCombinados = cell(numRowsCell, 67); % 2 columnas de ID y Measure + 4 columnas de valoresCell + 61 columnas de valoresCellwalk
% Copiar las primeras 2 columnas (ID y Measure) de valoresCell a valoresCombinados
valoresCombinados(:, 1:2) = valoresCell(:, 1:2); % ID y Measure
% Copiar las 4 columnas de datos de valoresCell a valoresCombinados
valoresCombinados(:, 3:6) = valoresCell(:, 3:6); % Datos de valoresCell
% Copiar las 61 columnas de datos de valoresCellwalk a valoresCombinados
valoresCombinados(:, 7:end) = valoresCellwalk(:, 3:end);
end

Answers (1)

Harsh
Harsh on 4 Jun 2025
It seems the primary reason you are encountering the "No data found in the file" message is likely due to how files are being identified and paired within the "abcd" function. The script relies on the order of files returned by "dir" and uses fixed indexing (j=1:2:length(excelFiles) for TUG, excelFiles(2:2:end) for walk), which is not robust if filenames don't sort perfectly into alternating TUG/WALK pairs in every folder.
In order to fix this, I would recommend you to modify the "abcd" function to reliably identify TUG and WALK files by name instead of relying on their order.
Please note that using cd(mainFolder) within a function can lead to unexpected behaviors like broken relative path, though the main issue here seems to be file identification.
I hope this helps, thanks!

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!