% QCB W12: Intro to MATLAB % W12_Day2_student_updated_v1 % ----------------------------------- % Day 2 - Improved Examples and Explanations %% % Define variables mynumber = 3.34; myvect = [1; 2; 3]; myarray = [1, 2, 3; 4, 5, 6]; %% % Demonstrate array/matrix functions disp('Array size and matrix operations examples:'); size(myarray) % Display size of the matrix myrange = 1:2:10; % Generate a range with step size 2 disp('Range:'); disp(myrange); %% % Matrix element-wise operations result = [1, 2, 3] .^ 2; % Square each element disp('Element-wise operations:'); disp(result); %% % Demonstrate functions sinValues = sin(pi * [1, 2, 3]); % Compute sine values disp('Sine values:'); disp(sinValues); %% % Access matrix elements a = [1, 2; 3, 4]; disp('Matrix element a(1,2):'); disp(a(1, 2)); %% % Nested for loops for matrix traversal for ii = 1:size(a, 1) for jj = 1:size(a, 2) fprintf('a(%d,%d) = %.2f\n', ii, jj, a(ii, jj)); end end %% % Writing to a formatted text file fileName = 'outputData.tab'; fileID = fopen(fileName, 'w'); for ii = 1:size(a, 1) fprintf(fileID, '%8.2f\t', a(ii, :)); fprintf(fileID, '\n'); end fclose(fileID); %% % Reading from a file data = readtable('dataFile.txt'); % Example file read disp('Data from file:'); disp(data); % Note: Ensure 'dataFile.txt' exists in the current folder. %% % QCB W12: Intro to MATLAB % W12_Day2_student_updated_v2 % ----------------------------------- % Recap of fundamental MATLAB concepts %% % Define variables and arrays mynumber = 3.34; myvect = [1; 2; 3]; myarray = [1, 2, 3; 4, 5, 6]; %% % Display array size and operations disp('Array size:'); disp(size(myarray)); %% % Generating arrays: ones, zeros, eye, rand, randn onesArray = ones(2, 3); zerosArray = zeros(2, 3); identityMatrix = eye(3); randomArray = rand(2, 3); normalRandomArray = randn(2, 3); %% % Generating ranges range1 = 1:10; range2 = 1:2:10; disp('Generated Ranges:'); disp(range1); disp(range2); %% % Element-wise operations result1 = [1, 2, 3] .^ 2; % Element-wise squaring result2 = [1, 2; 3, 4] ^ 2; % Matrix multiplication disp('Element-wise operation results:'); disp(result1); %% % Functions and matrix operations sinValues = sin(pi * [1, 2, 3]); matrixSum = sum(myarray, 2); % Sum along rows matrixMean = mean(myarray, 1); % Mean along columns disp('Sine values:'); disp(sinValues); %% % Accessing elements and slices of a matrix a = [1, 2; 3, 4]; disp('Matrix element a(1,2):'); disp(a(1, 2)); %% % Nested for loops for matrix traversal for ii = 1:size(a, 1) for jj = 1:size(a, 2) fprintf('a(%d,%d) = %.2f\n', ii, jj, a(ii, jj)); end end %% % Formatted output using fprintf a = [1, 2, 3, 4; 11, 22, 33, 44]; for ii = 1:size(a, 1) for jj = 1:size(a, 2) fprintf('%10d %10d : %8.2f\n', ii, jj, a(ii, jj)); end end %% % Writing formatted data to a file fileName = 'myfile2.tab'; fileID = fopen(fileName, 'w'); for ii = 1:size(a, 1) for jj = 1:size(a, 2) fprintf(fileID, '%8.2f\t', a(ii, jj)); end fprintf(fileID, '\n'); end fclose(fileID); %% % Reading files % numData = importdata('edata/numfile.txt'); % numTable = readtable('edata/numfile.txt'); % mixData = readtable('edata/flist.txt'); %% % Example plotting series = readtable('series.txt'); disp('Series data loaded for plotting'); % QCB W12: Intro to MATLAB % importfile_updated_v1 % ----------------------------------- function dataTable = importFile(filename, dataLines) % IMPORTFILE imports data from a specified text file into a table. % Inputs: % - filename: Path to the text file. % - dataLines: Row intervals for reading (default: [2, Inf]). % Set default dataLines if not provided if nargin < 2 dataLines = [2, Inf]; end % Configure import options opts = delimitedTextImportOptions("NumVariables", 3); opts.DataLines = dataLines; opts.Delimiter = "\t"; opts.VariableNames = ["Var1", "Name", "Expression"]; opts.SelectedVariableNames = ["Name", "Expression"]; opts.VariableTypes = ["string", "string", "double"]; opts.ExtraColumnsRule = "ignore"; opts.EmptyLineRule = "read"; opts = setvaropts(opts, ["Var1", "Name"], "WhitespaceRule", "preserve"); opts = setvaropts(opts, ["Var1", "Name"], "EmptyFieldRule", "auto"); % Attempt to read the table, with error handling try dataTable = readtable(filename, opts); catch ME error('Failed to read file: %s\nError: %s', filename, ME.message); end end %% % QCB W12: Intro to MATLAB % importfile_updated_v2 % ----------------------------------- function YBL005W = importFile(filename, dataLines) % IMPORTFILE Imports data from a text file into a MATLAB table. % YBL005W = IMPORTFILE(FILENAME) reads data from FILENAME with default row range [2, Inf]. % YBL005W = IMPORTFILE(FILENAME, DATALINES) reads data from specified row intervals. % % Example: YBL005W = importFile("C:\path\to\your\file.txt", [2, Inf]); % % Auto-generated by MATLAB on 31-Oct-2024 % Handle optional input if nargin < 2 dataLines = [2, Inf]; end % Set up the import options opts = delimitedTextImportOptions("NumVariables", 3); opts.DataLines = dataLines; opts.Delimiter = "\t"; opts.VariableNames = ["Var1", "Name", "expr"]; opts.SelectedVariableNames = ["Name", "expr"]; opts.VariableTypes = ["string", "string", "double"]; opts.ExtraColumnsRule = "ignore"; opts.EmptyLineRule = "read"; opts = setvaropts(opts, ["Var1", "Name"], "WhitespaceRule", "preserve"); opts = setvaropts(opts, ["Var1", "Name"], "EmptyFieldRule", "auto"); % Try reading the file try YBL005W = readtable(filename, opts); catch ME error('Error reading file %s: %s', filename, ME.message); end end % QCB W12: Intro to MATLAB % merge_updated_v1 % ----------------------------------- function mergedData = mergeDataFiles(fileListPath) % MERGEDATAFILES imports and merges data from a list of text files. % Input: % - fileListPath: Path to the file containing the list of files to merge. % Read file list opts = delimitedTextImportOptions("NumVariables", 1, "DataLines", [2, Inf]); opts.Delimiter = ","; opts.VariableNames = "file"; opts.VariableTypes = "string"; opts.ExtraColumnsRule = "ignore"; opts.EmptyLineRule = "read"; opts = setvaropts(opts, "file", "WhitespaceRule", "preserve"); opts = setvaropts(opts, "file", "EmptyFieldRule", "auto"); try fileList = readtable(fileListPath, opts); catch ME error('Error reading file list: %s', ME.message); end % Initialize variables mergedData = table(); labels = {}; % Iterate through each file for ii = 1:height(fileList) fileName = fileList.file{ii}; data = importFile(fileName); % Process data if it meets criteria expr = data.Expression; if mean(expr) > -1 geneName = extractBefore(fileName, ".txt"); mergedData = [mergedData, table(expr, 'VariableNames', {geneName})]; %#ok labels = [labels, {geneName}]; %#ok end end % Plot the data using the improved boxplot function createBoxPlot(mergedData{:,:}, labels); end %% % QCB W12: Intro to MATLAB % merge_updated_v2 % ----------------------------------- % Import data from a text file % This script reads multiple text files specified in a list and merges them % Auto-generated by MATLAB on 31-Oct-2024 % Set up the import options opts = delimitedTextImportOptions("NumVariables", 1); opts.DataLines = [2, Inf]; opts.Delimiter = ","; opts.VariableNames = "file"; opts.VariableTypes = "string"; opts.ExtraColumnsRule = "ignore"; opts.EmptyLineRule = "read"; opts = setvaropts(opts, "file", "WhitespaceRule", "preserve"); opts = setvaropts(opts, "file", "EmptyFieldRule", "auto"); % Import the file list try flist = readtable("C:\Users\lukasz\Desktop\W12\split\flist.txt", opts); catch ME error('Error reading file list: %s', ME.message); end % Initialize variables etab = table(); labels = {}; % Loop through each file in the list for ii = 1:height(flist) fileName = flist.file{ii}; series = importFile(fileName); % Use the updated import function expr = series.expr; % Process and merge data if mean(expr) > -1 if mean(expr) > -1 geneName = extractBefore(fileName, ".txt"); etab = [etab, table(expr, 'VariableNames', {geneName})]; %#ok labels = [labels, {geneName}]; %#ok fprintf('%s %s\n', fileName, geneName); % Output for logging end end % Create box plot using the custom function createBoxPlot(etab{:,:}, labels); % QCB W12: Intro to MATLAB % createboxplot_updated_v1 % ----------------------------------- function createBoxPlot(yData, xLabels) % CREATEBOXPLOT generates a box plot for the given data with labeled x-axis. % Inputs: % - yData: Data to be represented in the box chart (numeric array). % - xLabels: Labels for each data category (cell array of strings). % Check input validity if nargin < 2 || isempty(yData) || isempty(xLabels) error('Both yData and xLabels must be provided and non-empty.'); end % Create figure figureHandle = figure('Name', 'Box Plot', 'NumberTitle', 'off'); % Create axes and hold for multiple plots if necessary axesHandle = axes('Parent', figureHandle); hold(axesHandle, 'on'); % Plot box chart boxchart(yData, 'BoxFaceColor', 'cyan'); xticklabels(xLabels); % Set title and labels title('Box Plot of Given Data'); xlabel('Categories'); ylabel('Values'); % Release the hold state hold(axesHandle, 'off'); end %% % QCB W12: Intro to MATLAB % createboxplot_updated_v2 % ----------------------------------- function createBoxPlot(ydata1, xlabels) % CREATEBOXPLOT Generates a box plot for the provided data. % ydata1: Data to be represented in the boxchart (numeric array) % xlabels: Labels for the categories on the x-axis (cell array of strings) % Check for valid input arguments if nargin < 2 || isempty(ydata1) || isempty(xlabels) error('Both ydata1 and xlabels must be provided and cannot be empty.'); end % Create figure figure1 = figure('Name', 'Box Plot', 'NumberTitle', 'off'); % Create axes and hold axes1 = axes('Parent', figure1); hold(axes1, 'on'); % Create boxchart boxchart(ydata1); xticklabels(xlabels); % Enhance plot with labels and title title('Box Chart Representation'); xlabel('Categories'); ylabel('Values'); % Release the hold hold(axes1, 'off'); end