Skip to content

Instantly share code, notes, and snippets.

@dvsseed
Last active June 21, 2022 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvsseed/7f823abdcc677ca06cb2ea58dc401206 to your computer and use it in GitHub Desktop.
Save dvsseed/7f823abdcc677ca06cb2ea58dc401206 to your computer and use it in GitHub Desktop.
To calculate SVD with MATLAB.
% Clear all text from the Command Window.
clc; clear all; close all;
fprintf('SVD -- start calculating...\n');
tic % 開始計時
% data importing
% data = 'LBPhistogram_BGC_20220609.csv';
% data = 'LBPhistogram_BRGC_20220609.csv';
data = 'LBPhistogram_Binary_20220609.csv';
% skip lines after the header line
% opts = detectImportOptions(data);
% opts.DataLines = 2;
% opts.VariableNamesLine = 1;
% tab = readtable(data, opts);
% skip the first line -- header
tab = readtable(data, 'HeaderLines', 1);
% tab = readtable(data, 'Delimiter', ',');
% subTab = Tab(1:10, 1:10);
% converts everything but numbers to MATLAB's NaN
% DTab = str2double(Tab);
tab_arr = table2array(tab);
% ignore the headerline
% T = readtable(filename, 'HeaderLines', 1, 'ReadVariableNames', false);
% singular value decomposition
% [U, S, V] = svd(DTab, "vector");
% Error using svd
% Requested 131072x131072 (128.0GB) array exceeds maximum array
% size preference (13.1GB). This might cause MATLAB to become
% unresponsive.
% check array if any Nan or Inf
% nan_arr = any(any(isnan(tab_arr))); % == 1
% nan_arr = any(isnan(tab_arr(:))); % == 1
% nan_arr = disp(any(isnan(tab_arr(:)))); % == 1
% inf_arr = any(any(isinf(tab_arr))); % == 0
% [numRows, numCols] = size(tab_arr);
% for Finding if ANY NaN values occur in a matrix.
% result = sum(isnan(tab_arr(:)));
[S] = svd(tab_arr, "vector");
% "econ" Calculate the complete and economy-size decompositions of a rectangular matrix.
% Specify the "vector" option to return the singular values in a column vector.
% [U, S, V] = svds(T, 3000); % 將得到最大的3000個特徵值及其對應的最大特徵行向量和特徵列向量
% generalized singular value decomposition
% [U, S, V] = gsvd(T);
% export a matrix/vector as a CSV file
% writematrix(S, 'EigenValue_BGC_20220610.csv', 'Delimiter', ',');
% writematrix(S, 'EigenValue_BGC_20220610.csv');
% writematrix(S, 'EigenValue_BRGC_20220610.csv');
writematrix(S, 'EigenValue_Binary_20220610.csv');
toc % 結束計時
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment