function [labels, images] = read_mnist8m_libsvm_parallel(filename, num_samples) % Open file and read all lines in one go (fast) fid = fopen(filename, 'r'); if fid == -1 error('Could not open file.'); end data = textscan(fid, '%s', num_samples, 'Delimiter', '\n'); fclose(fid); data = data{1}; % Extract cell array of strings labels = zeros(num_samples, 1, 'uint8'); % Labels images = zeros(num_samples, 784, 'uint8'); % Preallocate matrix for images % Start parallel processing parfor i = 1:num_samples line = data{i}; % Extract current line parts = strsplit(line, ' '); % Split line into parts % First part is the label labels(i) = str2double(parts{1}); % Remaining parts are pixel index:value pairs pixel_data = parts(2:end); pixel_info = split(pixel_data, ':'); % Efficient parsing of indices and values indices = str2double(pixel_info(:, :, 1)); % Convert indices to numeric values = str2double(pixel_info(:, :, 2)); % Convert values to numeric % Assign pixel values in a local temporary array temp_img = zeros(1, 784, 'uint8'); temp_img(indices) = values; % Store the processed image in the main matrix images(i, :) = temp_img; end end