{"text": "function sim = gaussianKernel(x1, x2, sigma)\n%RBFKERNEL returns a radial basis function kernel between x1 and x2\n% sim = gaussianKernel(x1, x2) returns a gaussian kernel between x1 and x2\n% and returns the value in sim\n\n% Ensure that x1 and x2 are column vectors\nx1 = x1(:); x2 = x2(:);\n\n% You need to return the following variables correctly.\nsim = 0;\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Fill in this function to return the similarity between x1\n% and x2 computed using a Gaussian kernel with bandwidth\n% sigma\n%\n%\ndiff = x1 - x2;\nsqDiff = diff.^2;\nsim = exp(-sum(sqDiff)/(2*sigma*sigma));\n\n\n\n\n% =============================================================\n \nend\n", "meta": {"author": "AvaisP", "repo": "machine-learning-programming-assignments-coursera-andrew-ng", "sha": "45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf", "save_path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng", "path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng/machine-learning-programming-assignments-coursera-andrew-ng-45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf/machine-learning-ex6/ex6/gaussianKernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9648551546097941, "lm_q2_score": 0.9314625069680097, "lm_q1q2_score": 0.8987264011738454}} {"text": "%EoM_Single_Pendulum.m\n\n% This script derives the equations of motion for a single pendulum using\n% the lagrange equations and the matlab symbolic toolbox.\n\n% Model: Single Pendulum, with a point mass bob. Theta is measured from the\n% -j axis. Gravity points in the -j direction. The pendulum is a fixed\n% length, and there is no friction.\n\n% The lagrangian (L) is defined as:\n% \n% L = T - U\n%\n% where \n% T = system's kinetic energy\n% U = system's potential energy\n\n% How we go about expressing the equations of motion:\n%\n% dL d / dL \\ * Note that some of those 'd' should be\n% --- = -- | -- | curvy 'd' to represent partial\n% dth dt \\ dw / derivatives\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% set up variables %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nsyms th w a 'real'; \n% th == angle from -j axis\n% w == angular rate w = d(th)/dt\n% a == angular acceleration a = d(w)/dt\n\n% Note that in the standard notation we would have:\n% th == \"q\" -- generalized coordinate\n% w == \"q dot\"\n% a == \"q double dot\"\n\nsyms m g l 'real';\n% m == (point) mass of the pendulum bob\n% g == acceleration due to gravity\n% l == length of the pendulum\n\nT = (1/2)*m*(l^2)*(w^2); % kinetic energy of the pendulum\nU = m*g*l*(1-cos(th)); % potential energy of the pendulum\nL = T - U; % lagrangian\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% evaluate partial derivatives %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n% dL \n% dL_dth == --- Note that 'd' is partial derivative here \n% dth\n%\ndL_dth = jacobian(L,th);\n\n% dL \n% dL_dw == --- Note that 'd' is partial derivative here \n% dw\n%\ndL_dw = jacobian(L,w);\n\n% d / dL \\ * Note that some of those 'd' should be\n% ddL_dtdw == -- | -- | curvy 'd' to represent partial\n% dt \\ dw / derivatives\n%\n% Note the application of the chain rule:\n%\nddL_dtdw = jacobian(dL_dw,[th, w]) * [w, a]';\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% solve equations and write files %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n% Equations of motion:\neqn = ddL_dtdw - dL_dth;\n\n% Solve for acceleration:\nsoln = solve(eqn,a);\n\n% Write dynamics function:\nfilename = 'singlePendulumDynamics.m';\nmatlabFunction(soln,'file',filename,'vars',{th,g,l},'output',{'ddth'});\n\n% Write energy function:\nfilename = 'singlePendulumEnergy.m';\ntotalEnergy = T+U;\nenergy = [totalEnergy;T;U];\nmatlabFunction(totalEnergy,T,U,'file',filename,'vars',{th,w,m,g,l},'output',{'energy','kinetic','potential'});\n\n\n\n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/LagrangeMechanics/singlePendulum/EoM_Single_Pendulum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971992481016635, "lm_q2_score": 0.9241418158002492, "lm_q1q2_score": 0.8982588963509024}} {"text": "function number = comp_enum ( n, k )\n\n%*****************************************************************************80\n%\n%% COMP_ENUM returns the number of compositions of the integer N into K parts.\n%\n% Discussion:\n%\n% A composition of the integer N into K parts is an ordered sequence\n% of K nonnegative integers which sum to N. The compositions (1,2,1)\n% and (1,1,2) are considered to be distinct.\n%\n% The 28 compositions of 6 into three parts are:\n%\n% 6 0 0, 5 1 0, 5 0 1, 4 2 0, 4 1 1, 4 0 2,\n% 3 3 0, 3 2 1, 3 1 2, 3 0 3, 2 4 0, 2 3 1,\n% 2 2 2, 2 1 3, 2 0 4, 1 5 0, 1 4 1, 1 3 2,\n% 1 2 3, 1 1 4, 1 0 5, 0 6 0, 0 5 1, 0 4 2,\n% 0 3 3, 0 2 4, 0 1 5, 0 0 6.\n%\n% The formula for the number of compositions of N into K parts is\n%\n% Number = ( N + K - 1 )! / ( N! * ( K - 1 )! )\n%\n% Describe the composition using N '1's and K-1 dividing lines '|'.\n% The number of distinct permutations of these symbols is the number\n% of compositions. This is equal to the number of permutations of\n% N+K-1 things, with N identical of one kind and K-1 identical of another.\n%\n% Thus, for the above example, we have:\n%\n% Number = ( 6 + 3 - 1 )! / ( 6! * (3-1)! ) = 28\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 December 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Albert Nijenhuis, Herbert Wilf,\n% Combinatorial Algorithms for Computers and Calculators,\n% Second Edition,\n% Academic Press, 1978,\n% ISBN: 0-12-519260-6,\n% LC: QA164.N54.\n%\n% Parameters:\n%\n% Input, integer N, the integer whose compositions are desired.\n%\n% Input, integer K, the number of parts in the composition.\n%\n% Output, integer NUMBER, the number of compositions of N\n% into K parts.\n%\n number = i4_choose ( n + k - 1, n );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/legendre_product_polynomial/comp_enum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951711746926, "lm_q2_score": 0.934395157060208, "lm_q1q2_score": 0.8979086256250446}} {"text": "function sim = gaussianKernel(x1, x2, sigma)\n%RBFKERNEL returns a radial basis function kernel between x1 and x2\n% sim = gaussianKernel(x1, x2) returns a gaussian kernel between x1 and x2\n% and returns the value in sim\n\n% Ensure that x1 and x2 are column vectors\nx1 = x1(:); x2 = x2(:);\n\n% You need to return the following variables correctly.\nsim = 0;\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Fill in this function to return the similarity between x1\n% and x2 computed using a Gaussian kernel with bandwidth\n% sigma\n%\n%\n\nsim = exp(-sumsq(x1 - x2) / (2 * sigma^2));\n\n% =============================================================\n\nend\n", "meta": {"author": "zsiciarz", "repo": "ml-coursera", "sha": "54208ee72b88f1dc3c9235e644a47f618b80441c", "save_path": "github-repos/MATLAB/zsiciarz-ml-coursera", "path": "github-repos/MATLAB/zsiciarz-ml-coursera/ml-coursera-54208ee72b88f1dc3c9235e644a47f618b80441c/octave/mlclass-ex6/gaussianKernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9669140216112958, "lm_q2_score": 0.9273632871148287, "lm_q1q2_score": 0.8966805654388699}} {"text": "%DEMGAUSS Demonstrate sampling from Gaussian distributions.\n%\n%\tDescription\n%\n%\tDEMGAUSS provides a simple illustration of the generation of data\n%\tfrom Gaussian distributions. It first samples from a one-dimensional\n%\tdistribution using RANDN, and then plots a normalized histogram\n%\testimate of the distribution using HISTP together with the true\n%\tdensity calculated using GAUSS.\n%\n%\tDEMGAUSS then demonstrates sampling from a Gaussian distribution in\n%\ttwo dimensions. It creates a mean vector and a covariance matrix, and\n%\tthen plots contours of constant density using the function GAUSS. A\n%\tsample of points drawn from this distribution, obtained using the\n%\tfunction GSAMP, is then superimposed on the contours.\n%\n%\tSee also\n%\tGAUSS, GSAMP, HISTP\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\nclc\nmean = 2; var = 5; nsamp = 3000;\nxmin = -10; xmax = 10; nbins = 30;\ndisp('Demonstration of sampling from a uni-variate Gaussian with mean')\ndstring = [num2str(mean), ' and variance ', num2str(var), '. ', ...\n num2str(nsamp), ' samples are taken.'];\ndisp(dstring);\nx = mean + sqrt(var)*randn(nsamp, 1);\nfh1 = figure;\nhistp(x, xmin, xmax, nbins);\nhold on;\naxis([xmin xmax 0 0.2]);\nplotvals = linspace(xmin, xmax, 200)';\nprobs = gauss(mean, var, plotvals);\nplot(plotvals, probs, '-r');\nxlabel('X')\nylabel('Density')\n\ndisp(' ')\ndisp('Press any key to continue')\npause; \nmu = [3 2];\nlam1 = 0.5;\nlam2 = 5.0;\nSigma = lam1*[1,1]'*[1,1] + lam2*[1,-1]'*[1,-1];\ndisp(' ')\ndisp('Demonstration of sampling from a bi-variate Gaussian. The mean is')\ndstring = ['[', num2str(mu(1)), ', ', num2str(mu(2)), ...\n '] and the covariance matrix is'];\ndisp(dstring)\ndisp(Sigma);\nngrid = 40;\ncmin = -5; cmax = 10; \ncvals = linspace(cmin, cmax, ngrid);\n[X1, X2] = meshgrid(cvals, cvals);\nXX = [X1(:), X2(:)];\nprobs = gauss(mu, Sigma, XX);\nprobs = reshape(probs, ngrid, ngrid);\n\nfh2 = figure;\ncontour(X1, X2, probs, 'b');\nhold on\n\nnsamp = 300;\ndstring = [num2str(nsamp), ' samples are generated.'];\ndisp('The plot shows the sampled data points with a contour plot of their density.')\nsamples = gsamp(mu, Sigma, nsamp);\nplot(samples(:,1), samples(:,2), 'or');\nxlabel('X1')\nylabel('X2')\ngrid off;\n\ndisp(' ')\ndisp('Press any key to end')\npause; \nclose(fh1);\nclose(fh2);\nclear all; ", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/netlab3.3/demgauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361157495521, "lm_q2_score": 0.9324533036984185, "lm_q1q2_score": 0.8954919340503358}} {"text": "function pdf = normal_pdf ( x, a, b )\n\n%*****************************************************************************80\n%\n%% NORMAL_PDF evaluates the Normal PDF.\n%\n% Discussion:\n%\n% The normal PDF is also known as the Gaussian PDF.\n%\n% Formula:\n%\n% PDF(X)(A,B) = EXP ( - 0.5 * ( ( X - A ) / B )^2 ) / SQRT ( 2 * PI * B^2 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X(), the argument of the PDF.\n%\n% Input, real A, a parameter of the PDF.\n% A represents the mean value of the variables.\n%\n% Input, real B, a parameter of the PDF.\n% B represents the standard deviation of the variables.\n%\n% Output, real PDF(), the value of the PDF.\n%\n pdf = exp ( - 0.5 * ( ( x - a ) / b ).^2 ) / sqrt ( 2.0 * pi * b^2 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/normal_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9688561721629776, "lm_q2_score": 0.924141826246517, "lm_q1q2_score": 0.8953605123129039}} {"text": "% gauss2d() - generate a 2-dimensional gaussian matrix\n%\n% Usage:\n% >> [ gaussmatrix ] = gauss2d( rows, columns, ...\n% sigmaR, sigmaC, peakR, peakC, mask)\n%\n% Example:\n% >> imagesc(gauss2d(50, 50)); % image a size (50,50) 2-D gaussian matrix\n%\n% Inputs:\n% rows - number of rows in matrix\n% columns - number of columns in matrix\n% sigmaR - width of standard deviation in rows (default: rows/5)\n% sigmaC - width of standard deviation in columns (default: columns/5)\n% peakR - location of the peak in each row (default: rows/2)\n% peakC - location of the peak in each column (default: columns/2)\n% mask - (0->1) portion of the matrix to mask with zeros (default: 0)\n%\n% Ouput:\n% gaussmatrix - 2-D gaussian matrix\n%\n% Author: Arnaud Delorme, CNL/Salk Institute, 2001\n\n% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\nfunction mat = gauss2d( sizeX, sizeY, sigmaX, sigmaY, meanX, meanY, cut);\n\nif nargin < 2\n\thelp gauss2d\n\treturn; \nend;\nif nargin < 3\n\tsigmaX = sizeX/5;\nend;\nif nargin < 4\n\tsigmaY = sizeY/5;\nend;\nif nargin < 5\n\tmeanX = (sizeX+1)/2;\nend;\nif nargin < 6\n\tmeanY = (sizeY+1)/2;\nend;\nif nargin < 7\n\tcut = 0;\nend;\n\nX = linspace(1, sizeX, sizeX)'* ones(1,sizeY);\nY = ones(1,sizeX)' \t\t * linspace(1, sizeY, sizeY);\n%[-sizeX/2:sizeX/2]'*ones(1,sizeX+1);\n%Y = ones(1,sizeY+1)' *[-sizeY/2:sizeY/2];\n\nmat = exp(-0.5*( ((X-meanX)/sigmaX).*((X-meanX)/sigmaX)...\n\t\t\t\t+((Y-meanY)/sigmaY).*((Y-meanY)/sigmaY)))... \n \t\t\t/((sigmaX*sigmaY)^(0.5)*pi); \n\nif cut > 0\n\tmaximun = max(max(mat))*cut;\n\tI = find(mat < maximun);\n\tmat(I) = 0;\nend;\n\nreturn;\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/miscfunc/gauss2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611643025387, "lm_q2_score": 0.9314625098218848, "lm_q1q2_score": 0.8945404204367102}} {"text": "clear; close all; clc;\n\n%% 1. Create a CSV file to contain the data\n\nmy_mtx = [0,0; 3, 1.4; 6, 2.5; 9 3.1; 12 3.2; 15 1.7; 18 0];\n\nwritematrix(my_mtx, 'my_file.csv')\n\n%%%%%%%%%%% 2. Produce a MATLAB script and functions to do the following %%%%%%%%%%%\n\n%% a. Read the CSV file\n\nA = xlsread('my_file.csv');\n\n%% b. Plot the depth of the calanal along the cross-section\nplot(my_mtx(:,1), my_mtx(:,2));\naxis ij % this command will let the figure plot reverse the y-dir so that the graph can represent the \"DEPTH\" of canal.\n\n%% c. Numerically estimate the average depth of the canal using different methods and implementations\n\n%% i. Your own implementation ofh te trapezium method, using a loop to\n% iterate over the measurement data\n\ntotal_depth_trapz = 0;\nx = my_mtx(:,1);\nfx = my_mtx(:,2); \n\nfor i = 1:length(x)-1\n total_depth_trapz = total_depth_trapz + (x(i+1)-x(i))*(fx(i+1)+fx(i))/2;\nend\n% ref: https://en.wikipedia.org/wiki/Trapezoidal_rule\n\n%% ii. Your own implementation of the Simpson's Rule, using a loop to\n% iterate over the measurement data\n\n% coef of Simpson's rule\n% ref: https://www.math24.net/simpsons-rule/#example1\ncoef = ones(1, length(x));\ncoef(2:2:end-1) = 4;\ncoef(3:2:end-2) = 2;\n\ndelta_x = x(2)-x(1);\ntotal_depth_Simpson = 0;\nfor i = 1:length(x)\n total_depth_Simpson = total_depth_Simpson + delta_x/3*coef(i)*fx(i);\nend\n\n%% iii. Your own implementation of Simpson's rule, avoiding the use of a loop by using\n% operations on vectors\n\ntotal_depth_Simpson_vec = delta_x/3*(coef*fx); % vectorized summation using inner product\n\n%% iv. MATLAB's built-in trapz() function\ntotal_depth_MATLAB_trapz = trapz(x, fx);\n", "meta": {"author": "angeloyeo", "repo": "gongdols", "sha": "7be9fbd988dec6edab1dc881cb22d63e6f69398d", "save_path": "github-repos/MATLAB/angeloyeo-gongdols", "path": "github-repos/MATLAB/angeloyeo-gongdols/gongdols-7be9fbd988dec6edab1dc881cb22d63e6f69398d/MATLAB강의/최현준님질문/main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158416, "lm_q2_score": 0.952574121941844, "lm_q1q2_score": 0.8944907376927437}} {"text": "% CORRCOEF Correlation coefficients.\n% R=CORRCOEF(X) calculates a matrix R of correlation coefficients for\n% an array X, in which each row is an observation and each column is a\n% variable.\n% \n% R=CORRCOEF(X,Y), where X and Y are column vectors, is the same as\n% R=CORRCOEF([X Y]). CORRCOEF converts X and Y to column vectors if they\n% are not, i.e., R=CORRCOEF(X,Y) is equivalent to R=CORRCOEF([X(:) Y(:)])\n% in that case.\n% \n% If C is the covariance matrix, C = COV(X), then CORRCOEF(X) is\n% the matrix whose (i,j)'th element is\n% \n% C(i,j)/SQRT(C(i,i)*C(j,j)).\n% \n% [R,P]=CORRCOEF(...) also returns P, a matrix of p-values for testing\n% the hypothesis of no correlation. Each p-value is the probability\n% of getting a correlation as large as the observed value by random\n% chance, when the true correlation is zero. If P(i,j) is small, say\n% less than 0.05, then the correlation R(i,j) is significant.\n% \n% [R,P,RLO,RUP]=CORRCOEF(...) also returns matrices RLO and RUP, of\n% the same size as R, containing lower and upper bounds for a 95%\n% confidence interval for each coefficient.\n% \n% [...]=CORRCOEF(...,'PARAM1',VAL1,'PARAM2',VAL2,...) specifies additional\n% parameters and their values. Valid parameters are the following:\n% \n% Parameter Value\n% 'Alpha' A number between 0 and 1 to specify a confidence\n% level of 100*(1-ALPHA)%. Default is 0.05 for 95%\n% confidence intervals.\n% 'Rows' Either 'all' (default) to use all rows, 'complete' to\n% use rows with no NaN values, or 'pairwise' to compute\n% R(i,j) using rows with no NaN values in column i or j.\n% The 'pairwise' option potentially uses different sets\n% of rows to compute different elements of R, and can\n% produce a matrix that is indefinite.\n% \n% The p-value is computed by transforming the correlation to create a t\n% statistic having N-2 degrees of freedom, where N is the number of rows\n% of X. The confidence bounds are based on an asymptotic normal\n% distribution of 0.5*log((1+R)/(1-R)), with an approximate variance equal\n% to 1/(N-3). These bounds are accurate for large samples when X has a\n% multivariate normal distribution.\n% \n% Example: Generate random data having correlation between column 4\n% and the other columns.\n% x = randn(30,4); % uncorrelated data\n% x(:,4) = sum(x,2); % introduce correlation\n% [r,p] = corrcoef(x) % compute sample correlation and p-values\n% [i,j] = find(p<0.05); % find significant correlations\n% [i,j] % display their (row,col) indices\n% \n% Class support for inputs X,Y:\n% float: double, single\n% \n% See also COV, VAR, STD, PLOTMATRIX.\n%\n% Reference page in Doc Center\n% doc corrcoef\n%\n% Other functions named corrcoef\n%\n% codistributed/corrcoef gpuArray/corrcoef ts/corrcoef\n% fints/corrcoef\n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/classes/time_series/@ts/corrcoef.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811601648193, "lm_q2_score": 0.9263037369059444, "lm_q1q2_score": 0.8942361761992682}} {"text": "function y=expSlope1(x)\n%%EXPSLOPE1 Evaluate the function (exp(x)-1)/x avoiding problems at the\n% point x=0, where the limit equals 1. This function arises in\n% range enclosure algorithms for interval arithmetic.\n%\n%INPUTS: x A vector of matrix of real values at which the function should\n% be evaluated.\n%\n%OUTPUTS: y The value(s) of the function (exp(x)-1)/x at the point(s) in x.\n%\n%For values of x below 0.1, a Taylor series expansion about x=0 is used.\n%For values of x above 0.1, the function is implemented as in Chapter\n%1.14.1 of [2]. Though the method in [2] can go to lower values of x, it\n%still has a singularity at x=0. The Taylor series does not.\n%\n%This is one of the slope function in Table 10.6 of Section 10.6.2 of [1].\n%\n%REFERENCES:\n%[1] IEEE Standard for Interval Arithmetic,\" in IEEE Std 1788-2015,\n% pp.1-97, June 30 2015.\n%[2] N. J. Higham, Accuracy and Stability of Numerical Algorithms.\n% Philadelphia: SIAM, 1996.\n%\n%November 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\ny=zeros(size(x));\n\nselSmall=x<0.1;\nxSmall=x(selSmall);\nxLarge=x(~selSmall);\n\nif(~isempty(xSmall))\n %Use a Taylor-series approximation about x=0. THis avoud the\n %singularity. \n expanOrder=20;\n ySmall=ones(size(xSmall));\n\n xPow=xSmall;\n kFactorial=1;\n for k=1:expanOrder\n kFactorial=kFactorial*k;\n\n ySmall=ySmall+xPow/((k+1)*kFactorial);\n\n xPow=xPow.*xSmall;\n end\nelse\n ySmall=[];\nend\n\nif(~isempty(xLarge))\n yLarge=exp(xLarge);\n yLarge=(yLarge-1)/log(yLarge);\nelse\n yLarge=[];\nend\n\ny(selSmall)=ySmall;\ny(~selSmall)=yLarge;\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Slope_Functions/expSlope1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928905, "lm_q2_score": 0.9390248165754385, "lm_q1q2_score": 0.8931461486659793}} {"text": "function [P,N,check]=plane_intersect(N1,A1,N2,A2)\n%plane_intersect computes the intersection of two planes(if any)\n% Inputs: \n% N1: normal vector to Plane 1\n% A1: any point that belongs to Plane 1\n% N2: normal vector to Plane 2\n% A2: any point that belongs to Plane 2\n%\n%Outputs:\n% P is a point that lies on the interection straight line.\n% N is the direction vector of the straight line\n% check is an integer (0:Plane 1 and Plane 2 are parallel' \n% 1:Plane 1 and Plane 2 coincide\n% 2:Plane 1 and Plane 2 intersect)\n%\n% Example:\n% Determine the intersection of these two planes:\n% 2x - 5y + 3z = 12 and 3x + 4y - 3z = 6\n% The first plane is represented by the normal vector N1=[2 -5 3]\n% and any arbitrary point that lies on the plane, ex: A1=[0 0 4]\n% The second plane is represented by the normal vector N2=[3 4 -3]\n% and any arbitrary point that lies on the plane, ex: A2=[0 0 -2]\n%[P,N,check]=plane_intersect([2 -5 3],[0 0 4],[3 4 -3],[0 0 -2]);\n\n%This function is written by :\n% Nassim Khaled\n% Wayne State University\n% Research Assistant and Phd candidate\n%If you have any comments or face any problems, please feel free to leave\n%your comments and i will try to reply to you as fast as possible.\nP=[0 0 0];\nN=cross(N1,N2);\n\n% test if the two planes are parallel\nif norm(N) < 10^-7 % Plane 1 and Plane 2 are near parallel\n V=A1-A2;\n if (dot(N1,V) == 0) \n check=1; % Plane 1 and Plane 2 coincide\n return\n else \n check=0; %Plane 1 and Plane 2 are disjoint\n return\n end\nend\n \n check=2;\n \n% Plane 1 and Plane 2 intersect in a line\n%first determine max abs coordinate of cross product\nmaxc=find(abs(N)==max(abs(N)));\n\n\n%next, to get a point on the intersection line and\n%zero the max coord, and solve for the other two\n \nd1 = -dot(N1,A1); %the constants in the Plane 1 equations\nd2 = -dot(N2, A2); %the constants in the Plane 2 equations\n\nswitch maxc\n case 1 % intersect with x=0\n P(1)= 0;\n P(2) = (d2*N1(3) - d1*N2(3))/ N(1);\n P(3) = (d1*N2(2) - d2*N1(2))/ N(1);\n case 2 %intersect with y=0\n P(1) = (d1*N2(3) - d2*N1(3))/ N(2);\n P(2) = 0;\n P(3) = (d2*N1(1) - d1*N2(1))/ N(2);\n case 3 %intersect with z=0\n P(1) = (d2*N1(2) - d1*N2(2))/ N(3);\n P(2) = (d1*N2(1) - d2*N1(1))/ N(3);\n P(3) = 0;\nend\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/17618-plane-intersection/plane_intersect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104962847372, "lm_q2_score": 0.9241418246795768, "lm_q1q2_score": 0.8931003594260725}} {"text": "function [B,Lambda,CLS,exitCode]=jointMatDiagLS(A,w,maxIter,CLSTol,RelTol,AbsTol)\n%%JOINTMATDIAGLS Given K real or complex Hermitian or symmetric matrices in\n% A, try to find a common diagonalizing matrix B and sets of\n% values Lambda such that A(:,:,k)=B*diag(Lambda(:,k))*B' for\n% all k. An exact solution is only guaranteed for positive\n% (semi-)definite matrices with K=2. However, for general\n% problems the B and Lambda values are chosen trying to\n% minimize the least squares cost function\n% CLS=\\sum_{k=1}^K w(k)*norm(A_k-B*diag(lambda_k)*B','fro')^2 \n% when the matrices A are Hermitian, lambda_k is an NX1 vector\n% and \n% CLS=\\sum_{k=1}^K w(k)*norm(A_k-B*diag(lambda_k)*B.','fro')^2\n% when the matrices A re symmetric. Real matrices count as\n% Hermitian; one cannot mix Hermitian and Symmetric complex\n% matrices in a single A.\n%\n%INPUTS: A An NXNXK set of K NXN Hermitian or symmetric matrices. This\n% cannot contain Inf or NaN values.\n% w An optional set of positive that go into the cost function.\n% These do not need to sum to any particular value. The default if\n% omitted or an empty matrix is passed is ones(K,1).\n% maxIter The maximum number of iterations to perform. The default if\n% omitted or an empty matrix is passed is 10000.\n% CLSTol If the least squares cost is <= this threshold, then the\n% algorithm will terminate early. This value is checked every 10\n% iterations. The default if omitted or an empty matrix is passed\n% is 1e-6.\n% RelTol, AbsTol Absolute and relative tolerances on the parameters being\n% estimated. let theta=[B(:);Lambda(:)] and thetaPrev the estimate\n% from the previous step. Say that diff=abs(theta-thetaPrev).\n% Convergence is declared if\n% all((diff<=AbsTol)|diff<=RelTol*abs(theta))\n% The default values if omitted or empty matrices are passed are\n% 1e-9 and 1e-12.\n%\n%OUTPUTS: B The NXN matrix that approximately turns the Lambda values into\n% A. These are the diagonalizer values. B is generally not\n% an orthonormal matrix.\n% Lambda The NXK set of the diagonals of the K diagonal matrices.\n% CLS The value of the cost function on termination.\n% exitCode A parameter indicating how the function terminated. Possible\n% values are:\n% -1 The RelTol and/or AbsTol criteria were satisfied.\n% 0 The CLSTol criterion was satisfied.\n% 1 The maximum number of iterations was reached.\n%\n%This function implements the algorithm of [1]. Though exact solutions are\n%possible for pairs of positive semidefinite matrices, note that\n%convergence is often faster for pairs of positive definite matrices than\n%for pairs of positive semidefinite matrices, particularly when the\n%matrices are complex.\n%\n%EXAMPLE 1:\n%Here, we show that we can obtain an exact solution for a pair of positive\n%definite real, symmetric (Hermitian) matrices where one is positive\n%semi-definite.\n% C1=[57, 7, 12, 17;\n% 7, 47, 17, 22;\n% 12, 17, 37, 27;\n% 17, 22, 27, 27];\n% [V,D,U] = svd(C1);\n% D(2,2)=0;%Make uninformative.\n% D(3,3)=0;%Make uninformative.\n% C1=V*D*U';\n% C2=[87, 25, 18, 31;\n% 25, 63, 20, 17;\n% 18, 20, 65, 29;\n% 31, 17, 29, 65];\n% A=zeros(4,4,2);\n% A(:,:,1)=C1;\n% A(:,:,2)=C2;\n% [B,Lambda,CLS,exitCode]=jointMatDiagLS(A)\n% %The CLS is verified as:\n% CLSCheck=norm(A(:,:,1)-B*diag(Lambda(:,1))*B','fro')^2+norm(A(:,:,2)-B*diag(Lambda(:,2))*B','fro')^2\n%One will see that convergence is by the CLS bound.\n%\n%EXAMPLE 2:\n%Here, we have two positive definite complex Hermitian matrices. Again, an\n%exact solution is found rapidly. If the additive identity matrices to C1\n%and C2 are removed, then the matrices are no longer positive definite and\n%only a least-squares approximation can be found. In such an instance, the\n%algorithm is much slower.\n% C1=[ 9+ 0*1i, -65+ 0*1i, -11-153*1i, -91-173*1i;\n% -65+ 0*1i, 83+ 0*1i, 54- 38*1i, 31+ 28*1i;\n% -11+153*1i, 54+ 38*1i, 130+ 0*1i, 16- 47*1i;\n% -91+173*1i, 31- 28*1i, 16+ 47*1i, 22+ 0*1i]+215*eye(4);\n% \n% C2=[-16+ 0*1i, -32- 56*1i, -12-128*1i, 16+114*1i;\n% -32+ 56*1i, 79+ 0*1i, -87- 67*1i, -48+ 51*1i;\n% -12+128*1i, -87+ 67*1i, 76+ 0*1i, -7- 96*1i;\n% 16-114*1i, -48- 51*1i, -7+ 96*1i, -147+ 0*1i]+259*eye(4);\n% A=zeros(4,4,2);\n% A(:,:,1)=C1;\n% A(:,:,2)=C2;\n% [B,Lambda,CLS,exitCode]=jointMatDiagLS(A)\n% %The CLS is verified as:\n% CLSCheck=norm(A(:,:,1)-B*diag(Lambda(:,1))*B','fro')^2+norm(A(:,:,2)-B*diag(Lambda(:,2))*B','fro')^2\n%Again, convergence is due to satisfying the cost function criterion.\n%\n%EXAMPLE 3:\n%Though only approximations can be obtained for more than two matrices in\n%general, here we show that if three matrices originate from a common set\n%of basis vectors, then this function will find the correct\n%diagonalization.\n% [V,D]=eig(magic(4));\n% C1=V*D*V';\n% C2=V*diag([1;2;3;5])*V';\n% C3=V*diag([12;1;0;8])*V';\n% A=zeros(4,4,3);\n% A(:,:,1)=C1;\n% A(:,:,2)=C2;\n% A(:,:,3)=C3;\n% [B,Lambda,CLS,exitCode]=jointMatDiagLS(A)\n%Convergence of the cost function is quickly achieved for the three\n%matrices. Note, however, that B is not the same as V.\n%\n%REFERENCES:\n%[1] A. Yeredor, \"Non-orthogonal joint diagonalization in the least-squares\n% sense with application in blind source separation,\" IEEE Transactions\n% on Signal Processing, vol. 50, no. 7, pp. 1545-1553, Jul. 2002.\n%\n%July 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n K=size(A,3);\n N=size(A,1);\n\n if(nargin<6||isempty(AbsTol))\n AbsTol=1e-12;\n end\n \n if(nargin<5||isempty(RelTol))\n RelTol=1e-9;\n end\n\n if(nargin<4||isempty(CLSTol))\n CLSTol=1e-6;\n end\n \n if(nargin<3||isempty(maxIter))\n maxIter=10000;\n end\n\n if(nargin<2||isempty(w))\n w=ones(K,1);\n end\n\n %Check whether all (assume symmetric) matrices are Hermitian. If so,\n %then a different algorithm can be used.\n isHermitian=true;\n if(~isreal(A))\n for k=1:K\n if(any(any(A(:,:,k)~=A(:,:,k)')))\n isHermitian=false;\n break;\n end\n end\n end\n\n w=w(:);\n\n %Initial values. This doesn't necessarily help speed up the\n %convergence, but it will work even if the matrices in A are singular.\n B=eye(N,N);\n Lambda=ones(N,K);\n\n exitCode=1;\n if(isHermitian)\n for curIter=1:maxIter\n thetaPrev=[B(:);Lambda(:)];\n \n for iter=1:4\n for l=1:N\n B=ACPhase(A,Lambda,w,B,l);\n end\n end\n Lambda=DCPhase(A,B);\n\n %Check for convergence.\n if(mod(curIter,10))\n %Cost criterion.\n CLS=0;\n for k=1:K\n CLS=CLS+w(k)*norm(A(:,:,k)-B*diag(Lambda(:,k))*B','fro')^2;\n end\n if(CLS<=CLSTol)\n exitCode=0;\n return;\n end\n \n %Parameter change criterion.\n theta=[B(:);Lambda(:)];\n \n diff=abs(theta-thetaPrev);\n if(all((diff<=AbsTol)|diff<=RelTol*abs(theta)))\n exitCode=-1;\n break;\n end\n end\n end\n else%Assume it is symmetric, not Hermitian.\n for curIter=1:maxIter\n thetaPrev=[B(:);Lambda(:)];\n \n for iter=1:4\n for l=1:N\n B=ACPhaseSym(A,Lambda,w,B,l);\n end\n end\n Lambda=DCPhaseSym(A,B);\n\n %Check for convergence.\n if(mod(curIter,10))\n %Cost criterion.\n CLS=0;\n for k=1:K\n CLS=CLS+w(k)*norm(A(:,:,k)-B*diag(Lambda(:,k))*B.','fro')^2;\n end\n if(CLS<=CLSTol)\n exitCode=0;\n return;\n end\n \n %Parameter change criterion.\n theta=[B(:);Lambda(:)];\n \n diff=abs(theta-thetaPrev);\n if(all((diff<=AbsTol)|diff<=RelTol*abs(theta)))\n exigtCode=-1;\n break;\n end\n end\n end\n end\n\n %If the algorithm did not convergence, compute the current CLS if it should\n %be returned.\n if(nargout>2)\n CLS=0;\n if(isHermitian)\n for k=1:K\n CLS=CLS+w(k)*norm(A(:,:,k)-B*diag(Lambda(:,k))*B','fro')^2;\n end\n else\n for k=1:K\n CLS=CLS+w(k)*norm(A(:,:,k)-B*diag(Lambda(:,k))*B.','fro')^2;\n end\n end\n end\nend\n\nfunction B=ACPhase(A,Lambda,w,B,l)\n\n N=size(A,1);\n K=size(A,3);\n\n %Step 1\n P=zeros(N,N);\n for k=1:K\n innerSum=B*diag(Lambda(:,k))*B'-Lambda(l,k)*(B(:,l)*B(:,l)');\n\n P=P+w(k)*Lambda(l,k)*(A(:,:,k)-innerSum);\n end\n\n %Step 2\n [V,D]=eig(P);\n d=diag(D);\n [~,idx]=max(d);\n mu=d(idx);\n betaVec=V(:,idx);\n\n %The paper suggests using the first nonzero index of betaVec. We just\n %use the index having the largest magnitude value. in it.\n [~,nonZeroIdx]=max(abs(betaVec));\n\n %Force the first nonzero element of the unit eigenvector to be real and\n %positive.\n if(isreal(betaVec))\n if(betaVec(nonZeroIdx)<0)\n betaVec=-betaVec;\n end\n else\n betaVec=exp(-angle(betaVec(nonZeroIdx))*1i)*betaVec;\n %betaVec(nonZeroIdx) should be real and positive, but this line\n %deals avoids any possible finite precision issues.\n betaVec(nonZeroIdx)=abs(betaVec(nonZeroIdx));\n end\n\n if(mu<0)\n B(:,l)=zeros(N,1);\n else\n B(:,l)=betaVec*sqrt(mu)/sqrt(sum(w.*(Lambda(l,:).^2).'));\n end\nend\n\nfunction Lambda=DCPhase(A,B)\n\n N=size(A,1);\n K=size(A,3);\n\n %Step 1\n prodVal=B'*B;\n prodVal=conj(prodVal).*prodVal;\n %Use a pseudoinverse for poorly conditioned problems.\n if(rcond(prodVal)<=1e-14)\n G=pinv(prodVal);\n else\n G=inv(prodVal);\n end\n\n %Step 2\n Lambda=zeros(N,K);\n for k=1:K\n Lambda(:,k)=G*diag(B'*A(:,:,k)*B);\n end\nend\n\nfunction B=ACPhaseSym(A,Lambda,w,B,l)\n\n N=size(A,1);\n K=size(A,3);\n\n %Step 1\n P=zeros(N,N);\n for k=1:K\n innerSum=A(:,:,k);\n for n=1:N\n if(n~=l)\n innerSum=innerSum-Lambda(n,k)*(B(:,n)*B(:,n).');\n end\n end\n\n P=P+w(k)*Lambda(l,k)*conj(innerSum);\n end\n\n %Step 2\n [V,D]=eig([real(P), -imag(P);\n -imag(P), -real(P)]);\n\n %D should be real. This line is just in case some finite precision\n %issue in matlab makes it not real.\n D=real(D);\n \n d=diag(D);\n [~,idx]=max(d);\n mu=d(idx);\n xi=V(:,idx);\n\n %Step 3\n if(mu<0)\n B(:,l)=zeros(N,1);\n else\n gammaVal=xi(1:N);\n delta=xi((N+1):(2*N));\n\n B(:,l)=(gammaVal+1j*delta)*sqrt(mu)/sqrt(sum(w.*(abs(Lambda(l,:)).^2).'));\n end\nend\n\nfunction Lambda=DCPhaseSym(A,B)\n\n N=size(A,1);\n K=size(A,3);\n\n %Step 1\n prodVal=B'*B;\n prodVal=prodVal.*prodVal;\n %Use a pseudoinverse for poorly conditioned problems.\n if(rcond(prodVal)<=1e-14)\n G=pinv(prodVal);\n else\n G=inv(prodVal);\n end\n\n %Step 2\n Lambda=zeros(N,K);\n for k=1:K\n Lambda(:,k)=G*diag(B'*A(:,:,k)*conj(B));\n end\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Basic_Matrix_Operations/Joint_Matrix_Diagonalization/jointMatDiagLS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454896, "lm_q2_score": 0.9362850008588939, "lm_q1q2_score": 0.8912152691867162}} {"text": "function randOrthoMat=randOrthoMat(numDim)\n%RANDORTHOMAT Generate a random orthogonal matrix of the desired\n% dimensionality (with respect to the Haar distribution over\n% the orthogonal group --kind of a \"uniform\" distribution).\n% This means that the dot product of any two columns is zero.\n% The orthogonal matrices generated have determinants of +1 or\n% -1.\n%\n%INPUTS: numDim The scalar number of dimensions that the random orthogonal\n% matrix should have.\n%\n%OUTPUTS: randOrthoMat A numDimXnumDim random orthogonal matrix with a\n% determinant of either +1 or -1.\n%\n%As noted in [1], random orthogonal matrices can be obtained by first\n%gennerating a matrix of independent standard normal random variables, then\n%takign the QR decomposition of the matrix such that R has all positive\n%elements along the diagonal. However, since Matlab's QR command can\n%produce R matrices with negative diagonal elements, we have to effectively\n%transfer the sign of R onto Q to make the elements of the diagonal of R\n%all positive. This means multiplying Q by diag(sign(diag(R))).\n%\n%EXAMPLE:\n%We will plot the random directions in 2D on the unit circle to show that\n%this produces a relatively uniform set of rotation matrices.\n% numPoints=500;\n% figure(1)\n% clf\n% hold on\n% for curPoint=1:numPoints\n% thePoint=randOrthoMat(2)*[1;0];\n% scatter(thePoint(1),thePoint(2),'.k','linewidth',2)\n% end\n%\n%REFERENCE:\n%[1] G. W. Stewart, \"The efficient generation of random orthogonal matrices\n% with an application to condition estimators,\" SIAM Journal on\n% Numerical Analysis, vol. 17, no. 3, pp. 403-409, Jun. 1980.\n%\n%October 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nX=randn(numDim,numDim);\n[Q,R]=qr(X);\n\nrandOrthoMat=Q*diag(sign(diag(R)));\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/randOrthoMat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104924150547, "lm_q2_score": 0.9219218305645894, "lm_q1q2_score": 0.8909549302441135}} {"text": "function points = intersectCircles(circle1, circle2)\n%INTERSECTCIRCLES Intersection points of two circles.\n%\n% POINTS = intersectCircles(CIRCLE1, CIRCLE2)\n% Computes the intersetion point of the two circles CIRCLE1 and CIRCLE1.\n% Both circles are given with format: [XC YC R], with (XC,YC) being the\n% coordinates of the center and R being the radius.\n% POINTS is a 2-by-2 array, containing coordinate of an intersection\n% point on each row. \n% In the case of tangent circles, the intersection is returned twice. It\n% can be simplified by using the 'unique' function.\n%\n% Example\n% % intersection points of two distant circles\n% c1 = [0 0 10];\n% c2 = [10 0 10];\n% pts = intersectCircles(c1, c2)\n% pts =\n% 5 -8.6603\n% 5 8.6603\n%\n% % intersection points of two tangent circles\n% c1 = [0 0 10];\n% c2 = [20 0 10];\n% pts = intersectCircles(c1, c2)\n% pts =\n% 10 0\n% 10 0\n% pts2 = unique(pts, 'rows')\n% pts2 = \n% 10 0\n%\n% References\n% http://local.wasp.uwa.edu.au/~pbourke/geometry/2circle/\n% http://mathworld.wolfram.com/Circle-CircleIntersection.html\n%\n% See also \n% circles2d, intersectLineCircle, radicalAxis\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2011-01-20, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011-2022 INRA - Cepia Software Platform\n\n% adapt sizes of inputs\nn1 = size(circle1, 1);\nn2 = size(circle2, 1);\nif n1 ~= n2\n if n1 > 1 && n2 == 1\n circle2 = repmat(circle2, n1, 1);\n elseif n2 > 1 && n1 == 1\n circle1 = repmat(circle1, n2, 1);\n else \n error('Both input should have same number of rows');\n end\nend\n \n% extract center and radius of each circle\ncenter1 = circle1(:, 1:2);\ncenter2 = circle2(:, 1:2);\nr1 = circle1(:,3);\nr2 = circle2(:,3);\n\n% allocate memory for result\nnPoints = length(r1);\npoints = NaN * ones(2*nPoints, 2);\n\n% distance between circle centers\nd12 = distancePoints(center1, center2, 'diag');\n\n% get indices of circle couples with intersections\ninds = d12 >= abs(r1 - r2) & d12 <= (r1 + r2);\n\nif sum(inds) == 0\n return;\nend\n\n% angle of line from center1 to center2\nangle = angle2Points(center1(inds,:), center2(inds,:));\n\n% position of intermediate point, located at the intersection of the\n% radical axis with the line joining circle centers\nd1m = d12(inds) / 2 + (r1(inds).^2 - r2(inds).^2) ./ (2 * d12(inds));\ntmp = polarPoint(center1(inds, :), d1m, angle);\n\n% distance between intermediate point and each intersection point\nh = sqrt(r1(inds).^2 - d1m.^2);\n\n% indices of valid intersections\ninds2 = find(inds)*2;\ninds1 = inds2 - 1;\n\n% create intersection points\npoints(inds1, :) = polarPoint(tmp, h, angle - pi/2);\npoints(inds2, :) = polarPoint(tmp, h, angle + pi/2);\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom2d/intersectCircles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338068793908, "lm_q2_score": 0.9263037363973295, "lm_q1q2_score": 0.890672357984728}} {"text": "function val=numMPartitions(n,m,getUpToM)\n%%NUMMPARTITIONS Get the number of ways of partitioning the integer n into\n% m parts, where order does not matter (unlike compositions,\n% where order matters). That is the number of ways of\n% getting m nonzero integers that sum to n. The amount of\n% memory for this implementation is proportional to n*m and\n% thus the solution becomes slow for very large n and m\n% values.\n%\n%INPUTS: n The positive n>0 integer to be partitioned.\n% m The number of parts into which the integer is to be partitioned.\n% getUpToM This parameter changes what is returned. If false (the default\n% if omitted or an empty matrix is passed), the number of\n% ways of partitioning n into m parts is returned. If true, then\n% the total number of ways of partitioning n into m or fewer parts\n% is returned.\n%\n%OUTPUTS: val The number of ways of partitioning the integer n into m\n% parts or if getUpToM=true, then this is the total number of\n% ways of partitioning n into m or fewer parts.\n%\n%The counting method is based on the recurrence relation in Chapter 7.2.1.4\n%of [1]. The algorithm could be implemented to use less memory. However,\n%that would require shifting rows in a table up (to reuse memory) and would\n%make the code a lot more complicated.\n%\n%REFERENCES:\n%[1] D. E. Knuth, The Art of Computer Programming. Vol. 4, Fascicle 3:\n% Generating all Combinations and Partitions, Upper Saddle River, NJ:\n% Addison-Wesley, 2009.\n%\n%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(getUpToM))\n getUpToM=false;\nend\n\nP=eye(n+1,m+1);\nP(:,1+1)=1;\n\nfor curN=2:n\n for curK=1:min(curN,m)\n P(curN+1,curK+1)=P(curN-1+1,curK-1+1)+P(curN-curK+1,curK+1);\n end\nend\nif(getUpToM)\n val=sum(P(end,:));\nelse\n val=P(end,end);\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Combinatorics/numMPartitions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885303, "lm_q2_score": 0.9241418173671895, "lm_q1q2_score": 0.8885936038241826}} {"text": "%% COMPARISON OF CONVERGENCE RATE OF VARIOUS FINITE ELEMENT METHODS\n%\n% This example is to compare the rate of convergence of various finite\n% element approximation of the Poisson equation on the unit square:\n%\n% $$- \\Delta u = f \\; \\hbox{in } (0,1)^2$$\n%\n% for the Dirichlet boundary condition. Results holds for other boundary\n% conditions. \n\n%% Problem\nclear all; close all; clc;\n[node,elem] = squaremesh([0,1,0,1],0.25); \npde = sincosdata;\nbdFlag = setboundary(node,elem,'Dirichlet');\n% pde = sincosNeumanndata;\n% bdFlag = setboundary(node,elem,'Neumann');\noption.L0 = 2;\noption.maxIt = 5;\noption.printlevel = 1;\noption.plotflag = 0;\n\n%% P1 element \nerr = femPoisson(node,elem,pde,bdFlag,option);\n\n%%\n% The optimal rate of convergence of the H1-norm (1st order), L2-norm (2nd\n% order), and discrte maximum norm is observed. The 2nd order convergent\n% rate between two discrete functions ||DuI-Duh|| is known as\n% superconvergence.\n\n%% CR nonconforming P1 element\noption.elemType = 'CR';\nerr = femPoisson(node,elem,pde,bdFlag,option);\n\n%%\n% The optimal rate of convergence of the H1-norm (1st order), L2-norm (2nd\n% order), and discrte maximum norm is observed. But no superconvergence of\n% ||DuI-Duh||.\n\n%% P2 element\noption.elemType = 'P2';\nerr = femPoisson(node,elem,pde,bdFlag,option);\n\n%% P3 element\noption.elemType = 'P3';\nerr = femPoisson(node,elem,pde,bdFlag,option);\n\n%% Conclusion\n\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/example/femratecomparsion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561676667173, "lm_q2_score": 0.9161096147346158, "lm_q1q2_score": 0.8875784504944128}} {"text": "function fd_predator_prey ( p0, tspan, step_num )\n\n%*****************************************************************************80\n%\n%% FD_PREDATOR_PREY solves a pair of predator-prey ODE's.\n%\n% Discussion:\n%\n% The physical system under consideration is a pair of animal populations.\n%\n% The PREY reproduce rapidly; for each animal alive at the beginning of the\n% year, two more will be born by the end of the year. The prey do not have\n% a natural death rate; instead, they only die by being eaten by the predator.\n% Every prey animal has 1 chance in 1000 of being eaten in a given year by\n% a given predator.\n%\n% The PREDATORS only die of starvation, but this happens very quickly.\n% If unfed, a predator will tend to starve in about 1/10 of a year.\n% On the other hand, the predator reproduction rate is dependent on\n% eating prey, and the chances of this depend on the number of available prey.\n%\n% The resulting differential equations can be written:\n%\n% PREY(0) = 5000\n% PRED(0) = 100\n%\n% d PREY / dT = 2 * PREY(T) - 0.001 * PREY(T) * PRED(T)\n% d PRED / dT = - 10 * PRED(T) + 0.002 * PREY(T) * PRED(T)\n%\n% Here, the initial values (5000,100) are a somewhat arbitrary starting point.\n%\n% The pair of ordinary differential equations that result have an interesting\n% behavior. For certain choices of the interaction coefficients (such as\n% those given here), the populations of predator and prey will tend to\n% a periodic oscillation. The two populations will be out of phase; the number\n% of prey will rise, then after a delay, the predators will rise as the prey\n% begins to fall, causing the predator population to crash again.\n%\n% In this program, the pair of ODE's is solved with a simple finite difference\n% approximation using a fixed step size. In general, this is NOT an efficient\n% or reliable way of solving differential equations. However, this program is\n% intended to illustrate the ideas of finite difference approximation.\n%\n% In particular, if we choose a fixed time step size DT, then a derivative\n% such as dPREY/dT is approximated by:\n%\n% d PREY / dT = approximately ( PREY(T+DT) - PREY(T) ) / DT\n%\n% which means that the first differential equation can be written as\n%\n% PREY(T+DT) = PREY(T) + DT * ( 2 * PREY(T) - 0.001 * PREY(T) * PRED(T) ).\n%\n% We can rewrite the equation for PRED as well. Then, since we know the\n% values of PRED and PREY at time 0, we can use these finite difference\n% equations to estimate the values of PRED and PREY at time DT. These values\n% can be used to get estimates at time 2*DT, and so on. To get from time\n% T_START = 0 to time T_STOP = 5, we simply take STEP_NUM steps each of size\n% DT = ( T_STOP - T_START ) / STEP_NUM.\n%\n% Because finite differences are only an approximation to derivatives, this\n% process only produces estimates of the solution. And these estimates tend\n% to become more inaccurate for large values of time. Usually, we can reduce\n% this error by decreasing DT and taking more, smaller time steps.\n%\n% In this example, for instance, taking just 100 steps gives nonsensical\n% answers. Using STEP_NUM = 1000 gives an approximate solution that seems\n% to have the right kind of oscillatory behavior, except that the amplitude\n% of the waves increases with each repetition. Using 10000 steps, the\n% approximation begins to become accurate enough that we can see that the\n% waves seem to have a fixed period and amplitude.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 November 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% George Lindfield, John Penny,\n% Numerical Methods Using MATLAB,\n% Second Edition,\n% Prentice Hall, 1999,\n% ISBN: 0-13-012641-1,\n% LC: QA297.P45.\n%\n% Parameters:\n%\n% Input, real P0(2), the initial number of prey and predators.\n%\n% Input, real TSPAN(2), the initial and final times.\n%\n% Input, integer STEP_NUM, the number of steps.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FD_PREDATOR_PREY\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A finite difference approximate solution of a pair\\n' );\n fprintf ( 1, ' of ordinary differential equations for a population\\n' );\n fprintf ( 1, ' of predators and prey.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The exact solution shows wave behavior, with a fixed\\n' );\n fprintf ( 1, ' period and amplitude. The finite difference approximation\\n' );\n fprintf ( 1, ' can provide a good estimate for this behavior if the stepsize\\n' );\n fprintf ( 1, ' DT is small enough.\\n' );\n\n t_start = tspan(1);\n t_stop = tspan(2);\n dt = ( t_stop - t_start ) / step_num;\n\n trf = zeros (3,step_num+1);\n\n trf(1,1) = t_start;\n trf(2,1) = p0(1);\n trf(3,1) = p0(2);\n\n for i = 1 : step_num\n trf(1,i+1) = trf(1,i) + dt;\n trf(2,i+1) = trf(2,i) + dt * ( 2 * trf(2,i) - 0.004 * trf(2,i) * trf(3,i) );\n trf(3,i+1) = trf(3,i) + dt * ( - 10 * trf(3,i) + 0.003 * trf(2,i) * trf(3,i) );\n end\n%\n% Time plots.\n%\n figure ( 1 )\n plot ( trf(1,:), trf(2,:), 'g-', ...\n trf(1,:), trf(3,:), 'r-', 'LineWidth', 3 )\n filename = sprintf ( 'trf_%d_time.png', step_num );\n title ( 'Predator Prey System Solved by Finite Differences' );\n grid on\n xlabel ( 'Time' );\n ylabel ( 'Populations' );\n print ( '-dpng', filename );\n%\n% Phase plot.\n%\n figure ( 2 )\n plot ( trf(2,:), trf(3,:), 'b-', 'LineWidth', 3 )\n filename = sprintf ( 'trf_%d_phase.png', step_num );\n title ( 'Predator Prey System Solved by Finite Differences' );\n grid on\n xlabel ( 'Rabbits' );\n ylabel ( 'Foxes' );\n print ( '-dpng', filename );\n%\n% Write data to files.\n%\n filename = sprintf ( 'trf_%d.txt', step_num );\n r8mat_write ( filename, 3, step_num + 1, trf );\n fprintf ( 1, ' T, R, F values written to \"%s\".\\n', filename );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FD_PREDATOR_PREY\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction r8mat_write ( output_filename, m, n, table )\n\n%*****************************************************************************80\n%\n%% R8MAT_WRITE writes an R8MAT file.\n%\n% Discussion:\n%\n% An R8MAT is an array of R8's.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string OUTPUT_FILENAME, the output filename.\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, real TABLE(M,N), the points.\n%\n\n%\n% Open the file.\n%\n output_unit = fopen ( output_filename, 'wt' );\n\n if ( output_unit < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_WRITE - Error!\\n' );\n fprintf ( 1, ' Could not open the output file.\\n' );\n error ( 'R8MAT_WRITE - Error!' );\n end\n%\n% Write the data.\n%\n% For smaller data files, and less precision, try:\n%\n% fprintf ( output_unit, ' %14.6e', table(i,j) );\n%\n for j = 1 : n\n for i = 1 : m\n fprintf ( output_unit, ' %24.16e', table(i,j) );\n end\n fprintf ( output_unit, '\\n' );\n end\n%\n% Close the file.\n%\n fclose ( output_unit );\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fd_predator_prey/fd_predator_prey.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.9390248191350352, "lm_q1q2_score": 0.8873734882438039}} {"text": "function [A,B,C]=triAngles4Sides(a,b,c)\n%%TRIANGLES4SIDES Given the sides of a triangle, find the angles of the\n% triangle. This just applies the law of cosines.\n%\n%INPUTS: a, b, c The scalar lengths of the sides of the triangle in any\n% order.\n%\n%OUTPUTS: A, B, C The angles of the triangle in radians. A is the angle\n% opposite side a, B the angle opposite side b and C the\n% angle opposite side C.\n%\n%The law of cosines is given in [1], among many other places.\n%\n%EXAMPLE:\n%This recovers the angles of a 30-60-90 traingle.\n% a=1;\n% b=sqrt(3);\n% c=2;\n% [A,B,C]=triAngles4Sides(a,b,c);\n% ADeg=rad2deg(A)\n% BDeg=rad2deg(B)\n% CDeg=rad2deg(C)\n%\n%REFERENCES:\n%[1] Weisstein, Eric W. \"Law of Cosines.\" From MathWorld--A Wolfram Web\n% Resource. https://mathworld.wolfram.com/LawofCosines.html\n%\n%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\na2=a.*a;\nb2=b.*b;\nc2=c.*c;\n\nA=acos((-a2+b2+c2)./(2*b.*c));\nB=acos((a2-b2+c2)./(2*a.*c));\nC=pi-A-B;\n%We could have used:\n%C=acos((a2+b2-c2)./(2*a.*b));\n%But we know that the angles in a triangle in Euclidean geometry sum to 180\n%degrees.\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Geometry/triAngles4Sides.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9609517061554854, "lm_q2_score": 0.9230391563648733, "lm_q1q2_score": 0.8869960521571449}} {"text": "function x=lincon(a,b,n)\n%System of linear congruences\n% X = LINCON(A,B,N) solves the system of linear congruences\n%\n% A(1) * X == B(1) (mod N(1))\n% A(2) * X == B(2) (mod N(2))\n% ...\n% A(m) * X == B(m) (mod N(m))\n%\n% The solution, X, will be given as a vector [x1 x2] \n% representing the general solution \n%\n% X == x1 (mod x2)\n% \n% Any specific answer can be found by letting\n% X = x1 + x2 * k for any integer value of k.\n%\n% If no solution exists [NaN NaN] will be returned.\n%\n% A scalar input functions as a constant vector of the\n% same size as the other inputs.\n%\n% Program is compatible with Variable Precision Integer\n% Arithmetic Toolbox available on File Exchange (#22725)\n% Use of VPI is recommended for large magnitude inputs \n% or outputs. If VPI is not used and internal calculations\n% exceed largest consecutive flint a warning will be given\n% that results may be inaccurate, along with [NaN NaN].\n%\n% Example #1:\n% Solve the following system of linear congruences\n% 2x == 2 (mod 6)\n% 3x == 2 (mod 7)\n% 2x == 4 (mod 8)\n%\n% Solution:\n% a=[2 3 2]; b=[2 2 4]; n=[6 7 8];\n% x=lincon(a,b,n)\n%\n% Verify:\n% isequal( mod(a*x(1),n) , b)\n%\n%\n% Example #2:\n% Use of VPI for large magnitude numbers. Solve the following\n% system of linear congruences\n% (1234567)x == 89 (mod 2^32)\n% (9876543)x == 21 (mod 3^50)\n% (5555)x == 62830211 (mod 7^10)\n%\n% Solution:\n% a=[1234567 9876543 5555]; b=[89 21 62830211]; \n% n=[vpi(2)^32 vpi(3)^50 vpi(7)^10];\n% x=lincon(a,b,n)\n%\n% Verify:\n% isequal( mod(a*x(1),n) , b)\n%\n\n% Mike Sheppard\n% Last Modified 11-Sep-2011\n\n\n%Check Inputs\n[a,b,n,isvpi]=LinConCheckInputs(a,b,n);\n\n%Initialize\nb=mod(b,n); % Make all positive for consistency\nm=length(a); % Number of congruences\nx=[0 1]; % Initialize to x==0 (mod 1)\nk=0; % line number\n\nwhile k 1) is the number of\n% vectors and n is their dimensionality. Q, with values in the range\n% [0,n], is the number of eigenvectors used in constructing the\n% principal-components transformation matrix. P is a structure with\n% the following fields:\n%\n% P.Y K-by-Q matrix whose columns are the principal-\n% component vectors.\n% P.A Q-by-n principal components transformation matrix\n% whose rows are the Q eigenvectors of Cx corresponding\n% to the Q largest eigenvalues. \n% P.X K-by-n matrix whose rows are the vectors \n% reconstructed from the principal-component vectors. \n% P.X and P.Y are identical if Q = n. \n% P.ems The mean square error incurred in using only the Q\n% eigenvectors corresponding to the largest\n% eigenvalues. P.ems is 0 if Q = n. \n% P.Cx The n-by-n covariance matrix of the population in X.\n% P.mx The n-by-1 mean vector of the population in X.\n% P.Cy The Q-by-Q covariance matrix of the population in\n% Y. The main diagonal contains the eigenvalues (in\n% descending order) corresponding to the Q\n% eigenvectors.\n%\n% Copyright 2002-2020 Gatesmark\n%\n% This function, and other functions in the DIPUM Toolbox, are based \n% on the theoretical and practical foundations established in the \n% book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark \n% Press, 2020.\n%\n% Book website: http://www.imageprocessingplace.com\n% License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt\n\nK = size(X,1);\nX = double(X);\n\n% Obtain the mean vector and covariance matrix of the vectors in X.\n[P.Cx,P.mx] = covmatrix(X);\n% Convert mean vector to a row vector.\nP.mx = P.mx'; \n\n% Obtain the eigenvectors and corresponding eigenvalues of Cx. The\n% eigenvectors are the columns of n-by-n matrix V. D is an n-by-n\n% diagonal matrix whose elements along the main diagonal are the\n% eigenvalues corresponding to the eigenvectors in V, so that X*V =\n% D*V.\n[V,D] = eig(P.Cx);\n\n% Sort the eigenvalues in decreasing order. Rearrange the eigenvectors\n% to match.\nd = diag(D);\n[d,idx] = sort(d);\nd = flipud(d);\nidx = flipud(idx);\nD = diag(d);\nV = V(:,idx);\n\n% Now form the q rows of A from the first q columns of V.\nP.A = V(:,1:q)';\n\n% Compute the principal component vectors.\nP.Y = P.A*(X - P.mx)'; % q-by-K matrix.\n\n% Obtain the reconstructed vectors.\nP.X = (P.A'*P.Y)' + P.mx;\n\n% Convert P.Y to a K-by-q array and P.mx to an n-by-1 vector.\nP.Y = P.Y';\nP.mx = P.mx';\n\n% The mean square error is the sum of all the eigenvalues minus the sum\n% of the q largest eigenvalues.\nd = diag(D);\nP.ems = sum(d(q + 1:end));\n\n% Covariance matrix of the Y's.\nP.Cy = P.A*P.Cx*P.A';\n\n", "meta": {"author": "dipum", "repo": "dipum-toolbox", "sha": "9ce653c4c0c4b7c56e46194c24bf152db4ab6832", "save_path": "github-repos/MATLAB/dipum-dipum-toolbox", "path": "github-repos/MATLAB/dipum-dipum-toolbox/dipum-toolbox-9ce653c4c0c4b7c56e46194c24bf152db4ab6832/dipum/principalComponents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.9304582492269372, "lm_q1q2_score": 0.8856689909091758}} {"text": "function [A,B,C]=spherTriAngles4Sides(a,b,c,r)\n%%SPHERTRIANGLES4SIDES Given the lengths of the sides of a spherical\n% triangle, find the angles of the triangle. Note that the angles of\n% a spherical triangle do not sum to pi. This is just an application\n% of the spherical law of cosines. Note that unlike with a EUclidean\n% triangle, one cannot just enter arbitrary distances for a, b, and c\n% (even if much smaller than the circumference of the sphere),\n% because certain distance relations are not possible and will result\n% in non-real solutions.\n%\n%INPUTS: a, b, c The lengths of the sides of the spherical triangle\n% in any order. If one wishes to convert multiple triangles\n% at once, these can be matrices.\n% r The scalar radius of the sphere on which the distances are\n% measured. If omitted or an empty matrix is passed, the\n% default of 1 is used.\n%\n%OUTPUTS: A, B, C The angles of the spherical triangle in radians. A is the\n% angle opposite side a, B the angle opposite side b and C\n% the angle opposite side C. The dimensions correspond to\n% those of the inputs.\n%\n%The spherical law of cosines for the sides of a spherical triangle is\n%stated in [1].\n%\n%EXAMPLE:\n%First, we choose 3 points on the sphere, find the distances between them\n%and then show that we can get the angles. Then, we just set some arbitrary\n%distances that do not form a possible triangle on the spehre and we see\n%that the angular results are complex.\n%Choose 3 points in term of latitude-longitude on a sphere.\n% llPoints=deg2rad([19, 21, 27;\n% -158,-147,-152]);\n% r=1;\n% a=greatCircleDistance(llPoints(:,1),llPoints(:,2),r);\n% b=greatCircleDistance(llPoints(:,2),llPoints(:,3),r);\n% c=greatCircleDistance(llPoints(:,3),llPoints(:,1),r);\n% [A,B,C]=spherTriAngles4Sides(a,b,c,r);\n% ADeg=rad2deg(A)\n% BDeg=rad2deg(B)\n% CDeg=rad2deg(C)\n% a=1;\n% b=2;\n% c=3;\n% [A,B,C]=spherTriAngles4Sides(a,b,c,r)\n%\n%REFERENCES:\n%[1] Weisstein, Eric W. \"Law of Cosines.\" From MathWorld--A Wolfram Web\n% Resource. https://mathworld.wolfram.com/LawofCosines.html\n%\n%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<4||isempty(r))\n r=1;\nend\n\na=a./r;\nb=b./r;\nc=c./r;\n\ncosa=cos(a);\nsina=sin(a);\ncosb=cos(b);\nsinb=sin(b);\ncosc=cos(c);\nsinc=sin(c);\n\nA=acos((cosa-cosb.*cosc)./(sinb.*sinc));\nB=acos((cosb-cosa.*cosc)./(sina.*sinc));\nC=acos((cosc-cosa.*cosb)./(sina.*sinb));\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Geometry/spherTriAngles4Sides.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.9196425366837827, "lm_q1q2_score": 0.8853151433201177}} {"text": "function diffVal=angCircDiff(ang)\n%%ANGCIRCDIFF Given two angles (in radians) on a unit circle, take their\n% difference in radians. The difference can only span +/-pi. For\n% example the difference between 0 and 2*pi should be zero as both\n% represent the same point.\n%\n%INPUTS: angs A 2XnumAng matrix of angles in radians. The differences \n% angs(1,:)-angs(2,:) in each column will be taken.\n%\n%OUTPUTS: diffVal A 1XnumAng vector of the differences on the unit circle\n% of the angles. The shortest way around the circle is\n% chosen. This goes from -pi to pi.\n%\n%This function simple takes the difference and wraps it to the range of -pi\n%to pi with the wrapRange function.\n%\n%EXAMPLE:\n%One can verify that for an angle of 0.1\n% angCircDiff([0;0.1])-angCircDiff([0;0.1+2*pi])\n%the difference is around machine precision. Similarly,\n% angCircDiff([0;2*pi])\n% is exactly zero\n%\n%January 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\ndiffVal=wrapRange(ang(1,:)-ang(2,:),-pi,pi);\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/angCircDiff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.9324533046369554, "lm_q1q2_score": 0.8848210390984891}} {"text": "function result = is_orthonormal_set(A)\n%\n% Orthonormal Sets\n% \n% is_orthonormal_set(A) determines if a set of vectors in Euclidean n-space\n% is orthonormal. The matrix A is formed from these vectors as its columns. \n% That is, the subspace spanned by the set of vectors is the column space \n% of A. The value 1 is returned if the set is orthonormal. The value 0 is \n% returned if the set is not orthonormal. An error is returned if a set\n% containing only zero vectors is attempted to be determined for\n% orthonormality.\n%\n% For example, if the set of row vectors (u1,u2,...} is to be determined \n% for orthonormality, set A to be equal to [u1' u2' ...].\n%\n% Function written by Anthony Russo, downloaded from MatlabCentral.\n%\n\nmatrix_size = size(A);\n\nm = matrix_size(1,1);\nn = matrix_size(1,2);\n\ntolerance = 10^-10;\n\nif A == zeros(m,n) \n error('The set that contains just zero vectors cannot be orthonormal.');\nelseif n == 1\n if norm(A(1:m,1)) == 1\n result = 1;\n else\n result = 0;\n end\nelse\n if is_orthogonal_set(A) == 1\n length_counter = 0;\n \n for i = 1:n\n if abs(norm(A(1:m,i)) - 1) <= tolerance\n length_counter = length_counter + 1;\n end\n end\n\n if length_counter == n\n result = 1;\n else\n result = 0;\n end\n else\n result = 0;\n end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/afni/is_orthonormal_set.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214511730025, "lm_q2_score": 0.9173026556293917, "lm_q1q2_score": 0.884574628041384}} {"text": "function v = logdet(A, op)\n%LOGDET Computation of logarithm of determinant of a matrix\n%\n% v = logdet(A);\n% computes the logarithm of determinant of A. \n%\n% Here, A should be a square matrix of double or single class.\n% If A is singular, it will returns -inf.\n%\n% Theoretically, this function should be functionally \n% equivalent to log(det(A)). However, it avoids the \n% overflow/underflow problems that are likely to \n% happen when applying det to large matrices.\n%\n% The key idea is based on the mathematical fact that\n% the determinant of a triangular matrix equals the\n% product of its diagonal elements. Hence, the matrix's\n% log-determinant is equal to the sum of their logarithm\n% values. By keeping all computations in log-scale, the\n% problem of underflow/overflow caused by product of \n% many numbers can be effectively circumvented.\n%\n% The implementation is based on LU factorization.\n%\n% v = logdet(A, 'chol');\n% If A is positive definite, you can tell the function \n% to use Cholesky factorization to accomplish the task \n% using this syntax, which is substantially more efficient\n% for positive definite matrix. \n%\n% Remarks\n% -------\n% logarithm of determinant of a matrix widely occurs in the \n% context of multivariate statistics. The log-pdf, entropy, \n% and divergence of Gaussian distribution typically comprises \n% a term in form of log-determinant. This function might be \n% useful there, especially in a high-dimensional space. \n%\n% Theoretially, LU, QR can both do the job. However, LU \n% factorization is substantially faster. So, for generic\n% matrix, LU factorization is adopted. \n%\n% For positive definite matrices, such as covariance matrices,\n% Cholesky factorization is typically more efficient. And it\n% is STRONGLY RECOMMENDED that you use the chol (2nd syntax above) \n% when you are sure that you are dealing with a positive definite\n% matrix.\n%\n% Examples\n% --------\n% % compute the log-determinant of a generic matrix\n% A = rand(1000);\n% v = logdet(A);\n%\n% % compute the log-determinant of a positive-definite matrix\n% A = rand(1000);\n% C = A * A'; % this makes C positive definite\n% v = logdet(C, 'chol');\n%\n\n% Copyright 2008, Dahua Lin, MIT\n% Email: dhlin@mit.edu\n%\n% This file can be freely modified or distributed for any kind of \n% purposes.\n%\n\n%% argument checking\n\nassert(isfloat(A) && ndims(A) == 2 && size(A,1) == size(A,2), ...\n 'logdet:invalidarg', ...\n 'A should be a square matrix of double or single class.');\n\nif nargin < 2\n use_chol = 0;\nelse\n assert(strcmpi(op, 'chol'), ...\n 'logdet:invalidarg', ...\n 'The second argument can only be a string ''chol'' if it is specified.');\n use_chol = 1;\nend\n\n%% computation\n\nif use_chol\n v = 2 * sum(log(diag(chol(A))));\nelse\n [L, U, P] = lu(A);\n du = diag(U);\n c = det(P) * prod(sign(du));\n v = log(c) + sum(log(abs(du)));\nend\n\n", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/utils/math/logdet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360932, "lm_q2_score": 0.9241418147556224, "lm_q1q2_score": 0.8840656667876184}} {"text": "function x=findQuadraticFitVertex(x1,x2,param1,param2,param3)\n%%FINDQUADRATICFIRVERTEX Find the minimum of a parabola that fits given\n% scalar data when presented with one of two parameterizations.\n% the first parameterization uses two function values and one\n% derivaitve value. The second parameterization uses just two\n% derivative values.\n%\n%INPUTS: x1, x2 The two points at which the values are taken.\n% param1,param2,param3 These thee values can be given in two ways, which\n% determine their meaning. The first is:\n% f1 The value of the function at x1.\n% f2 The value of the function at x2.\n% g1 The derivative of the function at x1.\n% The other parameterization is\n% g1 The gradient at x1.\n% g2 The gradient at x2.\n% param3 is either omitted or an empty matrix is passed when\n% using the second formulation.\n%\n%OUTPUTS: x The interpolated critical point (minimum or maximum) of the\n% fitted parabola.\n%\n%For the first formulation of the problem, we are given equations with\n%unknown coefficients (a,b,c):\n% f1==a*x1^2+b*x1+c\n% f2==a*x2^2+b*x2+c\n% gl==b+2*a*x1\n%Solving for (a,b,c) one gets\n%a=(-f1+f2+g1*(x1-x2))/(x1-x2)^2\n%b=(2*f1*x1-x1*(2*f2+g1*x1)+g1*x2^2)/(x1-x2)^2\n%c=(f2*x1^2+g1*x1*(x1-x2)*x2+f1*x2*(-2*x1+x2))/(x1-x2)^2\n%Substitutign into the expression for the derivative and setting the\n%derivative equal to zero, one gets a value of x of \n%x=x1+(g1*(x2-x1)^2)/(2*(f1-f2+g1*(x2-x1)))\n%\n%For the second formulation of the problem, we are given equations with\n%unknown coefficients (a,b,c):\n% f1==a*x1^2+b*x1+c\n% g1==b+2*a*x1\n% g2==b+2*a*x2\n%Solving for (a,b,c) one gets\n% a=(g1-g2)/(2*x1-2*x2)\n% b=(g2*x1-g1*x2)/(x1-x2)\n% c=f1+(x1*(-(g1+g2)*x1+2*g1*x2))/(2*(x1-x2))\n%Substituting into the expression for the derivative and setting the\n%derivative equal to zero, one gets a value of x of\n% x=x2+g2*(x1-x2)/(g2-g1);\n%which does not require the value f1.\n%\n%EXAMPLE:\n%Here, we use the function f=3*(x-12)*(x-14)=3*x^2-78*x+504;\n% x1=-10;\n% x2=24;\n% f1=3*x1^2-78*x1+504;\n% f2=3*x2^2-78*x2+504;\n% g1=2*3*x1-78;\n% g2=2*3*x2-78;\n% xSol1=findQuadraticFitVertex(x1,x2,f1,f2,g1)\n% xSol2=findQuadraticFitVertex(x1,x2,g1,g2)\n%One will find that both xSol1 and xSol2 =13, which is the minimum point of\n%the parabola.\n%\n%February 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin>4&&~isempty(param3))\n %Given the first type of parameterization.\n f1=param1;\n f2=param2;\n g1=param3;\n\n \n diff=x2-x1;\n x=x1+(g1*diff^2)/(2*(f1-f2+g1*diff));\nelse\n %Given the second type of parameterization.\n g1=param1;\n g2=param2;\n \n x=x2+g2*(x1-x2)/(g2-g1);\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Polynomials/findQuadraticFitVertex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191271831558, "lm_q2_score": 0.92522995296862, "lm_q1q2_score": 0.8838898711136943}} {"text": "function [gm samc] = mcurvature_vec(x,y,z)\n% Description: The function calculates mean curvature and \n% Surface Avg Mean Curvature (SAMC) of a surface formed by x, y & z. \n% The input are the coordinate matrices x, y & z. The \n% matrices can be formed using meshgrid or similar functions.\n% This code is a vectorized form of original code (mcurvature) posted \n% on Matlab File Exchange.\n\n% The mean curvature is calculated according to the formula:\n\n% If x:U->R^3 is a regular patch, then the mean curvature is given by\n% \n% H = (eG-2fF+gE)/(2(EG-F^2)),\t\n% \n% where E, F, and G are coefficients of the first fundamental form and\n% e, f, and g are coefficients of the second fundamental form \n\n% Reference: Gray, A. \"The Gaussian and Mean Curvatures.\" §16.5 in \n% Modern Differential Geometry of Curves and Surfaces with Mathematica, \n% 2nd ed. Boca Raton, FL: CRC Press, pp. 373-380, 1997 (p. 377).\n\n% Inspired by:\n% Title: \tMean Curvature\n% Author: \tAhmed Elnaggar\n% Summary: \tCalculate the Mean curvature of a given surface (x,y,z).\n\ngm = zeros(size(z));\n[xu,xv] = gradient(x);\n[xuu,xuv] = gradient(xu);\n[xvu,xvv] = gradient(xv);\n\n[yu,yv] = gradient(y);\n[yuu,yuv] = gradient(yu);\n[yvu,yvv] = gradient(yv);\n\n[zu,zv] = gradient(z);\n[zuu,zuv] = gradient(zu);\n[zvu,zvv] = gradient(zv);\n\nXu(:,:,1) = xu;\nXu(:,:,2) = yu;\nXu(:,:,3) = zu;\n\nXv(:,:,1) = xv;\nXv(:,:,2) = yv;\nXv(:,:,3) = zv;\n\nXuu(:,:,1) = xuu;\nXuu(:,:,2) = yuu;\nXuu(:,:,3) = zuu;\n\nXuv(:,:,1) = xuv;\nXuv(:,:,2) = yuv;\nXuv(:,:,3) = zuv;\n\nXvv(:,:,1) = xvv;\nXvv(:,:,2) = yvv;\nXvv(:,:,3) = zvv;\n\nE = dot(Xu,Xu,3);\nF = dot(Xu,Xv,3);\nG = dot(Xv,Xv,3);\nm = cross(Xu,Xv,3);\ntemp(:,:,1) = sqrt(sum(m.*m,3));\ntemp(:,:,2) = temp(:,:,1);\ntemp(:,:,3) = temp(:,:,1);\nn = m./temp;\nL = dot(Xuu,n,3);\nM = dot(Xuv,n,3);\nN = dot(Xvv,n,3);\ngm = ((E.*N)+(G.*L)-(2.*F.*M))./(2.*(E.*G - F.^2));\n\ndim = size(z);\nsamc = 1/ (dim(1) * dim(2)) * sum (gm(:).^2);\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/10010-mean-curvature-fast-code/mcurvature_vec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812318188365, "lm_q2_score": 0.9124361598816667, "lm_q1q2_score": 0.8835860524622573}} {"text": "function y=expSlope2(x)\n%%EXPSLOPE2 Evaluate the function 2*(exp(x)-1-x)/x^2 avoiding problems at\n% the point x=0, where the limit equals 1. This function arises\n% in range enclosure algorithms for interval arithmetic.\n%\n%INPUTS: x A vector of matrix of real values at which the function should\n% be evaluated.\n%\n%OUTPUTS: y The value(s) of the function 2*(exp(x)-1-x)/x^2 at the point(s)\n% in x.\n%\n%For values of x having magnitude over 1e-2 or for complex values, the\n%function is evaluated as written. For smaller values, a Taylor series\n%expansion is used to avoid the singularity near the origin. The Taylor\n%series expansion is simple, because the value of the nth derivative at 0\n%is just 1/(n+1).\n%\n%This is one of the slope function in Table 10.6 of Section 10.6.2 of [1].\n%This file implements the function for non-intervals. See the Interval\n%class for an implementation for Interval arithmetic.\n%\n%REFERENCES:\n%[1] IEEE Standard for Interval Arithmetic,\" in IEEE Std 1788-2015,\n% pp.1-97, June 30 2015.\n%\n%November 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%Allocate space\ny=zeros(size(x));\n\n%For large enough values, use the standard function.\nsel=abs(x)>1e-2|~isreal(x);\nx1=x(sel);\ny(sel)=2*(expm1(x1)-x1)./x1.^2;\n\n%For smaller magnitude values, use a sixth-order Taylor series expansion.\n%The relative error at 10^-2 is on the order of 1e-20, which is less than\n%the precision of a double floating point number at that value. The series\n%is given in Horner form.\nx1=x(~sel);\ny(~sel)=1+x1.*(1/3+x1.*(1/12+x1.*(1/60+x1.*(1/360+(1/2520+x1./20160).*x1))));\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Slope_Functions/expSlope2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574122783325, "lm_q2_score": 0.9273632931373372, "lm_q1q2_score": 0.8833822754617545}} {"text": "%% Test Newton Method 2\n% Test Newton_n_sytem subroutine\n\n% Clear memory\nclear all; close all; clc;\n\n% display format\nformat long\n\n%% Examples\nexample = 3;\nswitch example\n case{1} % 2-by-2 Polynomials,\n % Define vector of functions 'f' and matrix of partial derivates 'df',\n f = inline('[x(1)^3+x(2)-1 ; x(2)^3-x(1)+1]');\n df = inline('[3*x(1)^2, 1 ; -1, 3*x(2)^2]');\n\n % Plot figures,\n g1 = 'x^3+y-1'; g2 = 'y^3-x+1'; xy_range = [-4,4,-4,4];\n figure(1); grid on;\n hold on;\n ez1 = ezplot(g1,xy_range);\n ez2 = ezplot(g2,xy_range); \n hold off;\n legend('g1(x,y)=x^3+y-1','g2(x,y)=y^3-x+1'); \n set(ez1,'color',[0 0 1]);\n set(ez2,'color',[1 0 0]);\n title('Solving x^3+y-1 & y^3-x+1 for {x,y}')\n \n % Initial Guess,\n x0 = [.5;.5] ;\n \n case{2} % 2-by-2 Nonlinear system,\n % Define vector of functions 'f' and matrix of partial derivates 'df',\n f = inline('[10*x(1)^2+sin(x(2))-20 ; x(1)^4+5*x(2)-6]');\n df = inline('[20*x(1), cos(x(2)) ; 4*x(1)^3, 5]');\n \n % Plot figures,\n g1 = '10*x^2+sin(y)-20'; g2 = 'x^4+5*y-6'; xy_range = [-8,8,-8,8];\n figure(1); grid on;\n hold on;\n ez1 = ezplot(g1,xy_range);\n ez2 = ezplot(g2,xy_range); \n hold off;\n legend('g1(x,y)=10x^2+sin(y)-20','g2(x,y)=x^4+5y-6',1); \n set(ez1,'color',[0 0 1]);\n set(ez2,'color',[1 0 0]);\n title('Solving 10x^2+sin(y)=20 & x^4+5y=6 for {x,y}')\n \n % Initial Guess,\n x0 = [1;1];\n \n case{3} % 3-by-3 Polynomial System,\n % Define vector of functions 'f' and matrix of partial derivates 'df',\n f = inline('[x(1)^3-2*x(2)-2 ; x(1)^3-5*x(3)^2+7 ; x(2)*x(3)^2-1]');\n df = inline('[3*x(1)^2 -2 0;3*x(1)^2 0 -10*x(3);0 x(3)^2 2*x(2)*x(3)]');\n \n % Initial Guess,\n x0 = [1;1;1];\nend\n\n%% Convergence criteria\n % Define max number of iterations,\n n_max = 8;\n\n % Define tolerance,\n tol = 1e-6;\n tol = tol*ones(size(2,1));\n\n%% Use Newton_n_sytem.m func,\ntic;\nx = x0; x_next = Newton_n_system(f,df,x); n = 1;\nwhile and((n < n_max),(abs(x_next - x) > tol))\n x = x_next;\n x_next = Newton_n_system(f,df,x);\n n = n + 1;\nend\nfprintf('My solver: %1.12f \\n',x) % show me the result\nt1 = toc; % time for Costumb solver\n\n%% Using Matlab solver,\ntic;\nx = x0; x = fsolve(f,x);\nfprintf('Matlab solver: %1.12f \\n',x) % show me the result\nt2 = toc; % time for Matlab solver\n\n% how fast is our Newton Solver,\nfprintf('Costum Solver is: %1.1f times faster than Matlab solver \\n',t2/t1)", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/Newton/NewtonTestMe2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.9252299493606285, "lm_q1q2_score": 0.8832683799694846}} {"text": "function [ x, w ] = ncc_compute ( n )\n\n%*****************************************************************************80\n%\n%% NCC_COMPUTE computes a Newton-Cotes Closed quadrature rule.\n%\n% Discussion:\n%\n% For the interval [-1,+1], the Newton-Cotes Closed quadrature rule\n% estimates\n%\n% Integral ( -1 <= X <= +1 ) F(X) dX\n%\n% using N abscissas X and weights W:\n%\n% sum ( 1 <= I <= N ) W(I) * F ( X(I) ).\n%\n% For the CLOSED rule, the abscissas are equally spaced, and include\n% the end points.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 November 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order.\n%\n% Output, real X(N), the abscissas.\n%\n% Output, real W(N), the weights.\n%\n x = ncc_compute_points ( n );\n\n w = ncc_compute_weights ( n );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrule/ncc_compute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9664104933824754, "lm_q2_score": 0.913676521650809, "lm_q1q2_score": 0.8829865780805424}} {"text": "% KRON Kronecker tensor product.\n% KRON(X,Y) is the Kronecker tensor product of X and Y.\n% The result is a large matrix formed by taking all possible\n% products between the elements of X and those of Y. For\n% example, if X is 2 by 3, then KRON(X,Y) is\n% \n% [ X(1,1)*Y X(1,2)*Y X(1,3)*Y\n% X(2,1)*Y X(2,2)*Y X(2,3)*Y ]\n% \n% If either X or Y is sparse, only nonzero elements are multiplied\n% in the computation, and the result is sparse.\n% \n% Class support for inputs X,Y:\n% float: double, single\n% integers: uint8, int8, uint16, int16, uint32, int32, uint64, int64\n%\n% Reference page in Doc Center\n% doc kron\n%\n% Other functions named kron\n%\n% splanar/kron sym/kron\n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/m/+parser/kron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899575269305, "lm_q2_score": 0.9136765257642905, "lm_q1q2_score": 0.8825197681692624}} {"text": "function y = norm_cdf(x,mu,sigma)\n%NORM_CDF Normal cumulative probability density function (cdf)\n%\n% Y = NORMCDF(X,MU,SIGMA) Returns the normal cdf with\n% mean, MU, and standard deviation, SIGMA, at the values in X.\n%\n% The size of X is the common size of the input arguments. A scalar input \n% functions as a constant matrix of the same size as the other inputs. \n%\n% Default values for MU and SIGMA are 0 and 1 respectively.\n%\n% Copyright (c) 1998-2004,2011 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\nif nargin < 3, \n sigma = 1;\nend\n\nif nargin < 2;\n mu = 0;\nend\n\nif nargin < 1, \n error('Requires at least one input argument.');\nend\n\ny = 0.5 * erfc(-((x-mu) ./ sigma) ./ sqrt(2));\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/dist/norm_cdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877726405083, "lm_q2_score": 0.908617890746506, "lm_q1q2_score": 0.8819842765500426}} {"text": "function value = circle_area_2d ( r )\n\n%*****************************************************************************80\n%\n%% CIRCLE_AREA_2D returns the area of a circle in 2D.\n%\n% Integration region:\n%\n% Points (X,Y) such that\n%\n% ( X - XC )**2 + ( Y - YC )**2 <= R**2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, the radius of the circle.\n%\n% Output, real CIRCLE_AREA_2D, the area of the circle.\n%\n value = pi * r * r;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/circle_area_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191259110589, "lm_q2_score": 0.9230391669503405, "lm_q1q2_score": 0.8817969701526713}} {"text": "function [ x, y, a, b, c, ierror ] = r8poly2_ex2 ( x1, y1, x2, y2, x3, y3 )\n\n%*****************************************************************************80\n%\n%% R8POLY2_EX2 finds the extremal point of a parabola determined by three points.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 September 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X1, Y1, X2, Y2, X3, Y3, the coordinates of \n% three points on the parabola. X1, X2 and X3 must be distinct.\n%\n% Output, real X, Y, the X coordinate of the extremal \n% point of the parabola, and the value of the parabola at that point.\n%\n% Output, real A, B, C, the coefficients that define the\n% parabola: P(X) = A * X**2 + B * X + C.\n%\n% Output, integer IERROR, error flag.\n% 0, no error.\n% 1, two of the X values are equal.\n% 2, the data lies on a straight line; there is no finite extremal\n% point.\n%\n ierror = 0;\n x = x1;\n y = y1;\n a = 0.0;\n b = 0.0;\n c = 0.0;\n\n if ( x1 == x2 || x2 == x3 || x3 == x1 )\n ierror = 1;\n return\n end\n\n if ( y1 == y2 && y2 == y3 && y3 == y1 )\n x = x1\n y = y1\n return\n end\n%\n% Set up the Vandermonde matrix.\n%\n v(1,1) = 1.0;\n v(1,2) = x1;\n v(1,3) = x1 * x1;\n\n v(2,1) = 1.0;\n v(2,2) = x2;\n v(2,3) = x2 * x2;\n\n v(3,1) = 1.0;\n v(3,2) = x3;\n v(3,3) = x3 * x3;\n%\n% Get the inverse.\n%\n [ w, det ] = r8mat_inverse_3d ( v );\n%\n% Compute the parabolic coefficients.\n%\n c = w(1,1) * y1 + w(1,2) * y2 + w(1,3) * y3;\n b = w(2,1) * y1 + w(2,2) * y2 + w(2,3) * y3;\n a = w(3,1) * y1 + w(3,2) * y2 + w(3,3) * y3;\n%\n% Determine the extremal point.\n%\n if ( a == 0.0 )\n ierror = 2;\n return\n end\n\n x = -b / ( 2.0 * a );\n y = a * x * x + b * x + c;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8poly2_ex2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182844, "lm_q2_score": 0.924141814233309, "lm_q1q2_score": 0.8815999625728}} {"text": "function J=normVecJacob(x)\n%%NORVECJACOB Consider a unit vector created as u=x/norm(x). This function\n% returns the partial derivatives of u with respect to the elements\n% of x. This partial derivative \n%\n%INPUTS: x A real NX1 vector.\n%\n%OUTPUTS: J The NXN partial derivative matrix The columns are the element\n% of x with respect to which the partial derivative is taken and\n% the rows are the elements of u.\n%\n%EXAMPLE:\n%Here, we verify that the output of this function agrees with the numerical\n%differentiation result.\n% x=[4;-18;12];\n% u=@(x)x/norm(x);\n% JNumDiff=numDiff(x,u,3);\n% J=normVecJacob(x);\n% RelErr=max(abs((J(:)-JNumDiff(:))./J(:)))\n%The relative error will be about 3.8488e-10, indicating a good level of\n%agreement between the numerical differentiation result and the analytic\n%result.\n%\n%November 2020 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nxDim=length(x);\nnormX=norm(x);\n\nJ=-x*x'/normX^3+eye(xDim,xDim)/normX;\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Coordinate_Systems/Jacobians/normVecJacob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9621075755433747, "lm_q2_score": 0.9161096198879968, "lm_q1q2_score": 0.8813960053224031}} {"text": "function val=geometricMean(x,dim)\n%%GEOMETRICMEAN Compute the geometric mean of a set of samples.\n%\n%INPUTS: x The set of samples over which the geometric mean is to be found.\n% How the function handles vectors and matrices is determined by\n% the parameter dim.\n% dim An optional parameter specifying over which dimension of x the\n% geometric mean is to be taken. If dim is omitted or an empty\n% matrix is passsed, then if x is a vector, the geometric mean is\n% found over all elements of the vector. If x is a matrix, then\n% the mean is found over the columns of the matrix (resulting in a\n% row vector), and if x is an n-dimensional (n>2) matrix, then the\n% geometric mean is found over the first non-singleton dimension\n% of the matrix.\n%\n%OUTPUT: val The geometric mean of x taken over the appropriate dimension.\n%\n%The geometric mean of n items is the nth-root of the product of those\n%items. The computation is performed using logarithms to avoid overflows.\n%This can mean that one does not obtain the desired complex nth root when\n%negative values are complex numbers are the argument as there are multiple\n%solutions to the nth root.\n%\n%October 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(isempty(x))\n val=[];\n return\nend\n\nxDims=size(x);\nif(nargin<2||isempty(dim))\n if(length(xDims)<3)%If x is a vector or matrix.\n if(xDims(1)==1||xDims(2)==1)%If x is a vector\n x=x(:);\n dim=1;\n n=length(x);\n else%x is a matrix, go over the columns.\n dim=2;\n n=xDims(2);\n end\n else%If x is an n-dimensional matrix.\n dim=find(xDims>1,1);\n if(isempty(dim))\n dim=1;\n n=1;\n else\n n=xDims(dim);\n end\n end\nelse\n n=xDims(dim);\nend\n\n%We could do prod(x,dim).^(1/n);, but that is likely to overflow if there\n%are many values. Thus, we take the exponent of the sum of the logarithm.\nval=exp((1/n)*sum(log(x),dim));\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/geometricMean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109784205502, "lm_q2_score": 0.9273632951448402, "lm_q1q2_score": 0.881376256689913}} {"text": "function value = mono_total_enum ( m, n )\n\n%*****************************************************************************80\n%\n%% MONO_TOTAL_ENUM enumerates monomials in M dimensions of degree equal to N.\n%\n% Discussion:\n%\n% For M = 3, we have the following values:\n%\n% N VALUE\n%\n% 0 1\n% 1 3\n% 2 6\n% 3 10\n% 4 15\n% 5 21\n%\n% In particular, VALUE(3,3) = 10 because we have the 10 monomials:\n%\n% x^3, x^2y, x^2z, xy^2, xyz, xz^3, y^3, y^2z, yz^2, z^3.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 September 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the maximum degree.\n%\n% Output, integer VALUE, the number of monomials in D variables,\n% of total degree N.\n%\n value = nchoosek ( n + m - 1, n );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/monomial/mono_total_enum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900507, "lm_q2_score": 0.9184802496038499, "lm_q1q2_score": 0.8809642662596316}} {"text": "function value = r8vec_scalar_triple_product ( v1, v2, v3 )\n\n%*****************************************************************************80\n%\n%% R8VEC_SCALAR_TRIPLE_PRODUCT finds the scalar triple product in 3D.\n%\n% Discussion:\n%\n% [A,B,C] = A dot ( B cross C )\n% = B dot ( C cross A )\n% = C dot ( A cross B )\n%\n% The volume of a parallelepiped, whose sides are given by\n% vectors A, B, and C, is abs ( A dot ( B cross C ) ).\n%\n% Three vectors are coplanar if and only if their scalar triple \n% product vanishes.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 August 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Eric Weisstein,\n% \"Scalar Triple Product\",\n% CRC Concise Encyclopedia of Mathematics, 1999\n%\n% Parameters:\n%\n% Input, real V1(3), V2(3), V3(3), the vectors.\n%\n% Output, real VALUE, the scalar triple product.\n%\n v4 = r8vec_cross_product_3d ( v2, v3 );\n\n value = v1' * v4;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec_scalar_triple_product.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96036116089903, "lm_q2_score": 0.9173026539338223, "lm_q1q2_score": 0.8809418416276468}} {"text": "function fx = p31_fun ( n, x )\n\n%*****************************************************************************80\n%\n%% P31_FUN evaluates the integrand for problem 31.\n%\n% Discussion:\n%\n% A simple Newton-Cotes quadrature rule, in which the order of the\n% rule is increased, but the interval is not subdivided, diverges\n% for this integrand.\n%\n% This is Runge's function, a standard example of the perils of\n% using high order polynomial interpolation at equally spaced nodes.\n% Since this is exactly what is really going on in a Newton Cotes\n% rule, it is little wonder that the result is so poor.\n%\n% Interval:\n%\n% -4 <= x <= 4\n%\n% Integrand:\n%\n% 1 / ( 1 + x^2 )\n%\n% Antiderivative:\n%\n% arctan ( x )\n%\n% Exact Integral:\n%\n% 2 * arctan ( 4 )\n%\n% Approximate Integral (20 digits):\n%\n% 2.6516353273360649301...\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 November 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Kendall Atkinson,\n% An Introduction to Numerical Analysis,\n% Prentice Hall, 1984, page 266.\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(N), the evaluation points.\n%\n% Output, real FX(N), the integrand values.\n%\n fx = 1.0 ./ ( 1.0 + x.^2 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_int/p31_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620608291781, "lm_q2_score": 0.9173026584553408, "lm_q1q2_score": 0.8803922898831816}} {"text": "function cfl = fd1d_heat_implicit_cfl ( k, t_num, t_min, t_max, x_num, ...\n x_min, x_max )\n\n%*****************************************************************************80\n%\n%% FD1D_HEAT_IMPLICIT_CFL: compute the Courant-Friedrichs-Loewy coefficient.\n%\n% Discussion:\n%\n% The equation to be solved has the form:\n%\n% dUdT - k * d2UdX2 = F(X,T)\n%\n% over the interval [X_MIN,X_MAX] with boundary conditions\n%\n% U(X_MIN,T) = U_X_MIN(T),\n% U(X_MIN,T) = U_X_MAX(T),\n%\n% over the time interval [T_MIN,T_MAX] with initial conditions\n%\n% U(X,T_MIN) = U_T_MIN(X)\n%\n% The code uses the finite difference method to approximate the\n% second derivative in space, and an explicit forward Euler approximation\n% to the first derivative in time.\n%\n% The finite difference form can be written as\n%\n% U(X,T+dt) - U(X,T) ( U(X-dx,T) - 2 U(X,T) + U(X+dx,T) )\n% ------------------ = F(X,T) + k * ------------------------------------\n% dt dx * dx\n%\n% or, assuming we have solved for all values of U at time T, we have\n%\n% U(X,T+dt) = U(X,T) + cfl * ( U(X-dx,T) - 2 U(X,T) + U(X+dx,T) ) + dt * F(X,T) \n%\n% Here \"cfl\" is the Courant-Friedrichs-Loewy coefficient:\n%\n% cfl = k * dt / dx / dx\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 24 January 2012\n%\n% Author:\n% \n% John Burkardt\n%\n% Reference:\n%\n% George Lindfield, John Penny,\n% Numerical Methods Using MATLAB,\n% Second Edition,\n% Prentice Hall, 1999,\n% ISBN: 0-13-012641-1,\n% LC: QA297.P45.\n%\n% Parameters:\n%\n% Input, real K, the heat conductivity coefficient.\n%\n% Input, integer T_NUM, the number of time values, including the initial\n% value.\n%\n% Input, real T_MIN, T_MAX, the minimum and maximum times.\n%\n% Input, integer X_NUM, the number of nodes.\n%\n% Input, real X_MIN, X_MAX, the minimum and maximum spatial coordinates.\n%\n% Output, real CFL, the Courant-Friedrichs-Loewy coefficient.\n%\n x_step = ( x_max - x_min ) / ( x_num - 1 );\n t_step = ( t_max - t_min ) / ( t_num - 1 );\n%\n% Check the CFL condition, print out its value, and quit if it is too large.\n%\n cfl = k * t_step / x_step / x_step;\n\n if ( 0.5 <= cfl )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FD1D_HEAT_EXPLICIT_CFL - Fatal error!\\n' );\n fprintf ( 1, ' CFL condition failed.\\n' );\n fprintf ( 1, ' 0.5 <= K * dT / dX / dX = %f\\n', cfl );\n error ( 'FD1D_HEAT_EXPLICIT_CFL - Fatal error!' );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fd1d_heat_implicit/fd1d_heat_implicit_cfl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.9314625041141347, "lm_q1q2_score": 0.8802271419837373}} {"text": "function [valuesSelected,costVal]=knapsack01DP(v,w,W)\n%%KNAPSACK01DP Solve the 0-1 knapsack problem using dynamic programming.\n% The 0-1 knapsack problem is to find a subset sel of the items in v\n% that solves the optimization problem\n% max_{sel} sum(v(sel))\n% such that sum(w(sel))<=W\n% This can be thought of as fitting the most things in a knapsack if\n% the v's are all 1's, the w's are the sizes of things and W is the\n% capacity of the knapsack.\n%\n%INPUTS: v An nX1 or 1Xn vector of positive real values to maximize.\n% w An nX1 or 1Xn vector of positive integer capacities required for\n% each value.\n% W The positive integer maximum allowable capacity that can be\n% filled.\n%\n%OUTPUTS: valuesSelected The indices of the items in v (and w) that are\n% selected. If the problem is infeasible, then an empty\n% matrix is returned.\n% costVal The sum of the selected items in v. 0 is returned if the\n% problem is infeasible.\n%\n%The knapsack problem is NP-hard. The complexity of this algorithm\n%scaled with W. It is O(n*W) The algorithm is sovled via dynamic\n%programming. A development of the recursion in such a dynamic programming\n%approach is given in Chapter 5.4 of [1]. However, this is a very common\n%method for solving this problem and thus solutions can be found in a\n%number of basic textbooks on algorithms.\n%\n%EXAMPLE:\n% W=7;\n% v=[2.1;3.125;66;4.3;6.2];\n% w=[1;2;3;4;5];\n% [valuesSelected,costVal]=knapsack01DP(v,w,W)\n%One will get vales 3, 2, and 1 selected. \n%\n%REFERENCES:\n%[1] L. A. Wolsey, Integer Programming. New York: Wiley-Interscience, 1998.\n%\n%January 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n \nn=length(v);\n\nV=zeros(n+1,W+1);\nV(0+1,:)=0;\nkeep=zeros(n,W+1);\n\nfor i=1:n\n for wIdx=0:W\n if(wIdx-w(i)>=0)\n VTest=V(i-1+1,wIdx-w(i)+1);\n else\n VTest=-Inf;\n end\n \n if((w(i)<=wIdx)&&(v(i)+VTest)>V(i-1+1,wIdx+1))\n V(i+1,wIdx+1)=v(i)+VTest;\n keep(i,wIdx+1)=1;\n else\n V(i+1,wIdx+1)=V(i-1+1,wIdx+1);\n keep(i,wIdx+1)=0;\n end\n end\nend\n\nK=W;\n\nvaluesSelected=zeros(n,1);\nnumSelected=0;\n\nfor i=n:-1:1\n if(keep(i,K+1)==1)\n numSelected=numSelected+1;\n valuesSelected(numSelected)=i;\n K=K-w(i); \n end\nend\n\nvaluesSelected=valuesSelected(1:numSelected);\n\ncostVal=V(n+1,W+1);\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Assignment_Algorithms/knapsack01DP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611597645271, "lm_q2_score": 0.9161096061456471, "lm_q1q2_score": 0.8797960838294577}} {"text": "function bern = bernstein_poly_ab ( n, a, b, x )\n\n%*****************************************************************************80\n%\n%% BERNSTEIN_POLY_AB evaluates at X the Bernstein polynomials based in [A,B].\n%\n% Formula:\n%\n% BERN(N,I)(X) = [N!/(I!*(N-I)!)] * (B-X)**(N-I) * (X-A)**I / (B-A)**N\n%\n% First values:\n%\n% B(0,0)(X) = 1\n%\n% B(1,0)(X) = ( B-X ) / (B-A)\n% B(1,1)(X) = ( X-A ) / (B-A)\n%\n% B(2,0)(X) = ( (B-X)^2 ) / (B-A)^2\n% B(2,1)(X) = ( 2 * (B-X) * (X-A) ) / (B-A)^2\n% B(2,2)(X) = ( (X-A)^2 ) / (B-A)^2\n%\n% B(3,0)(X) = ( (B-X)^3 ) / (B-A)^3\n% B(3,1)(X) = ( 3 * (B-X)^2 * (X-A) ) / (B-A)^3\n% B(3,2)(X) = ( 3 * (B-X) * (X-A)^2 ) / (B-A)^3\n% B(3,3)(X) = ( (X-A)^3 ) / (B-A)^3\n%\n% B(4,0)(X) = ( (B-X)^4 ) / (B-A)^4\n% B(4,1)(X) = ( 4 * (B-X)^3 * (X-A) ) / (B-A)^4\n% B(4,2)(X) = ( 6 * (B-X)^2 * (X-A)^2 ) / (B-A)^4 \n% B(4,3)(X) = ( 4 * (B-X) * (X-A)^3 ) / (B-A)^4 \n% B(4,4)(X) = ( (X-A)^4 ) / (B-A)^4 \n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 July 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the degree of the Bernstein polynomials to be used.\n% For any N, there is a set of N+1 Bernstein polynomials, each of\n% degree N, which form a basis for polynomials on [A,B].\n%\n% Input, real A, B, the endpoints of the interval on which the\n% polynomials are to be based. A and B should not be equal.\n%\n% Input, real X, the point at which the polynomials are to be evaluated.\n%\n% Output, real BERN(N+1,1), the values of the N+1 Bernstein polynomials at X.\n%\n if ( b == a )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BERNSTEIN_POLY_AB - Fatal error!\\n' );\n fprintf ( 1, ' A = B = %f\\n', a );\n error ( 'BERNSTEIN_POLY_AB - Fatal error!' );\n end\n\n bern = zeros ( n + 1, 1 );\n\n if ( n == 0 )\n \n bern(1) = 1.0;\n \n elseif ( 0 < n )\n \n bern(1) = ( b - x ) / ( b - a );\n bern(2) = ( x - a ) / ( b - a );\n \n for i = 2 : n\n bern(i+1) = ( x - a ) * bern(i) / ( b - a );\n for j = i-1 : -1 : 1\n bern(j+1) = ( ( b - x ) * bern(j+1) + ( x - a ) * bern(j) ) / ( b - a );\n end\n bern(1) = ( b - x ) * bern(1) / ( b - a );\n end\n \n end\n \n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/bernstein_polynomial/bernstein_poly_ab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350252, "lm_q2_score": 0.9124361640485893, "lm_q1q2_score": 0.8793876752135261}} {"text": "function dy = ode_system(t, y, m, b, k)\n\n%*****************************************************************************80\n%\n%% ODE_SYSTEM evaluates the right hand side of the ODE.\n%\n% Discussion:\n%\n% The second order ODE:\n%\n% m * x'' + b * x' + k * x = 0\n%\n% is transformed into a pair of first order ODE's\n% using the variables:\n%\n%\n% y(1) = x,\n% y(2) = x'\n%\n% so that\n%\n% y'(1) = y(2)\n% y'(2) = - ( k / m ) y(1) - ( b / m ) y(2)\n% \n% Modified:\n%\n% 01 March 2010\n%\n% Parameters:\n%\n% Input, real T, the current time.\n%\n% Input, real Y(2), the current solution.\n%\n% Input, real M, B, K, the mass, damping and stiffness constants.\n%\n% Output, real DY(2,1), the right hand sides of the ODE's,\n% returned as a column vector.\n%\n dy(1,1) = y(2);\n dy(2,1) = - ( k / m ) * y(1) - ( b / m ) * y(2);\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/ode_sweep_parfor/ode_system.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9632305318133554, "lm_q2_score": 0.9124361616674906, "lm_q1q2_score": 0.8788863692487138}} {"text": "function [X_norm, mu, sigma] = featureNormalize(X)\n%FEATURENORMALIZE Normalizes the features in X \n% FEATURENORMALIZE(X) returns a normalized version of X where\n% the mean value of each feature is 0 and the standard deviation\n% is 1. This is often a good preprocessing step to do when\n% working with learning algorithms.\n\n% You need to set these values correctly\nX_norm = X;\nmu = zeros(1, size(X, 2));\nsigma = zeros(1, size(X, 2));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: First, for each feature dimension, compute the mean\n% of the feature and subtract it from the dataset,\n% storing the mean value in mu. Next, compute the \n% standard deviation of each feature and divide\n% each feature by it's standard deviation, storing\n% the standard deviation in sigma. \n%\n% Note that X is a matrix where each column is a \n% feature and each row is an example. You need \n% to perform the normalization separately for \n% each feature. \n%\n% Hint: You might find the 'mean' and 'std' functions useful.\n% \n\nN = size(X,2); % number of features\n\nfor i=1:N,\n feature = X(:,i); % get feature\n mu(i) = mean(feature); % mean\n sigma(i) = std(feature); % standard deviation\n \n % normalize\n X_norm(:,i) = (feature - mu(i)) / sigma(i);\nend\n\n% ============================================================\n\nend\n", "meta": {"author": "rmarquis", "repo": "coursera-machinelearning", "sha": "5b165935e6fecfab977b2af1b0e9c588c75ca8f4", "save_path": "github-repos/MATLAB/rmarquis-coursera-machinelearning", "path": "github-repos/MATLAB/rmarquis-coursera-machinelearning/coursera-machinelearning-5b165935e6fecfab977b2af1b0e9c588c75ca8f4/homework/mlclass-ex1/featureNormalize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750373915658, "lm_q2_score": 0.921921831100897, "lm_q1q2_score": 0.8788450680148084}} {"text": "classdef WeibullD\n%%WEIBULLD Functions to handle the Weibull distribution.\n%Implemented methods are: mean, var, PDF, CDF, invCDF, rand, entropy\n%\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nmethods(Static)\n \nfunction val=mean(lambda,k)\n%%MEAN Obtain the mean of the Weibull distribution for given scale and\n% shape parameters.\n%\n%INPUTS: lambda The scale parameter of the distribution. lambda>0.\n% k The shape parameter of the distribution. k>0.\n%\n%OUTPUTS:val The mean of the Weibull distribution.\n%\n%The mean of the Weibull distribution is given on the inside of the front\n%cover of [1].\n%\n%EXAMPLE:\n%We verify the computed mean by comparing it to the sample mean.\n% lambda=2.2;\n% k=3.1;\n% meanVal=WeibullD.mean(lambda,k)\n% numSamp=1e6;\n% sampMeanVal=mean(WeibullD.rand([numSamp,1],lambda,k))\n%One will find both values are about 1.967\n%\n%REFERENCES:\n%[1] A. Papoulis and S. U. Pillai, Probability, Random Variables and\n% Stochastic Processes, 4th ed. Boston: McGraw Hill, 2002.\n%\n%October 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=lambda*gamma(1+1/k); \nend\n\nfunction val=var(lambda,k)\n%%VAR Obtain the variance of the Weibull distribution for given scale and\n% shape parameters/\n%\n%INPUTS: lambda The scale parameter of the distribution. lambda>0.\n% k The shape parameter of the distribution. k>0.\n%\n%OUTPUTS:val The variance of the Weibull distribution. \n%\n%The variance of the Weibull distribution is given on the inside of the front\n%cover of [1].\n%\n%EXAMPLE:\n%We verify the computed variance by comparing it to the sample variance.\n% lambda=2.2;\n% k=3.1;\n% varVal=WeibullD.var(lambda,k)\n% numSamp=1e6;\n% sampVarVal=var(WeibullD.rand([numSamp,1],lambda,k))\n%One will find both values are about 0.4821\n%\n%REFERENCES:\n%[1] A. Papoulis and S. U. Pillai, Probability, Random Variables and\n% Stochastic Processes, 4th ed. Boston: McGraw Hill, 2002.\n% \n%October 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=lambda^2*(gamma(1+2/k)-(gamma(1+1/k))^2); \nend\n\nfunction val=PDF(x,lambda,k)\n%%PDF Evaluate the probability density function (PDF) of the Weibull\n% distribution at one or more points.\n%\n%INPUTS: x The point(s) at which the Weibull PDF is to be evaluated. x>=0\n% for nonzero PDF values.\n% lambda The scale parameter of the distribution. lambda>0.\n% k The shape parameter of the distribution. k>0.\n%\n%OUTPUTS: val The value(s) of the Weibull PDF.\n%\n%The PDF of the Weibull distribution is given on the inside of the front\n%cover of [1].\n%\n%EXAMPLE:\n%Here, we validate the PDF by generating random samples and comparing the\n%PDF plot with a histogram of the random samples.\n% lambda=2.2;\n% k=3.1;\n% numSamples=1e5;\n% figure(1)\n% clf\n% histogram(WeibullD.rand([numSamples,1],lambda,k),'Normalization','pdf')\n% hold on\n% numPoints=1000;\n% x=linspace(0,6,numPoints);\n% vals=WeibullD.PDF(x,lambda,k);\n% plot(x,vals,'linewidth',2)\n% h1=xlabel('x');\n% h2=ylabel('PDF(x)');\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%One will see that the histogram matches well with the plot.\n%\n%REFERENCES:\n%[1] A. Papoulis and S. U. Pillai, Probability, Random Variables and\n% Stochastic Processes, 4th ed. Boston: McGraw Hill, 2002.\n%\n%October 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=(k/lambda)*(x/lambda).^(k-1).*exp(-(x/lambda).^k);\n val(x<0)=0;\nend\n\nfunction val=CDF(x,lambda,k)\n%%CDF Evaluate the cumulative distribution function (CDF) of the Weibull\n% distribution at one or more desired points.\n%\n%INPUTS: x The point(s) at which the Weibull CDF is to be evaluated.\n% lambda The scale parameter of the distribution. lambda>0.\n% k The shape parameter of the distribution. k>0.\n%\n%OUTPUTS: val The value(s) of the Weibull CDF.\n%\n%The CDF is the integral from 0 to x of the PDF. The Weibull PDF is\n%fairely simple and the integral is not hard. The Weibull PDF is given on\n%the inside of the front cover of [1].\n%\n%EXAMPLE:\n%We validate the CDF value by comparing it to a value computed from random\n%samples.\n% lambda=2.2;\n% k=3.1;\n% x=2;\n% numSamples=1e5;\n% prob=WeibullD.CDF(x,lambda,k)\n% probSamp=mean(WeibullD.rand([numSamples,1],lambda,k)<=x)\n%One will see that both values are about 0.5249.\n%\n%REFERENCES:\n%[1] A. Papoulis and S. U. Pillai, Probability, Random Variables and\n% Stochastic Processes, 4th ed. Boston: McGraw Hill, 2002.\n%\n%October 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=1-exp(-(x/lambda).^k);\n val(x<0)=0;\nend\n\nfunction val=invCDF(prob,lambda,k)\n%%INVCDF Evaluate the inverse of the cumulative distribution function (CDF)\n% of the Weibull distribution.\n%\n%INPUTS: prob The probability or probabilities (0<=prob<=1) at which the \n% argument of the CDF is desired.\n% lambda The scale parameter of the distribution. lambda>0.\n% k The shape parameter of the distribution. k>0.\n%\n%OUTPUTS: val The argument(s) of the CDF that would give the probability or\n% probabilities in prob.\n%\n%The CDF of the Weibull distribution can be easily algebraicly inverted,\n%which is what is done here. The Weibull CDF is the integral from 0 to x of\n%the Weibull PDF, which is given on the inside of the front cover of [1].\n%\n%EXAMPLE:\n%Here, we validate the inverse CDF by showing it to be the inverse of the\n%CDF.\n% lambda=2.2;\n% k=3.1;\n% x=2;\n% xBack=WeibullD.invCDF(WeibullD.CDF(x,lambda,k),lambda,k)\n%One will see that xBack is the same as x.\n%\n%REFERENCES:\n%[1] A. Papoulis and S. U. Pillai, Probability, Random Variables and\n% Stochastic Processes, 4th ed. Boston: McGraw Hill, 2002.\n%\n%October 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nval=lambda*(-log(1-prob)).^(1/k);\n\nend\n \nfunction vals=rand(N,lambda,k,lowerBound)\n%%RAND Generate Weibull distributed random variables with the given\n% parameters. This function can also be used to generate random\n% variable from a Weibull distribution that is clipped so that only\n% values above a certain threshold are generated. That can be useful\n% when performing simulations and generating false alarms that are all\n% above a given threshold.\n%\n%INPUTS: N If N is a scalar, then rand returns an NXN matrix of random\n% variables. If N=[M,N1] is a two-element row vector, then rand\n% returns an MXN1 matrix of random variables.\n% lambda The scale parameter of the distribution. lambda>0.\n% k The shape parameter of the distribution. k>0.\n% lowerBound An optional parameter specifying a lower bound below which\n% none of the randomly generated values should go. If this is\n% omitted or an empty matrix is passed, then lowerBound=0 and a\n% non-clipped Weibull distribution is used.\n%\n%OUTPUTS: vals A matrix whose dimensions are determined by N of the\n% generated Weibull random variables.\n%\n%This is an implementation of the inverse transform algorithm of Chapter\n%5.1 of [1]. To clip values to only being above lowerBound, the CDF value\n%of the lower bound is determined and the uniform random variables as used\n%in the inverse transform algorithm are all only generated above the\n%threshold.\n%\n%REFERENCES:\n%[1] S. M. Ross, Simulation, Ed. 4, Amsterdam: Elsevier, 2006.\n% \n%October 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n if(isscalar(N))\n dims=[N, N];\n else\n dims=N;\n end\n\n if(nargin<4||isempty(lowerBound)||lowerBound<=0)\n %If we are evaluating a standard Weibull-distributed random\n %variable rather than one that has been clipped to a particular\n %region.\n U=rand(dims);\n vals=WeibullD.invCDF(U,lambda,k);\n else\n %Only generate Weibull random variables that are >=lowerBound.\n p=WeibullD.CDF(lowerBound,lambda,k);\n %Generate a uniform random variable between p and 1.\n U=p+(1-p)*rand(dims);\n vals=WeibullD.invCDF(U,lambda,k);\n end\nend\n\nfunction entropyVal=entropy(lambda,k)\n%%ENTROPY Obtain the differential entropy of the Weibull distribution\n% given in nats. The differential entropy of a continuous\n% distribution is entropy=-int_x p(x)*log(p(x)) dx where the\n% integral is over all values of x. Units of nats mean that the\n% natural logarithm is used in the definition. Unlike the Shannon\n% entropy for discrete variables, the differential entropy of\n% continuous variables can be both positive and negative.\n%\n%INPUTS: lambda The scale parameter of the distribution. lambda>0.\n% k The shape parameter of the distribution. k>0.\n%\n%OUTPUTS: entropyVal The value of the differential entropy in nats.\n%\n%Differential entropy is defined in Chapter 8 of [1].\n%\n%REFERENCES:\n%[1] T. M. Cover and J. A. Thomas, Elements of Information Theory, 2nd ed.\n% Hoboken, NJ: Wiley-Interscience, 2006.\n%\n%April 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n gammaVal=-psi(1);\n entropyVal=gammaVal*(1-1/k)+log(lambda/k)+1;\nend\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/Distributions/WeibullD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514736, "lm_q2_score": 0.9252299643080208, "lm_q1q2_score": 0.8786625575421916}} {"text": "function [nodes,weights]=gaussquadrule(n,class,alpha,beta)\n% gaussquadrule: generate a gauss quadrature rule using associated orthogonal polynomials\n% usage: [nodes,weights]=gaussquadrule(n,class,alpha,beta)\n%\n% arguments:\n% n - number of nodes in the guassian quadrature\n% \n% class - (optional) - class of gaussian quadrature rule\n% any one of { 'Legendre' 'Laguerre' 'Hermite',\n% 'Jacobi', '1Cheby', '2Cheby' }. '1cheby' refers\n% of course to a first kind Gauss-Chebychev rule.\n% \n% Capitalization is ignored and class names\n% may be shortened as long as they are left\n% unambiguous. These are all minimally valid:\n% {'le', 'la', 'h' 'j' '1' '2'}\n% \n% DEFAULT == 'Legendre'\n%\n% The nominal integration intervals are:\n% \n% 'Legendre' --> [ -1, 1]\n% 'Laguerre' --> [ 0,inf]\n% 'Hermite' --> [-inf,inf]\n% 'Jacobi' --> [ -1, 1]\n% '1Cheby' --> [ -1, 1]\n% '2Cheby' --> [ -1, 1]\n% \n% See Abramowitz & Stegun for in-depth information\n% \n% alpha, beta - (optional) parameters for the rules\n% DEFAULT == 0 for both\n%\n% alpha and beta are ignored for the 'legendre',\n% 'hermite', 'cheby1' and 'cheby2' rules. Only\n% alpha is used for the Laguerre quadrature rules.\n% \n% arguments (output)\n% nodes - x values for integration\n% weights - integration weights\n\n% default parameters\nif (nargin<2) || isempty(class)\n class='legendre';\nend\n\nclass=lower(class);\nvalc={'legendre' 'laguerre' 'hermite' 'jacobi' 'cheby1' ...\n 'cheby2' '1chebychev' '2chebychev'};\nind=strmatch(class,valc);\nif isempty(ind)\n error 'Invalid quadrature class'\nelseif length(ind)>1\n error 'Ambiguous quadrature class'\nelse\n class=valc{ind};\nend\n\nif (nargin<4) || isempty(beta)\n beta=0;\nend\nif (nargin<3) || isempty(alpha);\n alpha=0;\nend\n\n% generate the appropriate orthogonal sympolys.\n% use the sympoly objects for this. orthpoly\n% creates them.\npn = orthpoly(n,class,alpha,beta);\npnp1 = orthpoly(n+1,class,alpha,beta);\n\nnodes=roots(pn);\nnodes=sort(nodes');\n\npnprime=diff(pn);\nweights=zeros(1,n);\nfor i=1:n\n weights(i)=-(pnp1.Coefficient(end))/(pn.Coefficient(end))./ ...\n double(subs(pnp1,'x',nodes(i)))./ ...\n double(subs(pnprime,'x',nodes(i)));\nend\n\n% norm\nswitch class\n case 'legendre'\n weights=weights*(2/(2*n+1));\n case 'hermite'\n weights=sqrt(pi)*(2^n)*(gamma(n+1))*weights;\n case 'laguerre'\n weights=weights*gamma(n+alpha+1)/gamma(n+1);\n case 'jacobi'\n weights=weights*(2/sum(weights));\n nodes=(nodes+1)/2;\n case {'cheby1' '1chebychev'}\n weights=weights*(2/sum(weights));\n case {'cheby2' '2chebychev'}\n weights=weights*(2/sum(weights));\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9577-symbolic-polynomial-manipulation/SymbolicPolynomials/gaussquadrule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611654370415, "lm_q2_score": 0.9149009532527358, "lm_q1q2_score": 0.8786353457252576}} {"text": "function [df d_arr] = richardson_based_derivative(eq, x0, n, h)\n% July 1, 2013 by Ehsan Behnam.\n% [df d_arr] = richardson_based_derivative(...) \n% computes the derative of the equation \"eq\" % at \"x0\" \n% using \"n\" iterations of Richardson extrapolation.\n% \"h\" specifies the initial differential increment/decrement around x0\n% (i.e. f(x+h) or f(x-h)). \n% A couple of notes: \n% 1) \"eq\" can be any string in the form of f(x). Note that it should be \n% computable in Matlab so for example, use eq = 'exp(x)' instead of 'e^x'.\n% 2) No matter of what is \"h\" at each step h <- h/2. Therefore if you want\n% to compare the accuracy of this method to other methods (e.g. Tyler's\n% series), you need to adjust the number of required steps properly. \n\n% The first output \"df\" is the d(eq(x))/dx |@(x = x0). Regarding the \n% educational purposes for producing the whole table, the function also \n% outputs the whole array iteratively generated as the function progresses.\n\n% Basic usage example: \n% eq = 'x^3*exp(-x)';\n% df = richardson_based_derivative(eq, 0.1, 10);\n% Finding the difference between \"df\" and the Matlab output ...\n% disp(subs(diff(sym(eq)), 0.1) - df);\n% It will show \"-4.6263e-07\" on the workspace.\n\nif (nargin < 2 || nargin > 4)\n help('richardson_based_derivative');\n df = '';\n d_arr = '';\n return;\nend\n\nif (nargin == 2)\n h = 1/2;\n n = 5;\nend\n\nif (nargin == 3)\n h = 1/2;\nend\n\nfx = sym(eq);\n\n%Initialization:\nd_arr = zeros(n);\nfor i = 1:n\n d_arr(i, 1) = subs(fx, 'x', x0 + h) - subs(fx, 'x', x0 - h);\n d_arr(i, 1) = d_arr(i, 1) / (2 * h);\n % Iteratively computing the coefficients:\n for j = 2:i\n d_arr(i, j) = d_arr(i, j - 1) + (d_arr(i, j - 1) - ...\n d_arr(i - 1, j - 1)) / (4 ^j -1);\n end\n % next iteration \"h\":\n h = h/2;\nend\ndf = d_arr(end, end);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/42471-richardson-extrapolation/richardson_based_derivative.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.921921830028282, "lm_q1q2_score": 0.8781988822377305}} {"text": "function kSum=KroneckerSum(A,B)\n%KRONECKERSUM Find the Kronecker sum of an nXn matrix A and an mXm matrix\n% B. This is defined as kron(A,eye(m))+kron(eye(n),B)\n%\n%INPUTS: A An nXn matrix.\n% B An mXm matrix.\n%\n%OUTPUTS: kSum The (n*m)X(n*m) Kronecker sum of A and B.\n%\n%The Kronecker sum arises in numerous matrix identities. For example, it is\n%used in [1] for expressions for eigenvectors. \n%\n%REFERENCES:\n%[1] J. W. Brewer, \"Kronecker products and matrix calculus in systems\n% theory,\" IEEE Transactions on Circuits and Systems, vol. CAS-25, no.\n% 9, pp. 772-781, Sep. 1978.\n%\n%December 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nn=size(A,1);\nm=size(B,1);\n\nkSum=kron(A,eye(m))+kron(eye(n),B);\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Basic_Matrix_Operations/KroneckerSum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9585377272885904, "lm_q2_score": 0.9161096164524095, "lm_q1q2_score": 0.8781256297015149}} {"text": "function [X_norm, mu, sigma] = featureNormalize(X)\n%FEATURENORMALIZE Normalizes the features in X \n% FEATURENORMALIZE(X) returns a normalized version of X where\n% the mean value of each feature is 0 and the standard deviation\n% is 1. This is often a good preprocessing step to do when\n% working with learning algorithms.\n\n% You need to set these values correctly\nX_norm = X;\nmu = zeros(1, size(X, 2));\nsigma = zeros(1, size(X, 2));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: First, for each feature dimension, compute the mean\n% of the feature and subtract it from the dataset,\n% storing the mean value in mu. Next, compute the \n% standard deviation of each feature and divide\n% each feature by it's standard deviation, storing\n% the standard deviation in sigma. \n%\n% Note that X is a matrix where each column is a \n% feature and each row is an example. You need \n% to perform the normalization separately for \n% each feature. \n%\n% Hint: You might find the 'mean' and 'std' functions useful.\n% \n\nmu = mean(X);\nsigma = std(X);\nX_norm = (X - mu) ./ sigma;\n#X_norm = (X - min(X)) ./ (max(X) - min(X))\n\n\n\n\n% ============================================================\n\nend\n", "meta": {"author": "JY-112553", "repo": "machine-learning", "sha": "db9c6e5a5175739821acd97787453472b8f46cac", "save_path": "github-repos/MATLAB/JY-112553-machine-learning", "path": "github-repos/MATLAB/JY-112553-machine-learning/machine-learning-db9c6e5a5175739821acd97787453472b8f46cac/machine-learning-ex1/ex1/featureNormalize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541659378682, "lm_q2_score": 0.9324533135530546, "lm_q1q2_score": 0.8780485472498032}} {"text": "function [ x, det ] = r8mat_solve_3d ( a, b, det, x )\n\n%*****************************************************************************80\n%\n%% R8MAT_SOLVE_3D solves a 3 by 3 linear system using Cramer's rule.\n%\n% Discussion:\n%\n% If the determinant DET is returned as zero, then the matrix A is\n% singular, and does not have an inverse. In that case, X is\n% returned as the [] vector.\n%\n% If DET is nonzero, then its value is roughly an estimate\n% of how nonsingular the matrix A is.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 December 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A(3,3), the matrix.\n%\n% Input, real B(3), the right hand side.\n%\n% Output, real DET, the determinant of the matrix A.\n%\n% Output, real X(3), the solution of the system,\n% if DET is nonzero.\n%\n\n%\n% Compute the determinant.\n%\n det = a(1,1) * ( a(2,2) * a(3,3) - a(2,3) * a(3,2) ) ...\n + a(1,2) * ( a(2,3) * a(3,1) - a(2,1) * a(3,3) ) ...\n + a(1,3) * ( a(2,1) * a(3,2) - a(2,2) * a(3,1) );\n%\n% If the determinant is zero, bail out.\n%\n if ( det == 0.0 )\n x = [];\n return\n end\n%\n% Compute the solution.\n%\n x(1) = ( ( a(2,2) * a(3,3) - a(2,3) * a(3,2) ) * b(1) ...\n - ( a(1,2) * a(3,3) - a(1,3) * a(3,2) ) * b(2) ...\n + ( a(1,2) * a(2,3) - a(1,3) * a(2,2) ) * b(3) ) / det;\n\n x(2) = ( - ( a(2,1) * a(3,3) - a(2,3) * a(3,1) ) * b(1) ...\n + ( a(1,1) * a(3,3) - a(1,3) * a(3,1) ) * b(2) ...\n - ( a(1,1) * a(2,3) - a(1,3) * a(2,1) ) * b(3) ) / det;\n\n x(3) = ( ( a(2,1) * a(3,2) - a(2,2) * a(3,1) ) * b(1) ...\n - ( a(1,1) * a(3,2) - a(1,2) * a(3,1) ) * b(2) ...\n + ( a(1,1) * a(2,2) - a(1,2) * a(2,1) ) * b(3) ) / det;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8mat_solve_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627597, "lm_q2_score": 0.9230391605990604, "lm_q1q2_score": 0.8779415189092623}} {"text": "function area = triangleArea(pt1, pt2, pt3)\n%TRIANGLEAREA Signed area of a triangle\n%\n% AREA = triangleArea(P1, P2, P3)\n% Computes area of the triangle whose vertices are given by P1, P2 and\n% P3. Each vertex is a 1-by-2 row vector. \n%\n% AREA = triangleArea(PTS)\n% Concatenates vertex coordinates in a 3-by-2 array. Each row of the\n% array contains coordinates of one vertex.\n%\n%\n% Example\n% % Compute area of a Counter-Clockwise (CCW) oriented triangle\n% triangleArea([10 10], [30 10], [10 40])\n% ans = \n% 300\n%\n% % Compute area of a Clockwise (CW) oriented triangle\n% triangleArea([10 40], [30 10], [10 10])\n% ans = \n% -300\n%\n% See also\n% polygonArea, triangleArea3d\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2011-08-23, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n% if data is given as one array, split vertices\nif nargin == 1\n pt2 = pt1(2,:);\n pt3 = pt1(3,:);\n pt1 = pt1(1,:);\nend\n\n% compute individual vectors\nv12 = bsxfun(@minus, pt2, pt1);\nv13 = bsxfun(@minus, pt3, pt1);\n\n% compute area from cross product\narea = (v13(:,2) .* v12(:,1) - v13(:,1) .* v12(:,2)) / 2;\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom2d/triangleArea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9546474168650673, "lm_q2_score": 0.9196425289753969, "lm_q1q2_score": 0.8779343647256204}} {"text": "% Figure 6.19: Polynomial fitting\n% Section 6.5.3\n% Boyd & Vandenberghe \"Convex Optimization\"\n% Original by Lieven Vandenberghe\n% Adapted for CVX by Joelle Skaf - 10/03/05\n% (a figure is generated)\n%\n% Given data u_1,...,u_m and v_1,...,v_m in R, the goal is to fit to the\n% data a polynomial of the form\n% p(u) = x_1 + x_2*u + ... + x_n*u^{n-1}\n% i.e. solve the problem: minimize ||Ax - v||\n% where A is the Vandermonde matrix s.t. Aij = u_i^{j-1}\n% Two cases are considered: L2-norm and Linfty-norm\n\n% Input data\nn=6;\nm=40;\nrandn('state',0);\n% generate 50 ponts ui, vi\nu = linspace(-1,1,m);\nv = 1./(5+40*u.^2) + 0.1*u.^3 + 0.01*randn(1,m);\n\n\n% LS fit polynomial x_1 + x_2*u + ... + x_n*u^(n-1) to (ui,vi)\nfprintf(1,'Computing optimal polynomial in the case of L2-norm...');\n\nA = vander(u');\nA = A(:,m-n+[1:n]); % last n columns of A\nx = A\\(v'); % coefficients of the polynomial in the following\n % order: x = [x_n x_(n-1) ... x_2 x_1]'\n\nfprintf(1,'Done! \\n');\n\n% L-infty fit\nfprintf(1,'Computing optimal polynomial in the case of Linfty-norm...');\n\ncvx_begin quiet\n variable x1(n)\n minimize (norm(A*x1 - v', inf))\ncvx_end\n\nfprintf(1,'Done! \\n');\n\n% generates 1000 points in [-1,1]\nu2 = linspace(-1.1,1.1,1000);\n\n% evaluate the interpolating polynomial using Horner's method\nvpol = x(1)*ones(1,1000);\nvpoll1 = x1(1)*ones(1,1000);\nfor i = 2:n\n vpol = vpol.*u2 + x(i);\n vpoll1 = vpoll1.*u2 + x1(i);\nend;\n\nfigure\n% plot function and interpolating polynomial\nplot(u2, vpol,'-', u, v, 'o', u2, vpoll1,'--');\nxlabel('u');\nylabel('p(u)');\ntitle('Fitting of data points with two polynomials of degree 5');\nlegend('L_2 norm','data points','L_{\\infty} norm', 'Location','Best');\n% print -deps polapprox.eps\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/cvxbook/Ch06_approx_fitting/fig6_19.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263736, "lm_q2_score": 0.9273632896242074, "lm_q1q2_score": 0.8778390076126306}} {"text": "function circle = makeCartCircle(radius, num_points, center_pos, arc_angle, plot_circle)\n%MAKECARTCIRCLE Create a 2D Cartesian circle or arc.\n%\n% DESCRIPTION:\n% MakeCartCircle creates a 2 x num_points array of the Cartesian\n% coordinates of points evenly distributed over a circle or arc (if\n% arc_angle is given).\n%\n% USAGE:\n% circle = makeCartCircle(radius, num_points)\n% circle = makeCartCircle(radius, num_points, center_pos)\n% circle = makeCartCircle(radius, num_points, center_pos, arc_angle)\n% circle = makeCartCircle(radius, num_points, center_pos, arc_angle, plot_circle)\n%\n% INPUTS:\n% radius - circle radius [m]\n% num_points - number of points in the circle\n%\n% OPTIONAL INPUTS:\n% center_pos - [x, y] position of the circle center [m] \n% (default = [0, 0])\n% arc_angle - arc angle for incomplete circle [radians]\n% (default = 2*pi)\n% plot_circle - Boolean controlling whether the Cartesian points\n% are plotted (default = false)\n%\n% OUTPUTS:\n% circle - 2 x num_points array of Cartesian coordinates\n%\n% ABOUT:\n% author - Bradley Treeby\n% date - 5th June 2009\n% last update - 20th March 2014\n% \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n%\n% See also cart2grid, makeCartSphere, makeCircle\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see .\n\n% check for plot_circle input\nif nargin < 5 || isempty(plot_circle)\n plot_circle = false;\nend\n\n% check for arc_angle input\nif nargin < 4 || isempty(arc_angle)\n arc_angle = 2*pi;\n full_circle = true;\nelseif arc_angle == 2*pi;\n full_circle = true;\nelse\n full_circle = false;\nend\n\n% check for center_pos input\nif nargin < 3 || isempty(center_pos)\n cx = 0;\n cy = 0;\nelse\n cx = center_pos(1);\n cy = center_pos(2);\nend\n\n% ensure there is only a total of num_points including the endpoints when\n% arc_angle is not equal to 2*pi\nif ~full_circle\n num_points = num_points - 1;\nend\n\n% create angles\nangles = (0:(num_points))*arc_angle/(num_points) + pi/2;\n\n% discard repeated final point if arc_angle is equal to 2*pi\nif full_circle\n angles = angles(1:end-1);\nend\n\n% create cartesian grid\n% circle = flipud([radius*cos(angles); radius*sin(-angles)]); % B.0.3\ncircle = ([radius*cos(angles); radius*sin(-angles)]); % B.0.4\n\n% offset if needed\ncircle(1, :) = circle(1, :) + cx;\ncircle(2, :) = circle(2, :) + cy;\n\n% plot results\nif plot_circle\n \n % select suitable axis scaling factor\n [x_sc, scale, prefix] = scaleSI(max(abs(circle(:)))); \n \n % create the figure\n figure;\n plot(circle(2,:)*scale, circle(1,:)*scale, 'b.');\n set(gca, 'YDir', 'reverse');\n xlabel(['y-position [' prefix 'm]']);\n ylabel(['x-position [' prefix 'm]']);\n axis equal;\n \nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/makeCartCircle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750453562491, "lm_q2_score": 0.9207896807817186, "lm_q1q2_score": 0.8777658247107589}} {"text": "function [R_sq]=R_squared(y,yf) \n\n% function [R_squared]=R_squared(y,yf) \n% ------------------------------------------------------------------------\n% This function calculates the coefficient of determination (R-Squared) for\n% the (e.g. measurement) data |y| and the data |yf| (e.g. a model fit). \n% NaN entries in either inputs are ignored. \n%\n%\n% Change log: \n% 2008/10/05\n% 2019/06/26 Updated description\n% 2019/06/26 Updated handling of NaN entries in the data\n% ------------------------------------------------------------------------\n\n%%\n\nL=~isnan(y) & ~isnan(yf); %Logic for non-NaN entries\n\ny_bar=mean(y(L)); %Mean of y\nSS_err=sum((y(L)-yf(L)).^2); %Sum of differences Of y with yf\nSS_tot=sum((y(L)-y_bar).^2); %Sum of differences of y with mean\nR_sq=1-(SS_err./SS_tot); %R-squared value\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/R_squared.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633822, "lm_q2_score": 0.9173026573249612, "lm_q1q2_score": 0.8775230926135856}} {"text": "function u2 = fd1d_wave_start ( x_num, x_vec, t, t_delta, alpha, u_x1, u_x2, ...\n ut_t1, u1 )\n\n%*****************************************************************************80\n%\n%% FD1D_WAVE_START takes the first step for the wave equation.\n%\n% Discussion:\n%\n% This program solves the 1D wave equation of the form:\n%\n% Utt = c^2 Uxx\n%\n% over the spatial interval [X1,X2] and time interval [T1,T2],\n% with initial conditions:\n%\n% U(T1,X) = U_T1(X),\n% Ut(T1,X) = UT_T1(X),\n%\n% and boundary conditions of Dirichlet type:\n%\n% U(T,X1) = U_X1(T),\n% U(T,X2) = U_X2(T).\n%\n% The value C represents the propagation speed of waves.\n%\n% The program uses the finite difference method, and marches\n% forward in time, solving for all the values of U at the next\n% time step by using the values known at the previous two time steps.\n%\n% Central differences may be used to approximate both the time\n% and space derivatives in the original differential equation.\n%\n% Thus, assuming we have available the approximated values of U\n% at the current and previous times, we may write a discretized\n% version of the wave equation as follows:\n%\n% Uxx(T,X) = ( U(T, X+dX) - 2 U(T,X) + U(T, X-dX) ) / dX^2\n% Utt(T,X) = ( U(T+dt,X ) - 2 U(T,X) + U(T-dt,X ) ) / dT^2\n%\n% If we multiply the first term by C^2 and solve for the single\n% unknown value U(T+dt,X), we have:\n%\n% U(T+dT,X) = ( C^2 * dT^2 / dX^2 ) * U(T, X+dX)\n% + 2 * ( 1 - C^2 * dT^2 / dX^2 ) * U(T, X )\n% + ( C^2 * dT^2 / dX^2 ) * U(T, X-dX)\n% - U(T-dT,X )\n%\n% (Equation to advance from time T to time T+dT, except for FIRST step!)\n%\n% However, on the very first step, we only have the values of U\n% for the initial time, but not for the previous time step.\n% In that case, we use the initial condition information for dUdT\n% which can be approximated by a central difference that involves\n% U(T+dT,X) and U(T-dT,X):\n%\n% dU/dT(T,X) = ( U(T+dT,X) - U(T-dT,X) ) / ( 2 * dT )\n%\n% and so we can estimate U(T-dT,X) as\n%\n% U(T-dT,X) = U(T+dT,X) - 2 * dT * dU/dT(T,X)\n%\n% If we replace the \"missing\" value of U(T-dT,X) by the known values\n% on the right hand side, we now have U(T+dT,X) on both sides of the\n% equation, so we have to rearrange to get the formula we use\n% for just the first time step:\n%\n% U(T+dT,X) = 1/2 * ( C^2 * dT^2 / dX^2 ) * U(T, X+dX)\n% + ( 1 - C^2 * dT^2 / dX^2 ) * U(T, X )\n% + 1/2 * ( C^2 * dT^2 / dX^2 ) * U(T, X-dX)\n% + dT * dU/dT(T, X )\n%\n% (Equation to advance from time T to time T+dT for FIRST step.)\n%\n% It should be clear now that the quantity ALPHA = C * DT / DX will affect\n% the stability of the calculation. If it is greater than 1, then\n% the middle coefficient 1-C^2 DT^2 / DX^2 is negative, and the\n% sum of the magnitudes of the three coefficients becomes unbounded.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 January 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% George Lindfield, John Penny,\n% Numerical Methods Using MATLAB,\n% Second Edition,\n% Prentice Hall, 1999,\n% ISBN: 0-13-012641-1,\n% LC: QA297.P45.\n%\n% Parameters:\n%\n% Input, integer X_NUM, the number of nodes in the X direction.\n%\n% Input, real X_VEC(X_NUM), the spatial coordinates of the nodes.\n%\n% Input, real T, the time after the first step has been taken.\n% In other words, T = T1 + T_DELTA.\n%\n% Input, real T_DELTA, the time step.\n%\n% Input, real ALPHA, the stability coefficient, computed by FD1D_WAVE_ALPHA.\n%\n% Input, real U_X1(T), U_X2(T), functions for the left and right boundary \n% conditions.\n%\n% Input, real UT_T1(X), the function that evaluates dUdT at the initial time.\n%\n% Input, real U1(X_NUM), the initial condition.\n%\n% Output, real U2(X_NUM), the solution at the first time step.\n%\n ut = ut_t1 ( x_num, x_vec );\n\n u2 = zeros ( 1, x_num );\n\n u2(1) = u_x1 ( t );\n u2(2:x_num-1) = alpha^2 * u1(3:x_num) / 2 ...\n + ( 1 - alpha^2 ) * u1(2:x_num-1) ...\n + alpha^2 * u1(1:x_num-2) / 2 ...\n + t_delta * ut(2:x_num-1);\n u2(x_num) = u_x2 ( t );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fd1d_wave/fd1d_wave_start.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338090839607, "lm_q2_score": 0.91243616285804, "lm_q1q2_score": 0.8773382192188443}} {"text": "function Area=unitVectors2SpherTriangArea(u,r)\n%%UNITVECTORS2SPHERTRIANGAREA Given unit vectors pointing from the center\n% of a 3D sphere to three points on the sphere, as well as the radius\n% of the sphere, determine the surface area of a spherical triangle.\n%\n%INPUTS: u A 3X3 matrix such that u(:,i) is the ith unit vector pointing\n% from the center of the sphere to the surface of the sphere.\n% r The scalar radius of the sphere. If this is omitted or an empty\n% matrix is passed, the default of 1 is used.\n%\n%OUTPUTS: Area The area of the specified triangle on the surface of a\n% sphere of radius r.\n%\n%Equation 1 in [1] is implemented. The absolute value of the atan function\n%is taken so that the result is always positive.\n%\n%EXAMPLE:\n%We find the surface area of a quadrant of a unit sphere. Since the surface\n%area of an entire sphere is 4*pi*r^2, the area of a quadrant will be pi/2.\n%The relative error is zero.\n% u=[[1;0;0],[0;1;0],[0;0;1]];\n% r=1;\n% Area=unitVectors2SpherTriangArea(u,r);\n% trueArea=pi/2;\n% RelErr=(Area-trueArea)./trueArea\n%\n%REFERENCES:\n% [1] F. Eriksson, \"On the measure of solid angles,\" Mathematics Magazine,\n% vol. 63, no. 3, pp. 184-187, 1990.\n%\n%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(r))\n r=1;\nend\n\na=u(:,1);\nb=u(:,2);\nc=u(:,3);\n\nArea=2*r^2*abs(atan(dot(a,cross(b,c))/(1+dot(b,c)+dot(c,a)+dot(a,b))));\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Geometry/unitVectors2SpherTriangArea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360067, "lm_q2_score": 0.9184802479302793, "lm_q1q2_score": 0.876824799683609}} {"text": "function val=intCosPow(u,n)\n%%INTCOSPOWER Evaluate the integral of cos(u)^n du. A definite integral\n% can be evaluated, or an indefinite integral (with a\n% particular additive constant).\n%\n%INPUTS: u A 2XN (for definite integral) or a 1XN (for indefinite\n% integrals) set of N points. For definite integrals, u(1,:) are\n% the real lower bounds and u(2,:) are the real upper bounds. For\n% indefinite integrals, the integral is evaluated at the points in\n% u. The values in u should be real.\n% n The positive integer exponent of the cosine term.\n%\n%OUTPUTS: val The 1XN set of values of the integral of cos(u)^n.\n%\n%This function simply implements the recursion that arises from integration\n%by parts from basic calculus, as are given in the tables in the back of\n%[1].\n%\n%REFERENCES:\n%[1] J. Stewart, Calculus, 7th ed. Belmont, CA: Brooks/Cole, 2012.\n%\n%October 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumDim=size(u,1);\n\nif(isempty(u))\n val=[];\n return;\nend\n\nif(numDim==1)%An indefinite integral\n val=indefIntCosPow(u,n);\nelse%A definite integral\n val=indefIntCosPow(u(2,:),n)-indefIntCosPow(u(1,:),n);\nend\n\nend\n\nfunction val=indefIntCosPow(u,n)\n\n%Special cases for n=0 and n=1.\nif(n==0)\n val=u;\n return;\nelseif(n==1)\n val=sin(u);\n return;\nend\n\n%If here, n>=1\nsinVal=sin(u);\ncosVal=cos(u);\n\nval=0;\nif(mod(n,2)==0)%If n is even\n endVal=2;\nelse\n endVal=3;\nend\n\ncoeffProd=1;\nfor k=n:-2:endVal\n val=val+coeffProd*(1/k)*cosVal.^(k-1).*sinVal;\n coeffProd=coeffProd*(k-1)/k;\nend\n\nif(endVal==2)\n %The final integral is over cos^0\n val=val+coeffProd*u;\nelse\n %The final integral is over cos^1\n val=val+coeffProd*sinVal;\nend\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Specific_Integrals/intCosPow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.9252299643080208, "lm_q1q2_score": 0.8765453347293292}} {"text": "function val=intSinPow(u,n)\n%%INTSINPOWER Evaluate the integral of sin(u)^n du. A definite integral\n% can be evaluated, or an indefinite integral (with a\n% particular additive constant).\n%\n%INPUTS: u A 2XN (for definite integral) or a 1XN (for indefinite\n% integrals) set of N points. For definite integrals, u(1,:) are\n% the real lower bounds and u(2,:) are the real upper bounds. For\n% indefinite integrals, the integral is evaluated at the points in\n% u. The values in u should be real.\n% n The positive integer exponent of the sine term.\n%\n%OUTPUTS: val The 1XN set of values of the integral of sin(u)^n.\n%\n%This function simply implements the recursion that arises from integration\n%by parts from basic calculus, as are given in the tables in the back of\n%[1].\n%\n%REFERENCES:\n%[1] J. Stewart, Calculus, 7th ed. Belmont, CA: Brooks/Cole, 2012.\n%\n%October 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumDim=size(u,1);\n\nif(isempty(u))\n val=[];\n return;\nend\n\nif(numDim==1)%An indefinite integral\n val=indefIntSinPow(u,n);\nelse%A definite integral\n val=indefIntSinPow(u(2,:),n)-indefIntSinPow(u(1,:),n);\nend\nend\n\nfunction val=indefIntSinPow(u,n)\n\n%Special cases for n=0 and n=1.\nif(n==0)\n val=u;\n return;\nelseif(n==1)\n val=-cos(u);\n return;\nend\n\n%If here, n>=1\nsinVal=sin(u);\ncosVal=cos(u);\n\nval=0;\nif(mod(n,2)==0)%If n is even\n endVal=2;\nelse\n endVal=3;\nend\n \ncoeffProd=1;\nfor k=n:-2:endVal\n val=val-coeffProd*(1/k)*sinVal.^(k-1).*cosVal;\n coeffProd=coeffProd*(k-1)/k;\nend\n\nif(endVal==2)\n %The final integral is over sin^0\n val=val+coeffProd*u;\nelse\n %The final integral is over sin^1\n val=val-coeffProd*cosVal;\nend\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Specific_Integrals/intSinPow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.92522995296862, "lm_q1q2_score": 0.8765453226120262}} {"text": "function varargout = randomAngle3d(varargin)\n%RANDOMANGLE3D Return a 3D angle uniformly distributed on unit sphere.\n%\n% usage\n% [THETA PHI] = randomAngle3d\n% Generate an angle unformly distributed on the surface of the unit\n% sphere.\n%\n% \"Mathematical\" convention is used: theta is the colatitude (angle with\n% vertical axis, 0 for north pole, +pi for south pole, pi/2 for points at\n% equator) with z=0. \n% phi is the same as matlab cart2sph: angle from Ox axis, counted\n% positively counter-clockwise.\n%\n% [THETA PHI] = randomAngle3d(N)\n% generates N random angles (N is a scalar). The result is a N-by-2\n% array.\n%\n% Example:\n% % Draw some points on the surface of a sphere\n% figure;\n% drawSphere; hold on;\n% drawPoint3d(pts, '.');\n% axis equal;\n%\n% See also \n% angles3d, sph2cart2, cart2sph2\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2005-02-18\n% Copyright 2005-2022 INRA - Cepia Software platform\n\nN = 1;\nif ~isempty(varargin)\n N = varargin{1};\nend\n\nphi = 2*pi*rand(N, 1);\ntheta = asin(2*rand(N, 1)-1) + pi/2;\n\nif nargout<2\n var = [theta phi];\n varargout{1} = var;\nelse\n varargout{1} = theta;\n varargout{2} = phi;\nend\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom3d/randomAngle3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296944, "lm_q2_score": 0.9196425245706047, "lm_q1q2_score": 0.8760276723552648}} {"text": "function value = ball_volume_nd ( n, r )\n\n%*****************************************************************************80\n%\n%% BALL_VOLUME_ND computes the volume of a ball in ND.\n%\n% Integration region:\n%\n% Points X(1:N) such that\n%\n% Sum ( X(1:N)**2 ) <= R**2\n%\n% Discussion:\n%\n% N Volume\n%\n% 2 PI * R**2\n% 3 (4/3) * PI * R**3\n% 4 (1/2) * PI**2 * R**4\n% 5 (8/15) * PI**2 * R**5\n% 6 (1/6) * PI**3 * R**6\n% 7 (16/105) * PI**3 * R**7\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 20 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the dimension of the space.\n%\n% Input, real R, the radius of the ball.\n%\n% Output, real BALL_VOLUME_ND, the volume of the ball.\n%\n value = ball_unit_volume_nd ( n ) * r^n;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/ball_volume_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737737, "lm_q2_score": 0.9111797033789887, "lm_q1q2_score": 0.8755996915952499}} {"text": "function [ b, det ] = r8mat_inverse_3d ( a )\n\n%*****************************************************************************80\n%\n%% R8MAT_INVERSE_3D inverts a 3 by 3 R8MAT using Cramer's rule.\n%\n% Discussion:\n%\n% If DET is zero, then A is singular, and does not have an\n% inverse. In that case, B is simply set to zero, and a\n% message is printed.\n%\n% If DET is nonzero, then its value is roughly an estimate\n% of how nonsingular the matrix A is.\n%\n% Modified:\n%\n% 31 January 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A(3,3), the matrix to be inverted.\n%\n% Output, real B(3,3), the inverse of the matrix.\n%\n% Output, real DET, the determinant of the matrix.\n%\n\n%\n% Compute the determinant of A\n%\n det = a(1,1) * ( a(2,2) * a(3,3) - a(2,3) * a(3,2) ) ...\n + a(1,2) * ( a(2,3) * a(3,1) - a(2,1) * a(3,3) ) ...\n + a(1,3) * ( a(2,1) * a(3,2) - a(2,2) * a(3,1) );\n%\n% If the determinant is zero, bail out.\n%\n if ( det == 0.0 )\n b(1:3,1:3) = 0.0;\n return\n end\n%\n% Compute the entries of the inverse matrix using an explicit\n% formula.\n%\n b(1,1) = + ( a(2,2) * a(3,3) - a(2,3) * a(3,2) ) / det;\n b(1,2) = - ( a(1,2) * a(3,3) - a(1,3) * a(3,2) ) / det;\n b(1,3) = + ( a(1,2) * a(2,3) - a(1,3) * a(2,2) ) / det;\n\n b(2,1) = - ( a(2,1) * a(3,3) - a(2,3) * a(3,1) ) / det;\n b(2,2) = + ( a(1,1) * a(3,3) - a(1,3) * a(3,1) ) / det;\n b(2,3) = - ( a(1,1) * a(2,3) - a(1,3) * a(2,1) ) / det;\n\n b(3,1) = + ( a(2,1) * a(3,2) - a(2,2) * a(3,1) ) / det;\n b(3,2) = - ( a(1,1) * a(3,2) - a(1,2) * a(3,1) ) / det;\n b(3,3) = + ( a(1,1) * a(2,2) - a(1,2) * a(2,1) ) / det;\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/r8mat_inverse_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885303, "lm_q2_score": 0.9099070005411123, "lm_q1q2_score": 0.8749063461484106}} {"text": "function [X_norm, mu, sigma] = featureNormalize(X)\n%FEATURENORMALIZE Normalizes the features in X \n% FEATURENORMALIZE(X) returns a normalized version of X where\n% the mean value of each feature is 0 and the standard deviation\n% is 1. This is often a good preprocessing step to do when\n% working with learning algorithms.\n\n% You need to set these values correctly\nX_norm = X;\nmu = zeros(1, size(X, 2));\nsigma = zeros(1, size(X, 2));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: First, for each feature dimension, compute the mean\n% of the feature and subtract it from the dataset,\n% storing the mean value in mu. Next, compute the \n% standard deviation of each feature and divide\n% each feature by it's standard deviation, storing\n% the standard deviation in sigma. \n%\n% Note that X is a matrix where each column is a \n% feature and each row is an example. You need \n% to perform the normalization separately for \n% each feature. \n%\n% Hint: You might find the 'mean' and 'std' functions useful.\n% \n\nmu = mean(X);\nsigma = std(X);\n\nfor i = 1:size(X,2)\n\tX_norm(:,i) = (X(:,i) - mu(i)) / sigma(i);\nend\n\n% ============================================================\n\nend", "meta": {"author": "gopaczewski", "repo": "coursera-ml", "sha": "9f68b71ac6b65bfd7cea32c7c22b4abd40401579", "save_path": "github-repos/MATLAB/gopaczewski-coursera-ml", "path": "github-repos/MATLAB/gopaczewski-coursera-ml/coursera-ml-9f68b71ac6b65bfd7cea32c7c22b4abd40401579/mlclass-ex1-005/mlclass-ex1/featureNormalize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.9353465098415279, "lm_q1q2_score": 0.8748730917870008}} {"text": "function [p,t] = smoothmesh(p,t,maxit,tol)\n\n%*****************************************************************************80\n%\n% SMOOTHMESH: Smooth a triangular mesh using Laplacian smoothing.\n%\n% Laplacian smoothing is an iterative process that generally leads to an\n% improvement in the quality of the elements in a triangular mesh.\n%\n% [p,t] = smoothmesh(p,t);\n%\n% p : Nx2 array of nodal XY coordinates, [x1,y1; x2,y2; etc].\n% t : Mx3 array of triangles as indices, [n11,n12,n13; \n% n21,n22,n23; etc].\n% maxit : Maximum allowable iterations.\n% tol : Convergence tolerance (Percentage change in edge length must be \n% less than TOL).\n%\n% If MAXIT or TOL are left empty the default values MAXIT = 20 and TOL =\n% 0.01 are used.\n%\n% EXAMPLE:\n%\n% [p,t] = smoothmesh(p,t,10,0.05);\n%\n% Author:\n%\n% Darren Engwirda\n%\n\nif nargin<4\n tol = [];\n if nargin<3\n maxit = [];\n if nargin<2\n error('Incorrect number of inputs.');\n end\n end\nelseif nargin>5\n error('Incorrect number of inputs.')\nend\nif nargout>2\n error('Incorrect number of outputs.');\nend\nif isempty(tol)\n tol = 0.01;\nend\nif isempty(maxit)\n maxit = 20;\nend\n\n[p,t] = fixmesh(p,t); % Ensure consistent mesh\n\nn = size(p,1);\nS = sparse(t(:,[1,1,2,2,3,3]),t(:,[2,3,1,3,1,2]),1,n,n); % Sparse connectiity matrix\nW = sum(S,2);\nif any(W==0)\n error('Invalid mesh. Hanging nodes found.');\nend\n\nedge = [t(:,[1,2]); t(:,[1,3]); t(:,[2,3])]; % Non-unique edges\nedge = sortrows(sort(edge,2)); % Put shared edges next to each other\nidx = all(diff(edge)==0,2); % Find shared edges\nidx = [idx;false]|[false;idx]; % True for all shared edges\nbnde = edge(~idx,:); % Boundary edges\nedge = edge(idx,:); % Internal edges\nedge = [bnde; edge(1:2:end-1,:)]; % Unique edges\nbnd = unique(bnde); % Boundary nodes\n\nL = max(sqrt(sum((p(edge(:,1),:)-p(edge(:,2),:)).^2,2)),eps); % Edge length\n\nfor iter = 1:maxit\n pnew = (S*p)./[W,W]; % Laplacian smoothing\n pnew(bnd,:) = p(bnd,:); % Dont let BND nodes move\n p = pnew;\n\n Lnew = max(sqrt(sum((p(edge(:,1),:)-p(edge(:,2),:)).^2,2)),eps); % Edge length\n move = norm((Lnew-L)./Lnew,inf); % Percentage change\n if moveoo ) F(N+1)/F(N)\n%\n phi = ( 1.0 + sqrt ( 5.0 ) ) / 2.0;\n%\n% Allocate storage for the point data.\n%\n x = zeros ( n, 1 );\n y = zeros ( n, 1 );\n%\n% Set the angle and radius of the first point.\n%\n a = 0.0;\n r = 0.0;\n%\n% Set the increments.\n%\n da = 2.0 * pi * ( phi - 1.0 ) / phi;\n dr = 1.0;\n%\n% Create a spiral in which the radius R and angle A both\n% increase by a constant increment,\n%\n for i = 1 : n\n x(i) = r * cos ( a );\n y(i) = r * sin ( a );\n a = mod ( a + da, 2 * pi );\n r = r + dr;\n end\n%\n% SCALE controls how many steps we take between the actual points.\n% A value of 5 is enough to see the basic spiral that connects the points.\n% A vale of 10 would make a smoother spiral.\n%\n scale = 5.0;\n%\n% Allocate storage for the intermediate data.\n%\n n2 = scale * ( n - 1 ) + 1;\n x2 = zeros ( n2, 1 );\n y2 = zeros ( n2, 1 );\n%\n% Set the angle and radius of the first point.\n%\n a = 0.0;\n r = 0.0;\n%\n% Set the increments.\n%\n da = 2.0 * pi * ( phi - 1.0 ) / phi;\n dr = 1.0;\n\n da = da / scale;\n dr = dr / scale;\n%\n% Create a spiral in which the radius R and angle A both\n% increase by a constant increment,\n%\n for i = 1 : n2\n x2(i) = r * cos ( a );\n y2(i) = r * sin ( a );\n a = mod ( a + da, 2 * pi );\n r = r + dr;\n end\n%\n% Display the points, \n% and use the intermediate points to draw lines that display the spiral.\n%\n figure\n scatter ( x, y, 'b.' );\n hold on\n plot ( x2, y2, 'r-' )\n axis equal\n title ( sprintf ( 'Connected Fibonacci spiral, N = %d', n ) )\n hold off\n\n return\nend\n\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fibonacci_spiral/fibonacci_spiral_connected.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342049451596, "lm_q2_score": 0.9136765316406923, "lm_q1q2_score": 0.8740542224231447}} {"text": "%% RATE OF CONVERGENCE OF LINEAR ELEMENT FOR POISSON EQUATION\n%\n% This example is to show the rate of convergence of linear finite element\n% approximation of the Poisson equation on the unit square with the\n% following boundary conditions:\n%\n% - Non-empty Dirichlet boundary condition.\n% - Pure Neumann boundary condition.\n% - Robin boundary condition.\n%\n% The basis, data structure and numerical test is summarized in Poissonfemrate.\n%\n% See also PoissonP2femrate, Poissonafemrate\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclear variables\n%% Setting\n[node,elem] = squaremesh([0,1,0,1],0.25); \nmesh = struct('node',node,'elem',elem);\noption.L0 = 3;\noption.maxIt = 4;\noption.printlevel = 1;\n\n%% Non-empty Dirichlet boundary condition.\noption.plotflag = 1;\npde = sincosdata;\nmesh.bdFlag = setboundary(node,elem,'Dirichlet','~(x==0)','Neumann','x==0');\nfemPoisson(mesh,pde,option);\n\n%% Pure Neumann boundary condition.\noption.plotflag = 0;\n% pde = sincosNeumanndata;\npde = sincosdata;\nmesh.bdFlag = setboundary(node,elem,'Neumann');\nfemPoisson(mesh,pde,option);\n\n%% Pure Robin boundary condition.\noption.plotflag = 0;\npde = sincosRobindata;\nmesh.bdFlag = setboundary(node,elem,'Robin');\nfemPoisson(mesh,pde,option);\n\n%% Conclusion\n%\n% The optimal rate of convergence of the H1-norm (1st order) and L2-norm\n% (2nd order) is observed. The 2nd order convergent rate between two\n% discrete functions ||DuI-Duh|| is known as superconvergence.\n%\n% MGCG converges uniformly in all cases.\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/example/fem/Poisson/Poissonfemrate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436404, "lm_q2_score": 0.914900957313305, "lm_q1q2_score": 0.8740223898187937}} {"text": "function [ freq,amp,phase,dc ] = fourier_series_real( t,x )\n% function [ freq,amp,phase,dc ] = fourier_series_real( t,x )\n% Fourier series of real signals.\n% Written by Yoash Levron, January 2013.\n%\n% This function computes the fourier series of a signal x(t).\n% the amplitudes of the fourier series have the same dimension\n% of the original signal, so this function is useful for immediate\n% computation of the actual frequency components, without\n% further processing.\n%\n% for example, x(t) = 2 + 3*cos(2*pi*50*t) will result in \n% dc value = 2\n% frequencies = [50 100 150 200 ...]\n% amplitudes = [3 0 0 0 ...]\n% phases = [0 0 0 0 ...]\n%\n% x(t) is one cycle of an infinite cyclic signal. The function\n% computes the fourier transform of that infinite signal.\n% the period of the signal (T) is determined by the length\n% of the input time vector, t.\n% x(t) must be real (no imaginary values).\n%\n% The signal x(t) is represented as:\n% x(t) = Adc + A1*cos(w*t + ph1) + A2*cos(2*w*t + ph2) + ...\n% the function computes the amplitudes, Adc,A1,A2...\n% and the phases ph1,ph2,...\n%\n% T = period of the signal = t(end) - t(1)\n% w = basic frequency = 2*pi/T\n%\n% The function automatically interpolates the original signal\n% to avoid aliasing. Likewise, the function automatically determines\n% the number of fourier components, and truncates trailing zeros.\n%\n% inputs:\n% t - [sec] time vector. Sample time may vary within the signal.\n% x - signal vector. same length as t.\n%\n% outputs:\n% freq - [Hz] frequencies of the fourier series, not including zero.\n% amp - amplitudes vector. amp=[A1 A2 A3 ...], not including the DC component.\n% phase - [rad/sec] . phases, not including the DC component.\n% dc - the DC value (average of the signal).\n\n\n%%%%%%%%%%% computation %%%%%%%%\nrel_tol = 1e-4; % relative tolerance, to determine trailing zero truncation\n\nif (~isreal(x))\n clc;\n beep;\n disp('fourier_series_real Error: x(t) must be real.');\n dc = NaN; amp = NaN; freq = NaN; phase = NaN;\n return;\nend\n\nt = t-t(1); % shifting time to zero.\nT = t(end); % period time.\nN = 100; % number of samples\nif (mod(N,2) == 1)\n N = N + 1;\nend\nN = N/2;\n\nok = 0;\nwhile (~ok)\n N = N*2; % increase number of samples\n \n if (N > 10e6)\n clc;\n beep;\n disp('fourier_series_real Error: signal bandwidth seems too high.');\n disp('Try decreasing the sample time in the input time vector t,');\n disp('or increasing the relative tolerance rel_tol');\n dc = NaN; amp = NaN; freq = NaN; phase = NaN;\n return;\n end\n dt = T/N;\n t1 = 0:dt:(T-dt);\n x1 = interp1(t,x,t1,'cubic',0);\n xk = (1/N)*fft(x1);\n \n dc = abs(xk(1));\n xkpos = xk(2:(N/2));\n xkneg = xk(end:-1:(N/2+2));\n \n freq = [1:length(xkpos)]/T; % Hz\n amp = 2*abs(xkpos);\n phase = angle(xkpos); % rad/sec\n \n %%% check if enough samples are used.\n %%% if not, try again, with more samples.\n Am = max(amp);\n ii = find((amp(end-10:end)/Am)>rel_tol);\n ok = isempty(ii);\nend\n\n% %%% truncate output vectors to remove trailing zeros\nAm = max(amp);\nii = length(amp);\nwhile (amp(ii) < Am*rel_tol)\n ii = ii - 1;\nend\namp = amp(1:ii);\nfreq = freq(1:ii);\nphase = phase(1:ii);\n\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/40017-fourier-series-of-real-signals/fourier_series_real.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110588, "lm_q2_score": 0.9149009549929797, "lm_q1q2_score": 0.8740223806190864}} {"text": "function [x,xL,t,intersects]=findClosestPointLineEllipsoid(xc,A,x0,a,aType,epsConst)\n%%FINDCLOSESTPOINTLINEELLIPSOID Given a 2D or 3D ellipsoid of the form\n% (x-xc)'*A*(x-xc)=1, and a line of the form x=x0+s*t, where t is\n% a scalar parameteric parameter, find the point on the ellipsoid\n% that is closest to the line as well as the point on the line\n% that is closest to the ellipsoid. If the line intersects the\n% ellipsoid, then more than once point can be returned. All\n% solutions and inputs are real.\n%\n%INPUTS: xc The xDimX1 center of the ellipsoid.\n% A The xDimXxDim symmetric positive definite matrix defining the\n% above equation for an ellipsoid.\n% x0, a These xDimX1 values define a line and the type of line is given\n% by aType. If aType=0, then the line is parameteric as x=x0+a*t\n% where t is a scalar value. If aType=1, then x0 and a are both\n% points on the line. \n% aType As mentioned above, this specifies how the line is\n% parameterized. The default if omitted or an empty matrix is\n% passed is 0.\n% epsConst In the rooting formulation of the solution, is is possible that\n% some candidate solutions are invalid (they do not satisfy the\n% constraint (x-xc)'*A*(x-xc)=1. Thus, the absolute value of a\n% transformed version of abs((x-xc)'*A*(x-xc)-1) must be\n% <=epsConst to be valid. The default if omitted or an empty\n% matrix is passed is 1e-9.\n%\n%OUTPUTS: x The xDimXnumSol set of closest points on the ellipsoid. If the\n% line and ellipsoid do not intersect, numSol=1.\n% xL The xDimXnumSol set of closest points on the line. These\n% correspond to those in x.\n% t The 1XnumSol set of parametric values such that the kth one is\n% xL(:,k)=x0+s*t(k).\n% intersects If the line intersects the ellipsoid, this is true. Otherwise,\n% it is false.\n%\n%This function utilizes a change of coordiantes to solve the problem.\n%We have to solve the optimization problem.\n%minimize norm(x0+s*t-x)^2\n%such that\n%(x-xc)'*A*(x-xc)=1\n%We perform an eigenvalue decomposition of A as A=U*D*U', where D is a\n%diagonal matrix and U is in a unitary matrix (because A is symmetric and\n%positive definite). Next, perform the change of variables\n%x=U*y+xc\n%s=U*c1 or c1=U'*s\n%c=x0-xc=U*c2 or c2=U'*(x0-xc)\n%c=U*c2\n%Because U'*U=I, the optimization problem becomes:\n%norm(c1*t-y+c2)^2\n%Subject to \n%y'*D*y=1\n%Thus, we solve for y and transform back into x. The method of solution is\n%Lagrangian relaxation. Chapter 4.1 or [1] goes over Lagrangian\n%multipliers. The Lagrangian for the problem is\n%L=norm(c1*t-y+c2)^2+lambda*(y'*D*y-1)\n%Setting the derivatives of L with respect to t and y equal to 0, one gets\n%a solution in terms of lambda (the Lagrangian parameter). One can then\n%choose lambda to satisfy the constraint y'*D*y=1. In this instance, that\n%can be formulated as involves solving a polynomial in terms of lambda.\n%That is what this function does. Due to possible singularities in a ratio\n%that is reduced to the polynomial, it is possible that invalid solutiosn\n%will be found. Thus, the epsConst parameter is introduced to throw out\n%possible solutions that do not sufficiently satisfy the condition. Of the\n%multiple solutions found for lambda, only the one minimizing the cost\n%function is kept.\n%\n%EXAMPLE 1:\n%This example is done in 2D, so it can be easily plotted. Multiple lines\n%are drawn. Two intersect an ellipse and two do not intersect the ellipse.\n%The closest points on the ellipse are drawn in red. Those on the lines at\n%black circles. Dashed black lines connect them.\n% xc=[2;2];\n% A=[0.5,-0.1;\n% -0.1, 0.2];\n% figure(1)\n% clf\n% hold on\n% drawEllipse(xc,A,1,'linewidth',2)\n% axis([-2, 6, -2, 6])\n% axis square\n% t=linspace(-10,10,500);\n% %Consider 4 lines.\n% a=[1,0,0, -2;\n% 2,0,-2, -1];\n% b=[4,1,-2,3;\n% 3,1,-1,-1;];\n% numLines=size(a,2);\n% for k=1:numLines\n% xy=bsxfun(@plus,a(:,k),bsxfun(@times,b(:,k),t));\n% plot(xy(1,:),xy(2,:),'linewidth',2)\n% [x,xL]=findClosestPointLineEllipsoid(xc,A,a(:,k),b(:,k));\n% \n% scatter(x(1,:),x(2,:),200,'.r')\n% scatter(xL(1,:),xL(2,:),100,'ok')\n% if(size(xL,2)==1)\n% %If the line either grazes the unit circle or does not intercept \n% %the unit circle, connect the point on the line to the nearest\n% %point on the circle.\n% plot([x(1),xL(1)],[x(2),xL(2)],'--k')\n% end\n% end\n%\n%EXAMPLE 2:\n%This example is similar to the first one, but is in 3D.\n% xc=[2;2;0];\n% A=[0.5,-0.1, 0.15;\n% -0.1, 0.2, 0.15;\n% 0.15,0.15,0.3];\n% figure(1)\n% clf\n% hold on\n% drawEllipse(xc,A,1,'edgecolor','none')\n% light()\n% %axis([-2, 6, -2, 6])\n% %axis square\n% t=linspace(-10,10,500);\n% %Consider 4 lines.\n% a=[1,0,0, -2;\n% 2,0,-2, -1;\n% 1,0,1, -1];\n% b=[4,1,-2,3;\n% 3,1,-1,-1;\n% 1,2,0,0];\n% numLines=size(a,2);\n% for k=1:numLines\n% xyz=bsxfun(@plus,a(:,k),bsxfun(@times,b(:,k),t));\n% plot3(xyz(1,:),xyz(2,:),xyz(3,:),'linewidth',2)\n% [x,xL]=findClosestPointLineEllipsoid(xc,A,a(:,k),b(:,k));\n% scatter3(x(1,:),x(2,:),x(3,:),200,'.r')\n% scatter3(xL(1,:),xL(2,:),xL(3,:),100,'ok')\n% if(size(xL,2)==1)\n% %If the line either grazes the unit circle or does not intercept \n% %the unit circle, connect the point on the line to the nearest\n% %point on the circle.\n% plot3([x(1),xL(1)],[x(2),xL(2)],[x(3),xL(3)],'--k')\n% end\n% end\n% axis([-6, 6, -6, 6,-6,6])\n% axis square\n% view(-8,30)\n%\n%REFERENCES:\n%[1] D. P. Bertsekas, Nonlinear Programming, 2nd ed. Belmont, MA:\n% Athena Science, 1999.\n%\n%October 2021 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<6||isempty(epsConst))\n epsConst=1e-9;\nend\n\nif(nargin<5||isempty(aType))\n aType=0;\nend\n\nif(aType==1)\n s=a-x0;\nelse\n s=a;\nend\n\n%The special case of s being 0. This means that we just find the closest\n%point on the ellipsoid to the point x0.\nif(all(s==0))\n x=nearestPointOnEllipsoid(xc,A,x0,1);\n xL=x0;\n t=0;\n intersects=all(x==xL);\n return; \nend\n\n%Check the special case of the line intercepting the ellipsoid. In this\n%instance,\n[x,t]=findEllipsLineIntersect(xc,A,x0,s,0);\nif(~isempty(x))\n t=t';\n xL=x;\n intersects=true;\n return; \nend\n\n%There is a line and it does not intercept the ellipsoid. Find the closest\n%point.\nintersects=false;\n\n[~,D,U]=eig(A);\nc1=U'*s;\nc2=U'*(x0-xc);\n\n[y,t]=solveDiagA(D,c2,c1,epsConst);\n\n%Transform back to x\nx=bsxfun(@plus,U*y,xc);\nxL=bsxfun(@plus,x0,bsxfun(@times,s,t));\n\nend\n\nfunction [x,t]=solveDiagA(A,a,b,epsConst)\n\nnumDim=size(a,1);\nswitch(numDim)\n case 2\n a11=A(1,1);\n a22=A(2,2);\n a1=a(1);\n a2=a(2);\n b1=b(1);\n b2=b(2);\n \n firstTerm=-a11*a22*(b1^2+b2^2)*(a11*b1^2+a22*b2^2);\n sqrtTerm=sqrt(a11^3*a22^3*(a2*b1-a1*b2)^2*(b1^2+b2^2)^2*(a11*b1^2+a22*b2^2));\n denom=a11^2*a22^2*(b1^2+b2^2)^2;\n \n if(imag(sqrtTerm)~=0)\n %If there is some finite precision error.\n x=[];\n t=[];\n return \n end\n\n lambda(1)=(firstTerm+sqrtTerm)/denom;\n lambda(2)=(firstTerm-sqrtTerm)/denom;\n\n x=zeros(2,2);\n t=zeros(1,2);\n cost=zeros(2,1);\n constErr=zeros(2,1);\n for k=1:2\n denom=a22*b2^2+a11*(b1^2+a22*(b1^2+b2^2)*lambda(k));\n \n x(:,k)=[a22*b2*(a1*b2-a2*b1);a11*b1*(a2*b1-a1*b2)]/denom;\n t(k)=-(a2*a22*b2*(1+a11*lambda(k))+a1*a11*b1*(1+a22*lambda(k)))/denom;\n \n cost(k)=norm(a+b*t(k)-x);\n constErr(k)=abs(x(:,k)'*A*x(:,k)-1);\n end\n sel=(constErr<=epsConst);\n if(sum(sel)==0)\n %If nothing met the constraint.\n x=[];\n t=[];\n return \n end\n x=x(:,sel);\n t=t(sel);\n cost=cost(sel);\n \n [~,idx]=min(cost);\n \n x=x(:,idx);\n t=t(idx);\n case 3\n a11=A(1,1);\n a22=A(2,2);\n a33=A(3,3);\n \n a1=a(1);\n a2=a(2);\n a3=a(3);\n b1=b(1);\n b2=b(2);\n b3=b(3);\n\n c0=(a11*b1^2+a22*b2^2+a33*b3^2)*(a22*(-1+a3^2*a33)*b2^2-2*a2*a22*a3*a33*b2*b3+(-1+a2^2*a22)*a33*b3^2+a11*((-1+a2^2*a22+a3^2*a33)*b1^2-2*a1*b1*(a2*a22*b2+a3*a33*b3)+a1^2*(a22*b2^2+a33*b3^2)));\n c1=2*(a11*b1^2+a22*b2^2+a33*b3^2)*(-a11*a33*(b1^2+b3^2)-a22*a33*(b2^2+b3^2)+a11*a22*((-1+(a2^2+a3^2)*a33)*b1^2+(-1+(a1^2+a3^2)*a33)*b2^2-2*a2*a3*a33*b2*b3+(a1^2+a2^2)*a33*b3^2-2*a1*a33*b1*(a2*b2+a3*b3)));\n c2=(-a22^2*a33^2*(b2^2+b3^2)^2+a11^2*(-a33^2*(b1^2+b3^2)^2+a22^2*((-1+a3^2*a33)*(b1^2+b2^2)^2-2*a3*a33*(a1*b1+a2*b2)*(b1^2+b2^2)*b3+a33*(a1*b1+a2*b2)^2*b3^2)+a22*a33*((-4+a2^2*a33)*b1^4-2*a1*a2*a33*b1^3*b2+2*a1*a33*b1*b2*b3*(a3*b2-a2*b3)+b3^2*((-2+a3^2*a33)*b2^2-2*a2*a3*a33*b2*b3+a2^2*a33*b3^2)+b1^2*((-4+a1^2*a33)*b2^2-2*a2*a3*a33*b2*b3+2*(-2+a2^2*a33)*b3^2)))+a11*a22*a33*(-2*a33*(b1^2*b2^2+2*(b1^2+b2^2)*b3^2+2*b3^4)+a22*(-2*a1*a33*b1*(a2*b2+a3*b3)*(b2^2+b3^2)+(b2^2+b3^2)*((-4+a1^2*a33)*b2^2+a1^2*a33*b3^2)+b1^2*((-4+a2^2*a33)*b2^2+2*a2*a3*a33*b2*b3+(-2+a3^2*a33)*b3^2))));\n c3=-2*a11*a22*a33*(b1^2+b2^2+b3^2)*(a11*a22*(b1^2+b2^2)+a11*a33*(b1^2+b3^2)+a22*a33*(b2^2+b3^2));\n c4=-a11^2*(a22^2)*(a33^2)*((b1^2+b2^2+b3^2)^2);\n\n lambda=roots([c4;c3;c2;c1;c0]);\n lambda=lambda(imag(lambda)==0);\n numSol=length(lambda);\n \n if(numSol==0)\n %If there is some finite precision error. There should be two\n %solutions.\n x=[];\n t=[];\n return \n end\n \n x=zeros(3,numSol);\n t=zeros(1,numSol);\n cost=zeros(numSol,1);\n %Due to singularities, some solutions might not be correct. Thus,\n %we also evaluate the relative error for enforcing the constraint\n %and if the error is too high, those solutions are discarded.\n constErr=zeros(numSol,1);\n for k=1:numSol\n lambdaCur=lambda(k);\n denom=a22*b2^2+a33*b3^2+a22*a33*(b2^2+b3^2)*lambdaCur+a11*b1^2*(1+a22*lambdaCur)*(1+a33*lambdaCur)+a11*lambdaCur*(a33*b3^2+a22*(b2^2+a33*(b2^2+b3^2)*lambdaCur));\n x(:,k)=[-a3*a33*b1*b3*(1+a22*lambdaCur)-a2*a22*b1*b2*(1+a33*lambdaCur)+a1*(a22*b2^2+a33*b3^2+a22*a33*(b2^2+b3^2)*lambdaCur);\n a11*b1*(a2*b1-a1*b2)+a33*b3*(-a3*b2+a2*b3)+a11*a33*(-b2*(a1*b1+a3*b3)+a2*(b1^2+b3^2))*lambdaCur;\n a11*b1*(a3*b1-a1*b3)+a22*b2*(a3*b2-a2*b3)+a11*a22*(a3*(b1^2+b2^2)-(a1*b1+a2*b2)*b3)*lambdaCur]/denom;\n t(k)=-(a1*a11*b1*(1+a22*lambdaCur)*(1+a33*lambdaCur)+(1+a11*lambdaCur)*(a3*a33*b3*(1+a22*lambdaCur)+a2*a22*b2*(1+a33*lambdaCur)))/denom; \n cost(k)=norm(a+b*t(k)-x);\n constErr(k)=abs(x(:,k)'*A*x(:,k)-1);\n end\n sel=(constErr<=epsConst);\n if(sum(sel)==0)\n %If nothing met the constraint.\n x=[];\n t=[];\n return \n end\n x=x(:,sel);\n t=t(sel);\n cost=cost(sel);\n\n [~,idx]=min(cost);\n x=x(:,idx);\n t=t(idx);\n otherwise\n error('An unsupported dimensionality is being used.')\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Geometry/findClosestPointLineEllipsoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660923657094, "lm_q2_score": 0.9161096072908429, "lm_q1q2_score": 0.87393750224593}} {"text": "function a = pascal1 ( n )\n\n%*****************************************************************************80\n%\n%% PASCAL1 returns the PASCAL1 matrix.\n%\n% Formula:\n%\n% if ( J = 1 )\n% A(I,J) = 1\n% elseif ( I = 0 )\n% A(1,J) = 0\n% else\n% A(I,J) = A(I-1,J) + A(I-1,J-1)\n%\n% Example:\n%\n% N = 5\n%\n% 1 0 0 0 0\n% 1 1 0 0 0\n% 1 2 1 0 0\n% 1 3 3 1 0\n% 1 4 6 4 1\n%\n% Properties:\n%\n% A is a \"chunk\" of the Pascal binomial combinatorial triangle.\n%\n% A is generally not symmetric: A' /= A.\n%\n% A is nonsingular.\n%\n% A is lower triangular.\n%\n% A is integral, therefore det ( A ) is integral, and \n% det ( A ) * inverse ( A ) is integral.\n%\n% det ( A ) = 1.\n%\n% A is unimodular.\n%\n% LAMBDA(1:N) = 1.\n%\n% (0, 0, ..., 0, 1) is an eigenvector.\n%\n% The inverse of A is the same as A, except that entries in \"odd\"\n% positions have changed sign:\n%\n% B(I,J) = (-1)^(I+J) * A(I,J)\n%\n% The product A*A' is a Pascal matrix\n% of the sort created by subroutine PASCAL2.\n%\n% Let the matrix C have the same entries as A, except that\n% the even columns are negated. Then Inverse(C) = C, and\n% C' * C = the Pascal matrix created by PASCAL2.\n%\n% The family of matrices is nested as a function of N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Robert Gregory, David Karney,\n% Example 3.15,\n% A Collection of Matrices for Testing Computational Algorithms,\n% Wiley, 1969, page 43, \n% LC: QA263.G68.\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for i = 1 : n\n for j = 1 : n\n\n if ( j == 1 )\n a(i,j) = 1.0;\n elseif ( i == 1 )\n a(i,j) = 0.0;\n else\n a(i,j) = a(i-1,j-1) + a(i-1,j);\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/pascal1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164657, "lm_q2_score": 0.931462509346239, "lm_q1q2_score": 0.8738273451930634}} {"text": "function fx = p46_fun ( n, x )\n\n%*****************************************************************************80\n%\n%% P46_FUN evaluates the integrand for problem 46.\n%\n% Discussion:\n%\n% The problem has a parameter ALPHA that can be set by calling\n% P46_PARAM_SET.\n%\n% The integrand is the radius of an ellipse as a function of angle.\n%\n% The integral represents the arc length of the ellipse.\n%\n% The suggested parameter range is 0.0 <= ALPHA < 1.0. ALPHA is\n% the eccentricity of the ellipse.\n%\n% Interval:\n%\n% 0 <= theta <= 2 pi\n%\n% Integrand:\n%\n% r(theta) = ( 1 - alpha^2 ) / ( 1 - alpha * cos ( theta ) )\n%\n% Exact Integral:\n%\n% When alpha = sin ( pi / 12 ), then\n%\n% 6.0690909595647754101\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 December 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Richard Crandall,\n% Projects in Scientific Computing,\n% Springer, 2000, page 47.\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(N), the evaluation points.\n%\n% Output, real FX(N), the integrand values.\n%\n%\n alpha = p46_param_get ( );\n\n fx(1:n) = ( 1.0 - alpha^2 ) ./ ( 1.0 - alpha * cos ( x(1:n) ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_int/p46_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627597, "lm_q2_score": 0.9184802456988518, "lm_q1q2_score": 0.8736053424576916}} {"text": "function z = zernpol(n,m,r,nflag)\n%ZERNPOL Radial Zernike polynomials of order N and frequency M.\n% Z = ZERNPOL(N,M,R) returns the radial Zernike polynomials of \n% order N and frequency M, evaluated at R. N is a vector of\n% positive integers (including 0), and M is a vector with the\n% same number of elements as N. Each element k of M must be a \n% positive integer, with possible values M(k) = 0,2,4,...,N(k)\n% for N(k) even, and M(k) = 1,3,5,...,N(k) for N(k) odd. R is \n% a vector of numbers between 0 and 1. The output Z is a matrix \n% with one column for every (N,M) pair, and one row for every\n% element in R.\n%\n% Z = ZERNPOL(N,M,R,'norm') returns the normalized Zernike poly-\n% nomials. The normalization factor Nnm = sqrt(2*(n+1)) is\n% chosen so that the integral of (r * [Znm(r)]^2) from r=0 to \n% r=1 is unity. For the non-normalized polynomials, Znm(r=1)=1\n% for all [n,m].\n%\n% The radial Zernike polynomials are the radial portion of the\n% Zernike functions, which are an orthogonal basis on the unit\n% circle. The series representation of the radial Zernike \n% polynomials is\n%\n% (n-m)/2\n% __\n% m \\ s n-2s\n% Z(r) = /__ (-1) [(n-s)!/(s!((n-m)/2-s)!((n+m)/2-s)!)] * r\n% n s=0\n%\n% The following table shows the first 12 polynomials.\n%\n% n m Zernike polynomial Normalization\n% ---------------------------------------------\n% 0 0 1 sqrt(2)\n% 1 1 r 2\n% 2 0 2*r^2 - 1 sqrt(6)\n% 2 2 r^2 sqrt(6)\n% 3 1 3*r^3 - 2*r sqrt(8)\n% 3 3 r^3 sqrt(8)\n% 4 0 6*r^4 - 6*r^2 + 1 sqrt(10)\n% 4 2 4*r^4 - 3*r^2 sqrt(10)\n% 4 4 r^4 sqrt(10)\n% 5 1 10*r^5 - 12*r^3 + 3*r sqrt(12)\n% 5 3 5*r^5 - 4*r^3 sqrt(12)\n% 5 5 r^5 sqrt(12)\n% ---------------------------------------------\n%\n% Example:\n%\n% % Display three example Zernike radial polynomials\n% r = 0:0.01:1;\n% n = [3 2 5];\n% m = [1 2 1];\n% z = zernpol(n,m,r);\n% figure\n% plot(r,z)\n% grid on\n% legend('Z_3^1(r)','Z_2^2(r)','Z_5^1(r)','Location','NorthWest')\n%\n% See also ZERNFUN, ZERNFUN2.\n\n% A note on the algorithm.\n% ------------------------\n% The radial Zernike polynomials are computed using the series\n% representation shown in the Help section above. For many special\n% functions, direct evaluation using the series representation can\n% produce poor numerical results (floating point errors), because\n% the summation often involves computing small differences between\n% large successive terms in the series. (In such cases, the functions\n% are often evaluated using alternative methods such as recurrence\n% relations: see the Legendre functions, for example). For the Zernike\n% polynomials, however, this problem does not arise, because the\n% polynomials are evaluated over the finite domain r = (0,1), and\n% because the coefficients for a given polynomial are generally all\n% of similar magnitude.\n% \n% ZERNPOL has been written using a vectorized implementation: multiple\n% Zernike polynomials can be computed (i.e., multiple sets of [N,M]\n% values can be passed as inputs) for a vector of points R. To achieve\n% this vectorization most efficiently, the algorithm in ZERNPOL\n% involves pre-determining all the powers p of R that are required to\n% compute the outputs, and then compiling the {R^p} into a single\n% matrix. This avoids any redundant computation of the R^p, and \n% minimizes the sizes of certain intermediate variables.\n%\n% Paul Fricker 11/13/2006\n\n\n% Check and prepare the inputs:\n% -----------------------------\nif ( ~any(size(n)==1) ) || ( ~any(size(m)==1) )\n error('zernpol:NMvectors','N and M must be vectors.')\nend\n\nif length(n)~=length(m)\n error('zernpol:NMlength','N and M must be the same length.')\nend\n\nn = n(:);\nm = m(:);\nlength_n = length(n);\n\nif any(mod(n-m,2))\n error('zernpol:NMmultiplesof2','All N and M must differ by multiples of 2 (including 0).')\nend\n\nif any(m<0)\n error('zernpol:Mpositive','All M must be positive.')\nend\n\nif any(m>n)\n error('zernpol:MlessthanN','Each M must be less than or equal to its corresponding N.')\nend\n\nif any( r>1 | r<0 )\n error('zernpol:Rlessthan1','All R must be between 0 and 1.')\nend\n\nif ~any(size(r)==1)\n error('zernpol:Rvector','R must be a vector.')\nend\n\nr = r(:);\nlength_r = length(r);\n\nif nargin==4\n isnorm = ischar(nflag) & strcmpi(nflag,'norm');\n if ~isnorm\n error('zernpol:normalization','Unrecognized normalization flag.')\n end\nelse\n isnorm = false;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Compute the Zernike Polynomials\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Determine the required powers of r:\n% -----------------------------------\nrpowers = [];\nfor j = 1:length(n)\n rpowers = [rpowers m(j):2:n(j)];\nend\nrpowers = unique(rpowers);\n\n% Pre-compute the values of r raised to the required powers,\n% and compile them in a matrix:\n% -----------------------------\nif rpowers(1)==0\n rpowern = arrayfun(@(p)r.^p,rpowers(2:end),'UniformOutput',false);\n rpowern = cat(2,rpowern{:});\n rpowern = [ones(length_r,1) rpowern];\nelse\n rpowern = arrayfun(@(p)r.^p,rpowers,'UniformOutput',false);\n rpowern = cat(2,rpowern{:});\nend\n\n% Compute the values of the polynomials:\n% --------------------------------------\nz = zeros(length_r,length_n);\nfor j = 1:length_n\n s = 0:(n(j)-m(j))/2;\n pows = n(j):-2:m(j);\n for k = length(s):-1:1\n p = (1-2*mod(s(k),2))* ...\n prod(2:(n(j)-s(k)))/ ...\n prod(2:s(k))/ ...\n prod(2:((n(j)-m(j))/2-s(k)))/ ...\n prod(2:((n(j)+m(j))/2-s(k)));\n idx = (pows(k)==rpowers);\n z(:,j) = z(:,j) + p*rpowern(:,idx);\n end\n \n if isnorm\n z(:,j) = z(:,j)*sqrt(2*(n(j)+1));\n end\nend\n\n% EOF zernpol", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/thirdParty/zernike/zernpol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079558, "lm_q2_score": 0.9184802362152842, "lm_q1q2_score": 0.8736053296213647}} {"text": "function volume = sphere_imp_volume_nd ( dim_num, r )\n\n%*****************************************************************************80\n%\n%% SPHERE_IMP_VOLUME_ND computes the volume of an implicit sphere in ND.\n%\n% Discussion:\n%\n% An implicit sphere in ND satisfies the equation:\n%\n% sum ( ( X(1:N) - CENTER(1:N) )^2 ) = R^2\n%\n% where R is the radius and CENTER is the center.\n%\n% Results for the first few values of N are:\n%\n% DIM_NUM Volume\n% - -----------------------\n% 2 PI * R^2\n% 3 (4/3) * PI * R^3\n% 4 (1/2) * PI^2 * R^4\n% 5 (8/15) * PI^2 * R^5\n% 6 (1/6) * PI^3 * R^6\n% 7 (16/105) * PI^3 * R^7\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the dimension of the space.\n%\n% Input, real R, the radius of the sphere.\n%\n% Output, real VOLUME, the volume of the sphere.\n%\n volume = r^dim_num * sphere_unit_volume_nd ( dim_num );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/sphere_imp_volume_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914020657881, "lm_q2_score": 0.9032941982430048, "lm_q1q2_score": 0.8734078250600809}} {"text": "function [ f, i ] = fibonacci_floor ( n )\n\n%*****************************************************************************80\n%\n%% FIBONACCI_FLOOR returns the largest Fibonacci number less than or equal to N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 July 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the positive integer whose Fibonacci \"floor\" is desired.\n%\n% Output, integer F, the largest Fibonacci number less than or equal to N.\n%\n% Output, integer I, the index of the F.\n%\n if ( n <= 0 )\n\n i = 0;\n f = 0;\n\n else\n\n i = floor ( log ( 0.5 * ( 2 * n + 1 ) * sqrt ( 5.0 ) ) ...\n / log ( 0.5 * ( 1.0 + sqrt ( 5.0 ) ) ) );\n\n f = fibonacci_direct ( i );\n\n if ( n < f )\n i = i - 1;\n f = fibonacci_direct ( i );\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/fibonacci_floor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.9111797009670495, "lm_q1q2_score": 0.8734001175579807}} {"text": "function [X_norm, mu, sigma] = featureNormalize(X)\n%FEATURENORMALIZE Normalizes the features in X \n% FEATURENORMALIZE(X) returns a normalized version of X where\n% the mean value of each feature is 0 and the standard deviation\n% is 1. This is often a good preprocessing step to do when\n% working with learning algorithms.\n\n% You need to set these values correctly\nX_norm = X;\nmu = zeros(1, size(X, 2));\nsigma = zeros(1, size(X, 2));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: First, for each feature dimension, compute the mean\n% of the feature and subtract it from the dataset,\n% storing the mean value in mu. Next, compute the \n% standard deviation of each feature and divide\n% each feature by it's standard deviation, storing\n% the standard deviation in sigma. \n%\n% Note that X is a matrix where each column is a \n% feature and each row is an example. You need \n% to perform the normalization separately for \n% each feature. \n%\n% Hint: You might find the 'mean' and 'std' functions useful.\n% \n\nfor i = 1:size(X, 2)\n\tmu(:,i) = mean(X_norm(:,i));\n\tsigma(:,i) = std(X_norm(:,i));\n\tX_norm(:,i) = (X_norm(:,i) - mu(:,i)) / sigma(:,i);\nend\n\n% ============================================================\n\nend\n", "meta": {"author": "rieder91", "repo": "MachineLearning", "sha": "f6708f216326cb5c9e9e5c3afc912060bfa10486", "save_path": "github-repos/MATLAB/rieder91-MachineLearning", "path": "github-repos/MATLAB/rieder91-MachineLearning/MachineLearning-f6708f216326cb5c9e9e5c3afc912060bfa10486/Exercise 1/ex1/featureNormalize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294984, "lm_q2_score": 0.9353465080392795, "lm_q1q2_score": 0.8730812495927139}} {"text": "function [x,t,intersects]=constrainedLSLineSpher(a,b,alphaVal)\n%%CONSTRAINEDLSLINESPHER This function solves the real optimization problem\n% arg min _{x,t} norm(a+b*t-x) such that norm(x)=alphaVal\n% where t is a scalar and x is a vector. That is, it finds the\n% closest point on the unit sphere to a line in an arbitrary number\n% of dimensions. If the line does not intersect the sphere, there\n% will be 1 solution. If the line intersects the sphere, there can be\n% 1 or two solutions. All solutions and inputs are real.\n%\n%INPUTS: a A real xDimX1 vector.\n% b A real xDimX1 vector.\n% alphaVal The norm of the solution. If this is omittd or ane mpty matrix\n% is passed, the default of 1 is used.\n%\n%OUTPUTS: x An xDimX1 or xDimX2 set of solutions.\n% t The t value(s) associated with the solution(s) in x. If b=0,\n% then t will be 0, though its value does not matter.\n% intersects If the line intersects the ellipsoid this is true. Otherwise,\n% this is false.\n%\n%We want to solve arg min _{x,t} norm(a+b*t-x)^2 such that\n%norm(x)^2=alphaVal. First, we consider two special cases. The first is if\n%b is all zero, in which case t does not matter and we are finding the unit\n%vector x such that solves min _{x} norm(a-x). The solution is just\n%x=sqrt(alphaVal)*(a/norm(a)). Note that if a=all zeros, then a bunch of\n%NaNs will be returned for x --every point on the sphere is the \"closest\".\n%\n%The second special case is if the line intersects the unit sphere. We do\n%not know a priori if the line does intersect the sphere, so we solve the\n%problem and if the solutions are complex, then it does not intersect the\n%sphere. In this case, we just substitute the line equation into the\n%constraint:\n%norm(a+b*t)^2=alphaVal\n%This is a quadratic equation and can be solved using the quadratic\n%formula.\n%\n%Finally, if the solutions to the above are complex, we solve the general\n%problem. In this instance, the Lagrangian for equality constrained\n%optimization is\n%L=norm(a+b*t-x)^2+lambda*(norm(x)^2-alphaVal)\n%where lambda is the Lagrgian parameter. Taking the gradient with respect\n%to x and the derivative with respect to t and setting it equal to 0 leads\n%to the following linear system of equations:\n%[-b', norm(b)^2;\n% (1+lambda)*eye(xDim), -b] *[x;t] == [-a'*b;a]\n%The matrix on the left can be explicitly inverted as\n%1/(lambda*norm(b)^2)*[b, (1/(1+lambda)*(b*b'+lambda*norm(b)^2*eye(xDim));\n% 1+lambda, b'];\n%This leads to solutions for t and x as\n%t=-a'b/norm(b)^2\n%x=(1/(1+lambda))*(a-(1/norm(b)^2)*(a'*b)*b)\n%Substituting x into the constraint leads to the solutions for lambda:\n%lambda=-1+norm(a-(1/norm(b)^2)*(a'*b)*b)\n%lambda=-1-norm(a-(1/norm(b)^2)*(a'*b)*b)\n%The solution for lambda to us is the one that minimizes norm(a+b*t-x) for\n%the given t.\n%\n%EXAMPLE:\n%In this example, the unit circle is plotted along with some lines. The\n%points on the circle closest to the lines are plotted in red and black\n%circles are used to mark the location on each line that is closest to the\n%circle. Dashed lines connect the closest points on the lines to the\n%closest points on the circle when the lines do not intersect the circle.\n%Generate a unit circle to plot.\n% figure(1)\n% clf\n% hold on\n% %Draw a circle.\n% drawEllipse([0;0],eye(2,2),1,'linewidth',2)\n% axis([-2,2,-2,2])\n% axis square\n% \n% t=linspace(-10,10,500);\n% %Consider 4 lines.\n% a=[1,0,0, -2;\n% 2,0,-2, -1];\n% b=[4,1,-2,3;\n% 3,1,-1,-1];\n% numLines=size(a,2);\n% \n% for k=1:numLines\n% xy=bsxfun(@plus,a(:,k),bsxfun(@times,b(:,k),t));\n% plot(xy(1,:),xy(2,:),'linewidth',2)\n% [x,ts]=constrainedLSLineSpher(a(:,k),b(:,k));\n% \n% scatter(x(1,:),x(2,:),200,'.r')\n% xySol=bsxfun(@plus,a(:,k),bsxfun(@times,b(:,k),ts));\n% scatter(xySol(1,:),xySol(2,:),100,'ok')\n% if(length(ts)==1)\n% %If the line either grazes the unit circle or does not intercept\n% %the unit circle, connect the point on the line to the nearest\n% %point on the circle.\n% plot([x(1),xySol(1)],[x(2),xySol(2)],'--k')\n% end\n% end\n%\n%October 2021 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(alphaVal))\n alphaVal=1; \nend\n\n%Check for the special case of b being 0. In this instance,\n%x=sqrt(alphaVal)*a/norm(a).\nif(all(b==0))\n normA=norm(a);\n intersects=normA==1;\n \n x=sqrt(alphaVal)*(a/normA);\n t=0;%t does not matter.\n return; \nend\n\nxDim=size(a,1);\n\n%Deal with the case where the line intersects the unit sphere. This means\n%solve for the intersection points and see if they are real. If they are\n%complex, then the line does not intersect the unit sphere.\naMag2=dot(a,a);\nbMag2=dot(b,b);\nab=dot(a,b);\nt=roots([bMag2,2*ab,aMag2-alphaVal]).';\nif(~isempty(t)&&isreal(t))\n %The line intersects the sphere of radius alphaVal\n numSol=length(t);\n x=zeros(xDim,numSol);\n \n for curSol=1:numSol\n x(:,curSol)=a+b*t(curSol);\n %Force normalization (deal with any finite precision issues).\n x(:,curSol)=sqrt(alphaVal)*(x(:,curSol)/norm(x(:,curSol)));\n end\n intersects=true;\n return;\nend\n\n%In this instance, the line does not intersect the sphere.\nintersects=false;\nt=-ab/bMag2;\n\nmagVal=norm(a-b*(ab/bMag2))/sqrt(alphaVal);\nlambda=zeros(2,1);\nlambda(1)=-1+magVal;\nlambda(2)=-1-magVal;\n\n%For the return values.\nx=zeros(xDim,2);\nfor k=1:2\n x(:,k)=(1/(1+lambda(k)))*a-(1/(bMag2*(1+lambda(k))))*ab*b;\nend\n\nlinePt=a+b*t;\n\nif(norm(linePt-x(:,1))2*n)\n error('Invalid parenthesis character string provided.') \n end\n \n cPrime=((q+1)*(q-p)*c)/((q+p)*(q-p+1));\n if(pString(m)==')')\n q=q-1;\n c=cPrime;\n m=m+1;\n break;\n end\n\n p=p-1;\n c=c-cPrime;\n rankVal=rankVal+cPrime;\n m=m+1;\n end\nend\nif(m~=2*n+1)\n error('Invalid parenthesis character string provided.')\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Combinatorics/rankNestedParenth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.9184802367731411, "lm_q1q2_score": 0.8729336992014188}} {"text": "function theta = vectorAngle3d(v1, v2)\n%VECTORANGLE3D Angle between two 3D vectors.\n%\n% THETA = vectorAngle3d(V1, V2)\n% Computes the angle between the 2 3D vectors V1 and V2. The result THETA\n% is given in radians, between 0 and PI.\n%\n%\n% Example\n% % angle between 2 orthogonal vectors\n% vectorAngle3d([1 0 0], [0 1 0])\n% ans = \n% 1.5708\n%\n% % angle between 2 parallel vectors\n% v0 = [3 4 5];\n% vectorAngle3d(3*v0, 5*v0)\n% ans = \n% 0\n%\n% See also \n% vectors3d, vectorNorm3d, crossProduct3d\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2010-10-04, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010-2022 INRA - Cepia Software Platform\n\n% compute angle using arc-tangent to get better precision for angles near\n% zero, see the discussion in: \n% http://www.mathworks.com/matlabcentral/newsreader/view_thread/151925#381952\ntheta = atan2(vectorNorm3d(crossProduct3d(v1, v2)), sum(bsxfun(@times, v1, v2),2));\n\n% equivalent to:\n% v1 = normalizeVector3d(v1);\n% v2 = normalizeVector3d(v2);\n% theta = acos(dot(v1, v2, 2));\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom3d/vectorAngle3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574129515172, "lm_q2_score": 0.9161096072908429, "lm_q1q2_score": 0.8726623117055607}} {"text": "function val=StirlingNumber2(n,k)\n%%STIRLINGNUMBER2 Compute the Stirling number of the second kind {n,k},\n% which is also called a Stirling set number. This is the\n% number of ways to partition a set of n objects into k\n% non-empty subsets. The number is computed using a\n% recursion that will not overflow unless the actual number\n% overflows. When n is very large, the function can be\n% slow.\n% \n%INPUTS: n The integer total number of items in the set n>=0.\n% k The desired integer number of non-empty subsets of the set.\n% k>=0.\n%\n%OUTPUTS: val The number of ways of partitioning n items into k subsets. If\n% an overflow occurs, this will be infinite.\n%\n%The implementation uses the recurrence relation from [1].\n%\n%The more commonly seen expression in terms of a sum of binomials is not\n%desirable, because overflows will occur even when the final number does\n%not overflow.\n%\n%REFERENCES:\n%[1] Weisstein, Eric W. \"Stirling Number of the Second Kind.\" From\n% MathWorld--A Wolfram Web Resource.\n% http://mathworld.wolfram.com/StirlingNumberoftheSecondKind.html\n%\n%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(n=-1.')\n end\n table=[1,1,1,2,3,8,15,48,105,384,945,3840,10395,46080,135135,645120,2027025,10321920,34459425,185794560,654729075,3715891200,13749310575,81749606400,316234143225,1961990553600,7905853580625,51011754393600,213458046676875,1428329123020800,6190283353629375,42849873690624000,191898783962510625,1371195958099968000,6332659870762850625,46620662575398912000,221643095476699771875,1678343852714360832000,8200794532637891559375,63777066403145711616000,319830986772877770815625,2551082656125828464640000,13113070457687988603440625,107145471557284795514880000,563862029680583509947946875,4714400748520531002654720000,25373791335626257947657609375,216862434431944426122117120000,1192568192774434123539907640625,10409396852733332453861621760000,58435841445947272053455474390625,520469842636666622693081088000000];\n \n val(curEl)=table(xCur+2);\n else\n if(xCur==0||xCur==-1)\n val(curEl)=1;\n elseif(mod(xCur,2)==0)%If it is divisible by 2.\n k=xCur/2;\n val(curEl)=exp(k*log(2)+gammaln(k+1));\n else%Assume that it is odd.\n n=(xCur+1)/2;\n val(curEl)=exp(gammaln(xCur+2)-(n*log(2)+gammaln(n+1)));\n end\n end\nend\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/doubleFactorial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.9099070042057362, "lm_q1q2_score": 0.8721801896998789}} {"text": "function [ c, s ] = spherical_harmonic ( l, m, theta, phi )\n\n%*****************************************************************************80\n%\n%% SPHERICAL_HARMONIC evaluates spherical harmonic functions.\n%\n% Discussion:\n%\n% The spherical harmonic function Y(L,M,THETA,PHI)(X) is the\n% angular part of the solution to Laplace's equation in spherical\n% coordinates.\n%\n% Y(L,M,THETA,PHI)(X) is related to the associated Legendre\n% function as follows:\n%\n% Y(L,M,THETA,PHI)(X) = FACTOR * P(L,M)(cos(THETA)) * exp ( i * M * PHI )\n%\n% Here, FACTOR is a normalization factor:\n%\n% FACTOR = sqrt ( ( 2 * L + 1 ) * ( L - M )! / ( 4 * PI * ( L + M )! ) )\n%\n% In Mathematica, a spherical harmonic function can be evaluated by\n%\n% SphericalHarmonicY [ l, m, theta, phi ]\n%\n% Note that notational tradition in physics requires that THETA\n% and PHI represent the reverse of what they would normally mean\n% in mathematical notation; that is, THETA goes up and down, and\n% PHI goes around.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 March 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Eric Weisstein,\n% CRC Concise Encyclopedia of Mathematics,\n% CRC Press, 1999.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input, integer L, the first index of the spherical harmonic function.\n% Normally, 0 <= L.\n%\n% Input, integer M, the second index of the spherical harmonic function.\n% Normally, -L <= M <= L.\n%\n% Input, real THETA, the polar angle, for which\n% 0 <= THETA <= PI.\n%\n% Input, real PHI, the longitudinal angle, for which\n% 0 <= PHI <= 2*PI.\n%\n% Output, real C(1:L+1), S(1:L+1), the real and imaginary\n% parts of the functions Y(L,0:L,THETA,PHI).\n%\n m_abs = abs ( m );\n\n plm(1:l+1) = legendre_associated_normalized ( l, m_abs, cos ( theta ) );\n\n c(1:l+1) = plm(1:l+1) * cos ( m * phi );\n s(1:l+1) = plm(1:l+1) * sin ( m * phi );\n\n if ( m < 0 )\n c(1:l+1) = -c(1:l+1);\n s(1:l+1) = -s(1:l+1);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/spherical_harmonic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013548, "lm_q2_score": 0.9149009474519222, "lm_q1q2_score": 0.8721522397497411}} {"text": "function y=atanSlope3(x)\n%%ATANSLOPE3 Evaluate the function -3*(atan(x)-x)/x^3 avoiding problems at\n% the point x=0, where the limit equals 1. This function arises\n% in range enclosure algorithms for interval arithmetic.\n%\n%INPUTS: x A vector of matrix of real values at which the function should\n% be evaluated.\n%\n%OUTPUTS: y The value(s) of the function -3*(atan(x)-x)/x^3 at the point(s)\n% in x.\n%\n%For values of x having magnitude over 1e-2 or for complex values, the\n%function is evaluated as written. For smaller values, a Taylor series\n%expansion is used to avoid the singularity near the origin.\n%\n%This is one of the slope function in Table 10.6 of Section 10.6.2 of [1].\n%This file implements the function for non-intervals. See the Interval\n%class for an implementation for Interval arithmetic.\n%\n%REFERENCES:\n%[1] IEEE Standard for Interval Arithmetic,\" in IEEE Std 1788-2015,\n% pp.1-97, June 30 2015.\n%\n%November 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%Allocate space\ny=zeros(size(x));\n\n%For large enough values, use the standard function.\nsel=abs(x)>1e-2|~isreal(x);\nx1=x(sel);\ny(sel)=-3*(atan(x1)-x1)./x1.^3;\n\n%For smaller magnitude values, use an eigth-order Taylor series expansion.\n%The relative error at 10^-2 is on the order of 1e-23, which is less than\n%the precision of a double floating point number at that value. The series\n%is given in Horner form.\nx1=x(~sel);\ny(~sel)=1+x1.^2.*(-(3/5)+x1.^2.*(3/7+x1.^2.*(-(1/3)+(3*x1.^2)/11)));\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Slope_Functions/atanSlope3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739075, "lm_q2_score": 0.9149009474519223, "lm_q1q2_score": 0.8721522385352584}} {"text": "function [ n_data, n, area ] = sphere_unit_area_values ( n_data )\n\n%*****************************************************************************80\n%\n%% SPHERE_UNIT_AREA_VALUES returns some areas of the unit sphere in ND.\n%\n% Discussion:\n%\n% The formula for the surface area of the unit sphere in N dimensions is:\n%\n% Sphere_Unit_Area ( N ) = 2 * PI**(N/2) / Gamma ( N / 2 )\n%\n% Some values of the function include:\n%\n% N Area\n%\n% 2 2 * PI\n% 3 ( 4 / ) * PI\n% 4 ( 2 / 1) * PI**2\n% 5 ( 8 / 3) * PI**2\n% 6 ( 1 / 1) * PI**3\n% 7 (16 / 15) * PI**3\n% 8 ( 1 / 3) * PI**4\n% 9 (32 / 105) * PI**4\n% 10 ( 1 / 12) * PI**5\n%\n% For the unit sphere, Area(N) = N * Volume(N)\n%\n% In Mathematica, the function can be evaluated by:\n%\n% 2 * Pi^(n/2) / Gamma[n/2]\n%\n% Modified:\n%\n% 19 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA.\n% On input, if N_DATA is 0, the first test data is returned, and\n% N_DATA is set to the index of the test data. On each subsequent\n% call, N_DATA is incremented and that test data is returned. When\n% there is no more test data, N_DATA is set to 0.\n%\n% Output, integer N, the spatial dimension.\n%\n% Output, real AREA, the area of the unit sphere \n% in that dimension.\n%\n n_max = 20;\n\n area_vec = [ ...\n 0.2000000000000000E+01, ...\n 0.6283185307179586E+01, ...\n 0.1256637061435917E+02, ...\n 0.1973920880217872E+02, ...\n 0.2631894506957162E+02, ...\n 0.3100627668029982E+02, ...\n 0.3307336179231981E+02, ...\n 0.3246969701133415E+02, ...\n 0.2968658012464836E+02, ...\n 0.2550164039877345E+02, ...\n 0.2072514267328890E+02, ...\n 0.1602315322625507E+02, ...\n 0.1183817381218268E+02, ...\n 0.8389703410491089E+01, ...\n 0.5721649212349567E+01, ...\n 0.3765290085742291E+01, ...\n 0.2396678817591364E+01, ...\n 0.1478625959000308E+01, ...\n 0.8858104195716824E+00, ...\n 0.5161378278002812E+00 ];\n\n n_vec = [ ...\n 1, ...\n 2, ...\n 3, ...\n 4, ...\n 5, ...\n 6, ...\n 7, ...\n 8, ...\n 9, ...\n 10, ...\n 11, ...\n 12, ...\n 13, ...\n 14, ...\n 15, ...\n 16, ...\n 17, ...\n 18, ...\n 19, ...\n 20 ];\n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n n = 0;\n area = 0.0;\n else\n n = n_vec(n_data);\n area = area_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/sphere_unit_area_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140235181256, "lm_q2_score": 0.9019206679615432, "lm_q1q2_score": 0.8720797419528512}} {"text": "function chi = chi_measure ( dim_num, n, z, ns, sample_routine, seed_init )\n\n%*****************************************************************************80\n%\n%% CHI_MEASURE determines the pointset quality measure CHI.\n%\n% Discussion:\n%\n% The CHI measure of point distribution quality for a set Z of\n% N points in an DIM_NUM-dimensional region is defined as follows:\n%\n% Assign every point X in the region to the nearest element\n% Z(I) of the point set. For each Z(I), let H(I) be the maximum\n% distance between Z(I) and any point assigned to it by this process.\n%\n% For each point Z(I), we determine the nearest distinct element of\n% the pointset by\n%\n% GAMMA(I) = minimum ( 1 <= J <= N, I /= J ) distance ( Z(I), Z(J) )\n%\n% Then\n%\n% CHI(I) = 2 * H(I) / GAMMA(I)\n%\n% and\n%\n% CHI = maximum ( 1 <= I <= N ) CHI(I)\n%\n% This quantity can be estimated by using sampling to pick a large\n% number of points in the region, rather than all of them.\n%\n% For an ideally regular mesh, all the CHI(I)'s will be equal.\n% Any deviation from regularity increases the value of some entries\n% of CHI; thus, given two meshes, the one with a lower value of\n% CHI is to be recommended.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 November 2004\n%\n% Author:\n%\n% Max Gunzburger\n% John Burkardt\n%\n% Reference:\n%\n% Max Gunzburger and John Burkardt,\n% Uniformity Measures for Point Samples in Hypercubes.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, real ( kind = 8 ) Z(DIM_NUM,N), the points.\n%\n% Input, integer NS, the number of sample points.\n%\n% Input, character SAMPLE_ROUTINE, the name of the function to be used to\n% return sample points in the region. The function must have the form\n% [ x, seed ] = sample_routine ( dim_num, n, seed )\n%\n% Input, integer SEED_INIT, the initial value of the random number seed.\n%\n% Output, real CHI, the CHI quality measure.\n%\n seed = seed_init;\n h(1:n) = 0.0;\n\n for k = 1 : ns\n\n [ x, seed ] = feval ( sample_routine, dim_num, 1, seed );\n\n closest = find_closest ( dim_num, n, 1, x, z );\n\n dist = sum ( ( x(1:dim_num) - z(1:dim_num,closest(1)) ).^2 );\n\n h(closest(1)) = max ( h(closest(1)), dist );\n\n end\n\n gamma = pointset_spacing ( dim_num, n, z );\n\n chi_vec(1:n) = 2.0 * sqrt ( h(1:n) ) ./ gamma(1:n);\n\n chi = max ( chi_vec(1:n) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quality/chi_measure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620585273153, "lm_q2_score": 0.9086178870347122, "lm_q1q2_score": 0.8720569736751751}} {"text": "function y=sinhSlope3(x)\n%%SINHSLOPE3 Evaluate the function 6*(sinh(x)-x)/x^3 avoiding\n% problems at the point x=0, where the limit equals 1. This\n% function arises in range enclosure algorithms for interval\n% arithmetic.\n%\n%INPUTS: x A vector of matrix of real values at which the function should\n% be evaluated.\n%\n%OUTPUTS: y The value(s) of the function 6*(sinh(x)-x)/x^3 at the\n% point(s) in x.\n%\n%For values of x having magnitude over 1e-2 or for complex values, the\n%function is evaluated as written. For smaller values, a Taylor series\n%expansion is used to avoid the singularity near the origin.\n%\n%This is two times one of the slope function in Table 10.6 of Section\n%10.6.2 of [1]. As the standard says the value at 0 is 1, but the value of\n%the function in the standard at 0 is 1/2, it is assumed that there is a\n%typo in the standard. Hence this function is twice that listed in [1].\n%This file implements the function for non-intervals. See the Interval\n%class for an implementation for Interval arithmetic.\n%\n%REFERENCES:\n%[1] IEEE Standard for Interval Arithmetic,\" in IEEE Std 1788-2015,\n% pp.1-97, June 30 2015.\n%\n%November 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%Allocate space\ny=zeros(size(x));\n\n%For large enough values, use the standard function.\nsel=abs(x)>1e-2|~isreal(x);\nx1=x(sel);\ny(sel)=6*(sinh(x1)-x1)./x1.^3;\n\n%For smaller magnitude values, use an sixth-order Taylor series expansion.\n%The relative error at 10^-2 is on the order of 1e-23, which is less than\n%the precision of a double floating point number at that value. The series\n%is given in Horner form.\nx1=x(~sel);\ny(~sel)=1+x1.^2.*(1/20+x1.^2.*(1/840+x1.^2/60480));\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Slope_Functions/sinhSlope3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297142, "lm_q2_score": 0.9173026635420488, "lm_q1q2_score": 0.871814524541629}} {"text": "function [xx, yy] = secdraw(start_angle, sector_angle, radius)\n\n% usage: [xx, yy] = secdraw(start_angle, sector_angle, radius, clk_wise)\n%\n% Input:\n% start_angle - starting angle in degrees, [0 is default]\n% NOTE: this can be positive or negative\n% sector_angle - central angle of sector in degrees\n% NOTE: if negative, plotting will be clockwise\n% direction. \n% radius - radius of sector (default 1)\n%\n% Output: \n% returns the corner points (xx, yy) of a patch for a sector,\n% which can plotted using the patch(...) function\n% NOTE:\n% 1. if less than 2 or NO output variables are given, \n% secdraw(...) draws the sector on the current (or a new)\n% figure\n% 2. if one argument is given, \n% the argument is taken as the central angle \n%\n% Example 1 > [xx, yy] = secdraw(45, 90, 10);\n% patch( xx, yy, 'b', 'EdgeColor', 'b', 'EraseMode', 'none') ;\n% set( gca, 'DataAspectRatio', [1 1 1] );\n% - this will draw a sector from 45 to 90 degrees with radius=1\n%\n% Example 2 > secdraw( 60 )\n% - this will draw a sector from 0 to 60 degrees counter\n% clockwise\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% author: Laine Berhane Kahsay\n% \n% date : 19-Feb-2004\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin < 1 | isempty( nargin ) \n %disp '';\n disp '-- error in usage --------------------------------';\n disp ' Not enough input arguments.'; \n help secdraw;\n return;\nelseif nargin == 1 \n sector_angle = start_angle;\n start_angle = 0;\n radius = 1;\nelse nargin == 2\n radius = 1;\nend\n\ntheta0 = pi*0/180; % offset angle in radians\ntheta1 = pi*start_angle/180; % starting angle in radians\ntheta = pi*sector_angle/180; % central angle in radians\n\nangle_ratio = theta/(2*pi); % ratio of the sector to the complete circle\nrho = abs(radius); % abs(...) can be removed\nMaxPts = 100; % maximum number of points in a whole circle.\n % if set to small # (e.g 10) the resolution\n % of the curve will be poor. \n % generally values greater than 50\n % will give (very) good resolution\n\nn = abs( ceil( MaxPts*angle_ratio ) );\nr = [ 0; rho*ones(n+1,1); 0 ];\ntheta = theta0 + theta1 + [ 0; angle_ratio*(0:n)'/n; 0 ]*2*pi;\n\n% output\n[xx,yy] = pol2cart(theta,r);\n\n% plot if not enough output variable are given\nif nargout < 2,\n hh=patch(xx, yy, 'b','EdgeColor','b','EraseMode','none');\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/4503-sector-plot/SecDraw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9390248140158416, "lm_q2_score": 0.9284088079835903, "lm_q1q2_score": 0.8717989082474601}} {"text": "classdef HypergeometricD\n%%HYPERGEOMETRICD Functions to handle the scalar hypergeometric\n% distribution. Given an urn containg N1+N2 objects, N2 of\n% type 1 and N2 of type 2, choose N balls. The number of\n% balls of type 1 that is chosen is given by a\n% hypergeometric distribution with parameters n, N1 and N2.\n%Implemented methods are: mean, var, PMF, CDF, rand\n%\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release. \n \nmethods(Static)\nfunction val=mean(n,N1,N2)\n%%MEAN Obtain the mean of the hypergeometric distribution.\n% \n%INPUTS: n The total number of objects drawn. n<=N1+N2.\n% N1 The number of objects of type 1.\n% N2 The number of objectes of type 2. \n%\n%OUTPUTS: val The mean of the hypergeometric distribution under\n% consideration. \n%\n%The hypergeometric distribution is given in Chapter 2.8 of [1].\n%\n%EXAMPLE:\n%We verify that the computed variance by comparing it to the sample\n%variance.\n% n=20;\n% N1=63;\n% N2=28;\n% varVal=HypergeometricD.mean(n,N1,N2)\n% numSamp=1e3;\n% sampVarVal=mean(HypergeometricD.rand([1,numSamp],n,N1,N2))\n%One will find both values are about 13.836\n%\n%REFERENCES:\n%[1] S. M. Ross, Simulation, 4th ed. Amsterdam: Academic Press, 2006.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=n*N1/(N1+N2);\nend\n \nfunction val=var(n,N1,N2)\n%%VAR Obtain the variance of the hypergeometric distribution.\n% \n%INPUTS: n The total number of objects drawn. n<=N1+N2.\n% N1 The number of objects of type 1.\n% N2 The number of objectes of type 2. \n%\n%OUTPUTS: val The variance of the hypergeometric distribution under\n% consideration. \n%\n%The hypergeometric distribution is given in Chapter 2.8 of [1].\n%\n%EXAMPLE:\n%We verify that the computed variance by comparing it to the sample\n%variance.\n% n=20;\n% N1=63;\n% N2=28;\n% varVal=HypergeometricD.var(n,N1,N2)\n% numSamp=1e3;\n% sampVarVal=var(HypergeometricD.rand([1,numSamp],n,N1,N2))\n%One will find both values are about 3.36.\n%\n%REFERENCES:\n%[1] S. M. Ross, Simulation, 4th ed. Amsterdam: Academic Press, 2006.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=n*N1*N2/(N1+N2)^2*(1-(n-1)/(N1+N2-1));\nend\n \nfunction val=PMF(x,n,N1,N2)\n%%PMF Evaluate the hypergeometric probability mass function (PMF) at given\n% points.\n%\n%INPUTS: x The point(s) at which the hypergeometric PMF is evaluated.\n% n The total number of objects drawn. n<=N1+N2.\n% N1 The number of objects of type 1.\n% N2 The number of objectes of type 2.\n%\n%OUTPUTS: val The PMF of the hypergeometric distribution evaluated at the\n% desired point(s).\n%\n%The hypergeometric distribution is given in Chapter 2.8 of [1].\n%\n%EXAMPLE:\n%Here, we validate the PMF by generating random samples and comparing the\n%PMF plot with a histogram of the random samples.\n% n=20;\n% N1=25;\n% N2=15;\n% numSamples=1e5;\n% figure(1)\n% clf\n% histogram(HypergeometricD.rand([numSamples,1],n,N1,N2),'BinWidth',1,'Normalization','pdf')\n% hold on\n% x=0:20;\n% vals=HypergeometricD.PMF(x,n,N1,N2);\n% stem(x,vals,'linewidth',2)\n% h1=xlabel('x');\n% h2=ylabel('PDF(x)');\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%One will see that the histogram matches well with the plot.\n%\n%REFERENCES:\n%[1] S. M. Ross, Simulation, 4th ed. Amsterdam: Academic Press, 2006.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=zeros(size(x));\n numEls=numel(x);\n\n denom=binomial(N1+N2,n);\n for curEl=1:numEls\n i=x(curEl);\n if(i>0&&i<=n)\n val(curEl)=binomial(N1,i).*binomial(N2,n-i)/denom;\n end\n end\nend\n \nfunction val=CDF(x,n,N1,N2)\n%%CDF Evaluate the cumulative distribution function of the hypergeometric\n% distribution at desired points.\n%\n%INPUTS: x The point(s) at which the hypergeometric CDF is evaluated.\n% n The total number of objects drawn. n<=N1+N2.\n% N1 The number of objects of type 1.\n% N2 The number of objectes of type 2.\n%\n%OUTPUTS: val The CDF of the hypergeometric distribution evaluated at the\n% desired point(s).\n%\n%The hypergeometric distribution is given in Chapter 2.8 of [1].\n%\n%EXAMPLE:\n%We validate the CDF value by comparing it to a value computed from random\n%samples.\n% n=20;\n% N1=25;\n% N2=15;\n% x=12;\n% numSamples=1e5;\n% prob=HypergeometricD.CDF(x,n,N1,N2)\n% probSamp=mean(HypergeometricD.rand([numSamples,1],n,N1,N2)<=x)\n%One will find the values of both be about 0.5.\n%\n%REFERENCES:\n%[1] S. M. Ross, Simulation, 4th ed. Amsterdam: Academic Press, 2006.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=zeros(size(x));\n numEls=numel(x);\n\n denom=binomial(N1+N2,n);\n for curEl=1:numEls\n i=floor(x(curEl));\n if(i>0&&i<=n)\n %Just sum the numerators in the PDF and normalize. This is\n %slow if N1+N2 is large.\n\n sumVal=0;\n for k=0:i\n sumVal=sumVal+binomial(N1,k).*binomial(N2,n-k);\n end\n val(curEl)=sumVal/denom;\n elseif(i>n)\n val(curEl)=1; \n end\n end\nend\n \nfunction x=rand(N,n,N1,N2)\n%%RAND Generate hypergeometric random variables.\n%\n%INPUTS: N If N is a scalar, then rand returns an NXN matrix of random\n% variables. If N=[M,N1] is a two-element row vector, then rand\n% returns an MXN1 matrix of random variables.\n% n The total number of objects drawn. n<=N1+N2.\n% N1 The number of objects of type 1.\n% N2 The number of objectes of type 2.\n%\n%OUTPUTS: vals A matrix whose dimensions are determined by N of the\n% generated hypergeometric random variables.\n%\n%The inverse transform method fo Chapter 4.1 of [1] is used.\n%\n%REFERENCES:\n%[1] S. M. Ross, Simulation, 4th ed. Amsterdam: Academic Press, 2006.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n \n if(isscalar(N))\n dims=[N N];\n else\n dims=N;\n end\n\n denom=binomial(N1+N2,n);\n\n x=zeros(dims);\n numEls=prod(dims);\n \n for curEl=1:numEls\n U=rand();\n cumProb=0;\n for k=0:n\n cumProb=cumProb+binomial(N1,k).*binomial(N2,n-k)/denom;\n\n if(U<=cumProb)\n break;\n end\n end\n x(curEl)=k;\n end\nend\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/Distributions/HypergeometricD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.920789673173896, "lm_q1q2_score": 0.8716164358066875}} {"text": "% 样条插值举例\nclear; clc\n\nX = [27.7, 28, 29, 30];\nY = [4.1, 4.3, 4.1, 3.0];\ndf0 = 3.0; dfn = -4.0; % 第一类边界条件\n\nn = length(X) - 1;\nH = diff(X); % 每个插值小区间的长度\nmu = H(1:n-1) ./ (H(1:n-1) + H(2:n));\nlambda = 1 - mu;\n% 计算二阶差商\nY1 = diff(Y) ./ diff(X); % 一阶差商\nY2 = diff(Y1) ./ ( X(3:end) - X(1:end-2) ); % 二阶差商\n% 计算右端项\nd = 6*Y2;\nd0 = 6/H(1) * (Y1(1) - df0);\ndn = 6/H(end) * (dfn - Y1(end));\n% 给出系数矩阵\nA = 2*eye(n+1) + diag([mu(:);1],-1) +diag([1;lambda(:)],1);\nb = [d0; d(:); dn];\nM = A\\b;\n\n% 计算 s_k(x) 的系数, 两种形式\np = zeros(n,4); p0 = zeros(n,4); \nfor k = 1 : n\n p(k,1) = (M(k+1) - M(k))/(6*H(k));\n p(k,2) = M(k)/2;\n p(k,3) = (Y(k+1) - Y(k))/ H(k) - H(k)/6 * (2*M(k) + M(k+1));\n p(k,4) = Y(k);\n p0(k,1) = M(k)/(6*H(k));\n p0(k,2) = M(k+1)/(6*H(k));\n p0(k,3) = (Y(k) - M(k)*H(k)*H(k)/6) / H(k);\n p0(k,4) = (Y(k+1) - M(k+1)*H(k)*H(k)/6) / H(k);\nend\n\n% 调用 Matlab 的三次样条插值函数\npp = spline(X, [df0;Y(:);dfn]);\n\n%输出结果\nfprintf('按形式一输出: \\n'); disp(p0);\nfprintf('按形式二输出: \\n'); disp(p);\nfprintf('spline的结果(形式二): \\n'); disp(pp.coefs);\n", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/第二章 插值方法/demo_2_11.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813545264446, "lm_q2_score": 0.9111797154386841, "lm_q1q2_score": 0.8710708185820937}} {"text": "function val=numInvolutions(n)\n%%NUMINVOLUTIONS Determine the number of involutions of length n. An\n% involution is a permution of items 1:n such that the\n% permutation is its own inverse. The number of involutions\n% also equals the number of possible Young tableau having n\n% cells.\n%\n%INPUTS: n A positive integer >=0.\n%\n%OUTPUTS: val The number of involutions of length n. For n=0, this is\n% defined as 1.\n%\n%This function uses the recurrence relation given in Equation 40 in Section\n%5.1.4 of [1].\n%\n%REFERENCES:\n%[1] D. Knuth, The Art of Computer Programming: Sorting and Searching, 2nd\n% ed. Boston: Addison-Wesley, 2018, vol. 3.\n%\n%November 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(n<0)\n error('n must be >=0.')\nend\n\nif(n<=1)\n val=1;\n return;\nend\n\nan1=1;\nan=1;\nfor k=2:n\n an2=an1;\n an1=an;\n an=an1+(k-1)*an2; \nend\nval=an;\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Combinatorics/numInvolutions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474181553805, "lm_q2_score": 0.9124361664296878, "lm_q1q2_score": 0.8710548305136945}} {"text": "function [optN, C, N] = sshist(x,N)\n% [optN, C, N] = sshist(x,N)\n%\n% Function `sshist' returns the optimal number of bins in a histogram\n% used for density estimation.\n% Optimization principle is to minimize expected L2 loss function between \n% the histogram and an unknown underlying density function.\n% An assumption made is merely that samples are drawn from the density\n% independently each other.\n%\n% The optimal binwidth D* is obtained as a minimizer of the formula, \n% (2K-V) / D^2,\n% where K and V are mean and variance of sample counts across bins with width D.\n% Optimal number of bins is given as (max(x) - min(x)) / D*.\n%\n% For more information, visit \n% http://2000.jukuin.keio.ac.jp/shimazaki/res/histogram.html\n%\n% Original paper:\n% Hideaki Shimazaki and Shigeru Shinomoto\n% A method for selecting the bin size of a time histogram\n% Neural Computation 19(6), 1503-1527, 2007\n% http://dx.doi.org/10.1162/neco.2007.19.6.1503\n%\n% Example usage:\n% optN = sshist(x); hist(x,optN);\n%\n% Input argument\n% x: Sample data vector.\n% N (optinal):\n% A vector that specifies the number of bins to be examined. \n% The optimal number of bins is selected from the elements of N. \n% Default value is N = 2:50.\n% * Do not search binwidths smaller than a sampling resolution of data.\n%\n% Output argument\n% optN: Optimal number of bins.\n% N: Bin numbers examined.\n% C: Cost function of N.\n%\n% See also SSKERNEL\n%\n% Copyright (c) 2009 2010, Hideaki Shimazaki All rights reserved.\n% http://2000.jukuin.keio.ac.jp/shimazaki\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Parameters Setting\nx = reshape(x,1,numel(x));\nx_min = min(x);\nx_max = max(x);\n\nif nargin < 2\n buf = abs(diff(sort(x)));\n dx = min(buf(logical(buf ~= 0)));\n N_MIN = 2; % Minimum number of bins (integer)\n % N_MIN must be more than 1 (N_MIN > 1). \n N_MAX = min(floor((x_max - x_min)/(2*dx)),50);\n % Maximum number of bins (integer)\n N = N_MIN:N_MAX; % # of Bins\nend\n \nSN = 30; % # of partitioning positions for shift average\nD = (x_max - x_min) ./ N; % Bin Size Vector\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Computation of the Cost Function\nCs = zeros(length(N),SN);\nfor i = 1: length(N)\n\n shift = linspace(0,D(i),SN);\n for p = 1 : SN\n edges = linspace(x_min+shift(p)-D(i)/2,...\n x_max+shift(p)-D(i)/2,N(i)+1); % Bin edges\n\n ki = histc(x,edges); % Count # of events in bins\n ki = ki(1:end-1);\n\n k = mean(ki); % Mean of event count\n v = sum( (ki-k).^2 )/N(i); % Variance of event count\n\n Cs(i,p) = ( 2*k - v ) / D(i)^2; % The Cost Function\n end\n\nend\nC = mean(Cs,2);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Optimal Bin Size Selectioin\n[Cmin idx] = min(C);\noptN = N(idx); % Optimal number of bins\n%optD = D(idx); % *Optimal binwidth\n%edges = linspace(x_min,x_max,N(idx)); % Optimal segmentation\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/24913-histogram-binwidth-optimization/sshist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778012346835, "lm_q2_score": 0.9099070084811306, "lm_q1q2_score": 0.8710337804068452}} {"text": "function [ ] = montyhall(n,d,o)\n%montyhall(n,d,o) Simulates n rounds of the Monty Hall problem and\n% gives win/loss ratio\n%\n% n : Number of rounds to simulate (Any positive integer)\n% d : Number of doors (Positive integer >= 3)\n% o=0 : Show final win/loss score and estimated probability\n% o=1 : Show win/loss tally chart and estimated probability\n% o=2 : Show results for each round\n%\n% All parameters are optional, by default they will take the values:\n% n=1, d=3, o=0.\n% \n% The Monty Hall problem is a probability puzzle based on the American\n% television game show Let's Make a Deal. The name comes from the show's\n% host, Monty Hall. The problem is also called the Monty Hall paradox,\n% as it is a veridical paradox in that the result appears absurd but is\n% demonstrably true.\n% http://en.wikipedia.org/wiki/Monty_Hall_problem\n% \n%\n%------------------------%\n\nwin=0;lose=0;tally=[0;0];Monty=0;\n%-- Check for nonexistent variables and set to defaults\nif exist('n')~=1, n=1; end\nif exist('d')~=1 || d<3 || d~=round(d), d=3; end\nif exist('o')~=1, o=0; end\n%--\n\nif o==2\n for i = 1:n\n %-- Picks a random door for the car to be behind\n Car = randi(d)-1;\n %-- Player picks a random door\n Choose = randi(d)-1;\n %-- Monty recursively picks a random door until he has chosen\n % the door that neither has the car behind it or has been\n % chosen by the player\n while (Monty==Car || Monty==Choose), Monty=randi(d)-1; end\n %-- If you originally choose the car, no matter what door Monty\n % opens, you will lose by switching.\n % If you originally choose a goat, Monty has to open a door to\n % reveal the other goat, and switching will switch to the car\n % meaning you win.\n % Simply put, if you originally choose the car, switching wins\n % and if you don't, switching loses.\n % This is the basis of the score tally system\n if Choose==Car, lose=lose+1; else win=win+1; end\n %-- Display round results after game has been played.\n disp(['Round ',num2str(i)]);\n disp('Chosen door:');disp([zeros(1,Choose),1,zeros(1,(d-1)-Choose)]);\n if CarChoose, disp('Monty opens:');disp([ones(1,Choose),0,ones(1,Car-Choose-1),0,ones(1,(d-1)-Car)]); end\n if Car==Choose\n if Car=10, disp(['Estimated Chance Of Winning After Switch: ',num2str(win/n)]); end\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26398-monty-hall/montyhall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.9207896780646392, "lm_q1q2_score": 0.8708840470792358}} {"text": "function M = Pythagor_tree(m,n,Colormap)\n% function M = Pythagor_tree(m,n,Colormap)\n% Compute Pythagoras_tree\n% The Pythagoras Tree is a plane fractal constructed from squares.\n% It is named after Pythagoras because each triple of touching squares \n% encloses a right triangle, in a configuration traditionally used to\n% depict the Pythagorean theorem.\n% http://en.wikipedia.org/wiki/Pythagoras_tree\n%\n% Input : \n% - m ( double m> 0) is the relative length of one of the side\n% right-angled triangle. The second side of the right-angle is \n% taken to be one.\n% To have a symmetric tree, m has to be 1.\n% - n ( integer ) is the level of recursion.\n% The number of elements of tree is equal to 2^(n+1)-1.\n% A reasonnable number for n is 10.\n% - Colormap: String used to generate color of the different levels\n% of the tree.\n% All these arguments are optional: the function can run with\n% argument.\n% Output : \n% - Matrix M: Pyhagoras tree is stored in a matrix M.\n% This matrix has 5 columns.\n% Each row corresponds to the cordinate of each square of the tree\n% The two first columns give the bottom-left position of each\n% square. The third column corresponds to the orientation angle of\n% each square. The fourth column gives the size of each square. The\n% fifth column specifies the level of recursion of each square.\n% The first row corresponds to the root of the tree. It is always\n% the same\n% M(1,:) = [0 -1 0 1 1];\n% The leaf located at row i will give 2 leaves located at 2*i and\n% 2*i+1.\n% - A svg file giving a vectorial display of the tree. The name of\n% file is generated from the parameter m,n,Colormap. The file is\n% stored in the current folder.\n%\n% 2010 02 29\n% Guillaume Jacquenot\n% guillaume dot jacquenot at gmail dot com\n\n%% Check inputs\nnarg = nargin;\nif narg <= 2\n % Colormap = 'jet';\n Colormap = 'summer';\n if narg <= 1\n n = 12; % Recursion level \n if nargin == 0\n m = 0.8;\n end\n end\nend\nif m <= 0\n\terror([mfilename ':e0'],'Length of m has to be greater than zero');\nend\nif rem(n,1)~=0\n\terror([mfilename ':e0'],'The number of level has to be integer');\nend\nif ~iscolormap(Colormap)\n\terror([mfilename ':e1'],'Input colormap is not valid');\nend\n%% Compute constants\nd = sqrt(1+m^2); % \nc1 = 1/d; % Normalized length 1\nc2 = m/d; % Normalized length 2\nT = [0 1/(1+m^2);1 1+m/(1+m^2)]; % Translation pattern \nalpha1 = atan2(m,1); % Defines the first rotation angle\nalpha2 = alpha1-pi/2; % Defines the second rotation angle\npi2 = 2*pi; % Defines pi2\nnEle = 2^(n+1)-1; % Number of elements (square)\nM = zeros(nEle,5); % Matrice containing the tree\nM(1,:) = [0 -1 0 1 1]; % Initialization of the tree\n\n%% Compute the level of each square contained in the resulting matrix\nOffset = 0;\nfor i = 0:n\n tmp = 2^i;\n M(Offset+(1:tmp),5) = i;\n Offset = Offset + tmp;\nend\n%% Compute the position and size of each square wrt its parent\nfor i = 2:2:(nEle-1)\n j = i/2;\n mT = M(j,4) * mat_rot(M(j,3)) * T;\n Tx = mT(1,:) + M(j,1);\n Ty = mT(2,:) + M(j,2); \n theta1 = rem(M(j,3)+alpha1,pi2);\n theta2 = rem(M(j,3)+alpha2,pi2);\n M(i ,1:4) = [Tx(1) Ty(1) theta1 M(j,4)*c1];\n M(i+1,1:4) = [Tx(2) Ty(2) theta2 M(j,4)*c2];\nend\n%% Display the tree\nPythagor_tree_plot(M,n);\n\n%% Write results to an SVG file\nPythagor_tree_write2svg(m,n,Colormap,M);\n\nfunction Pythagor_tree_write2svg(m,n,Colormap,M)\n% Determine the bounding box of the tree with an offset\n% Display_metadata = false;\nDisplay_metadata = true;\n\nnEle = size(M,1);\nr2 = sqrt(2);\nLOffset = M(nEle,4) + 0.1;\nmin_x = min(M(:,1)-r2*M(:,4)) - LOffset;\nmax_x = max(M(:,1)+r2*M(:,4)) + LOffset;\nmin_y = min(M(:,2) ) - LOffset; % -r2*M(:,4)\nmax_y = max(M(:,2)+r2*M(:,4)) + LOffset;\n\n% Compute the color of tree\nColorM = zeros(n+1,3);\neval(['ColorM = flipud(' Colormap '(n+1));']);\nco = 100;\nWfig = ceil(co*(max_x-min_x));\nHfig = ceil(co*(max_y-min_y));\nfilename = ['Pythagoras_tree_1_' strrep(num2str(m),'.','_') '_'...\n num2str(n) '_' Colormap '.svg'];\nfid = fopen(filename, 'wt');\nfprintf(fid,'\\n');\nif ~Display_metadata\n fprintf(fid,'\\n');\nend\nfprintf(fid,'\\n');\n\nif Display_metadata\n fprintf(fid,'\\tPythagoras tree\\n');\n fprintf(fid,'\\t\\n');\n fprintf(fid,'\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\timage/svg+xml\\n');\n fprintf(fid,'\\t\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\tPythagoras tree\\n');\n fprintf(fid,'\\t\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\t\\t\\tGuillaume Jacquenot\\n');\n fprintf(fid,'\\t\\t\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\t\\n');\n fprintf(fid,'\\t\\t\\n');\n fprintf(fid,'\\t\\n'); \nend\nfprintf(fid,'\\t\\n');\nfprintf(fid,'\\t\\t\t\\n');\nfprintf(fid,'\\t\\n');\nfprintf(fid,'\\t\\n',...\n round(co*max_x),round(co*max_y));\nfor i = 0:n\n fprintf(fid,'\\t\\t\\n',...\n generate_color_hexadecimal(ColorM(i+1,:))); \n Offset = 2^i-1;\n for j = 1:2^i\n k = j + Offset;\n fprintf(fid,['\\t\\t\\t\\n'],...\n co*M(k,1),co*M(k,2),M(k,3)*180/pi,M(k,4)); \n end\n fprintf(fid,'\\t\\t\\n');\nend\nfprintf(fid,'\\t\\n');\nfprintf(fid,'\\n');\nfclose(fid);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction M = mat_rot(x)\nc = cos(x);\ns = sin(x);\nM=[c -s; s c];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction H = Pythagor_tree_plot(D,ColorM)\nif numel(ColorM) == 1\n ColorM = flipud(summer(ColorM+1));\nend\nH = figure('color','w');\nhold on\naxis equal\naxis off\nfor i=1:size(D,1)\n cx = D(i,1);\n cy = D(i,2);\n theta = D(i,3);\n si = D(i,4); \n M = mat_rot(theta);\n x = si*[0 1 1 0 0];\n y = si*[0 0 1 1 0];\n pts = M*[x;y];\n fill(cx+pts(1,:),cy+pts(2,:),ColorM(D(i,5)+1,:));\n % plot(cx+pts(1,1:2),cy+pts(2,1:2),'r');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Scolor = generate_color_hexadecimal(color)\nScolor = '000000';\nfor i=1:3\n c = dec2hex(round(255*color(i)));\n if numel(c)==1\n Scolor(2*(i-1)+1) = c;\n else\n Scolor(2*(i-1)+(1:2)) = c;\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction res = iscolormap(cmap)\n% This function returns true if 'cmap' is a valid colormap\nLCmap = {...\n 'autumn'\n 'bone'\n 'colorcube'\n 'cool'\n 'copper'\n 'flag'\n 'gray'\n 'hot'\n 'hsv'\n 'jet'\n 'lines'\n 'pink'\n 'prism'\n 'spring'\n 'summer'\n 'white'\n 'winter'\n};\n\nres = ~isempty(strmatch(cmap,LCmap,'exact'));\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26816-pythagoras-tree/Pythagor_tree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9539660962919971, "lm_q2_score": 0.9124361509525462, "lm_q1q2_score": 0.8704331530398959}} {"text": "function xyz = rtp_to_xyz ( r, theta, phi )\n\n%*****************************************************************************80\n%\n%% RTP_TO_XYZ converts (R,Theta,Phi) to (X,Y,Z) coordinates.\n%\n% Discussion:\n%\n% R measures the distance of the point to the origin.\n%\n% Theta measures the \"longitude\" of the point, between 0 and 2 PI.\n%\n% PHI measures the angle from the \"north pole\", between 0 and PI.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, THETA, PHI, the radius, longitude, and\n% declination of a point.\n%\n% Output, real XYZ(3,1), the corresponding Cartesian coordinates.\n%\n xyz = zeros ( 3, 1 );\n\n xyz(1,1) = r * cos ( theta ) * sin ( phi );\n xyz(2,1) = r * sin ( theta ) * sin ( phi );\n xyz(3,1) = r * cos ( phi );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/rtp_to_xyz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9621075777163566, "lm_q2_score": 0.9046505293168444, "lm_q1q2_score": 0.870371129440849}} {"text": "function h = circle_segment_height_from_area ( r, area )\n\n%*****************************************************************************80\n%\n%% CIRCLE_SEGMENT_HEIGHT_FROM_AREA: height of a circle segment from area.\n%\n% Discussion:\n%\n% Begin with a circle of radius R. Choose two points P1 and P2 on the\n% circle, and draw the chord P1:P2. This chord divides the circle\n% into two pieces, each of which is called a circle segment.\n% Consider one of the pieces. The \"angle\" of this segment is the angle \n% P1:C:P2, where C is the center of the circle. Let Q be the point on \n% the chord P1:P2 which is closest to C. The \"height\" of the segment\n% is the distance from Q to the perimeter of the circle.\n%\n% This function is given the radius R and area of the segment, and\n% determines the corresponding height.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 16 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, the radius of the circle.\n% 0 < R.\n%\n% Input, real AREA, the area of the circle segment.\n% 0 <= AREA <= 2.0 * PI * R^2.\n%\n% Output, real H, the height of the circle segment.\n%\n if ( area < 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CIRCLE_SEGMENT_HEIGHT_FROM_AREA - Fatal error!\\n' );\n fprintf ( 1, ' AREA < 0.0.\\n' );\n error ( 'CIRCLE_SEGMENT_HEIGHT_FROM_AREA - Fatal error!' );\n end\n\n area_circle = 2.0 * pi * r^2;\n\n if ( area == 0.0 )\n h = 0.0;\n return\n end\n\n if ( area == area_circle )\n h = 2.0 * r;\n return\n end\n\n if ( area_circle < area )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CIRCLE_SEGMENT_HEIGHT_FROM_AREA - Fatal error!\\n' );\n fprintf ( 1, ' 2.0 * pi * r^2 < AREA.\\n' );\n error ( 'CIRCLE_SEGMENT_HEIGHT_FROM_AREA - Fatal error!' );\n end\n\n if ( r <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CIRCLE_SEGMENT_HEIGHT_FROM_AREA - Fatal error!\\n' );\n fprintf ( 1, ' R <= 0.0.\\n' );\n error ( 'CIRCLE_SEGMENT_HEIGHT_FROM_AREA - Fatal error!' );\n end\n\n h1 = 0.0;\n a1 = circle_segment_area_from_height ( r, h1 );\n h2 = 2.0 * r;\n a2 = circle_segment_area_from_height ( r, h2 );\n\n it = 0;\n\n while ( it < 30 )\n\n h = 0.5 * ( h1 + h2 );\n a = circle_segment_area_from_height ( r, h );\n it = it + 1;\n\n if ( abs ( a - area ) < sqrt ( eps ) * area )\n break\n end\n\n if ( a < area )\n h1 = h;\n a1 = a;\n else\n h2 = h;\n a2 = a;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/circle_segment/circle_segment_height_from_area.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.9353465080392795, "lm_q1q2_score": 0.8703008765453867}} {"text": "function HaarTransformationMatrix=ConstructHaarWaveletTransformationMatrix(WidthOfSquareMatrix)\n%--------------------------------------------------------------------------\n%Create Haarwavelet transformation matrix H for the matrix vector\n%mulplication implimentation of Haar wavelet transformation.\n%This function uses the following nice formula to create the Haar\n%transformation matrix:\n% H_n=1/sqrt(2)[H_(n/2) kron (1 1)\n% I_(n/2) kron (1 -1)],\n% where 'kron' denotes the kronecker product.\n%The iteration starts with H_1=[1]. The normalization constant 1/sqrt(2)\n%ensure that H_n^T*H_n=I, where I is identity matrix. Haar wavelets are the\n%rows of H_n.\n%--------------------------------------------------------------------------\n%function HaarTransformationMatrix=ConstructHaarWaveletTransformationMatrix(WidthOfSquareMatrix)\n% Input:\n% WidthOfSquareMatrix: the width of sqaure Haar wavelet\n% transformation matrix. \n% Output:\n% HaarTransformationMatrix: Ceated Haar transformation matrix and\n% it's size is the power of 2,i.e., 2, 4,\n% 8,16,32,64,128,256,512,1024,2048,4096,etc.\n%--------------------------------------------------------------------------\n%Author: Jin Qi\n%Email: jqichina@hotmail.com\n%Date: 11/4/2011\n%--------------------------------------------------------------------------\n%Test function for one dimentional signal\n%\n% n=8;\n% S=rand(n,1); % for one dimentional signal\n% H=ConstructHaarWaveletTransformationMatrix(n);\n% C=H*S; %Haar wavelet transformation\n% RS=H'*C;% Reconstruct signal\n% fprintf('reconstruction error is %f',norm(S-RS));%plot reconstruction error\n%--------------------------------------------------------------------------\n%Test for two dimentional signal,ie. image\n%\n% n=8;\n% S=rand(n,n); % for one dimentional signal\n% H=ConstructHaarWaveletTransformationMatrix(n);\n% C=H*S*H'; %Haar wavelet transformation\n% RS=H'*C*H;% Reconstruct signal\n% fprintf('reconstruction error is %f',norm(S-RS,'fro'));%plot reconstruction error\n\nn=WidthOfSquareMatrix; % copy the parameter\n\n% check input parameter and make sure it's the power of 2\nLevel=log2(n);\nif 2^Level=q, compute\n% the principal angles and vectors between the matrices. This can\n% be used in canonical correlation analysis to find combinations\n% of variables with maximum correlation between each other.\n% Specifically, the principle angles are defined recursively by\n% d(k)=cos(theta_k)=F(:,k)'*G(:,k)=\n% max_{F(:,k)} max_{G(:,k)} F(:,k)'*G(:,k)\n% where in the optimization F(:,k) is a unit vector in the space\n% spanned by A that is orthogonal to all F(:,i) with isize(A,2))\n error('The number of columns of B must be <= the number of columns of A.') \nend\n\n[QA,~]=qr(A,0);\n[QB,~]=qr(B,0);\n[Y,D,Z]=svd(QA'*QB);\nF=QA*Y(:,1:q);\nG=QB*Z(:,1:q);\nd=diag(D);\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Basic_Matrix_Operations/principalAngVec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611563610179, "lm_q2_score": 0.9059898203834278, "lm_q1q2_score": 0.8700774315547396}} {"text": "function val=greatestCommonDivisor(m,n)\n%%GREATESTCOMMONDIVISOR Given two integers m and n, determine the integer\n% that is the greatest common divisor. This is like the gcd\n% function that is built into Matlab, but it can be useful to\n% have an explcit function if one wishes to use a different data\n% type with appropriately overloaded operators, such as for\n% extended precision arithmetic.\n%\n%INPUTS: m, n Two positive real integers.\n%\n%OUTPUTS: val The greatest common divisor of the integers.\n%\n%This function implements Algorithm F in Problem 3 of Section 1.1 of [1].\n%\n%EXAMPLE:\n% val=greatestCommonDivisor(24,32)\n%One will get val=8.\n%\n%REFERENCES:\n%[1] D. E. Knuth, The Art of Computer Programming. Vol. 1: Fundamental\n% Algorithms, 3rd Edition, Boston: Addison-Wesley, 2011.\n%\n%October 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nwhile(1)\n %Step F1\n m=rem(m,n);\n\n %Step F2\n if(m==0)\n val=n;\n return\n end\n\n %Step F3\n n=rem(n,m);\n\n %Step F4\n if(n==0)\n val=m;\n return\n end\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/greatestCommonDivisor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9390248242542284, "lm_q2_score": 0.9263037292767219, "lm_q1q2_score": 0.8698221965901102}} {"text": "function dists = eucl(crds1,crds2)\n% EUCL: Calculates the euclidean distances among a set of points, or between a\n% reference point and a set of points, or among all possible pairs of two \n% sets of points, in P dimensions. Returns a single distance for two points.\n%\n% Syntax: dists = eucl(crds1,crds2)\n%\n% crds1 = [N1 x P] matrix of point coordinates. If N=1, it is taken to\n% be the reference point.\n% crds2 = [N2 x P] matrix of point coordinates. If N=1, it is taken to\n% be the reference point.\n% -----------------------------------------------------------------------\n% dists = [N1 x N1] symmetric matrix of pairwise distances (if only crds1\n% is specified);\n% [N1 x 1] col vector of euclidean distances (if crds1 & ref\n% are specified);\n% [1 x N2] row vector of euclidean distances (if ref & crds2\n% are specified);\n% [N1 x N2] rectangular matrix of pairwise distances (if crds1\n% & crds2 are specified);\n% [1 x 1] scalar (if crds1 is a [2 x P] matrix or ref1 & ref2\n% are specified);\n%\n\n% RE Strauss, 5/4/94\n% 10/28/95 - output row (rather than column) vector for the (reference\n% point)-(set of points) case; still outputs column vector for the\n% (set of points)-(reference point) case.\n% 10/30/95 - for double for-loops, put one matrix-col access in outer loop\n% to increase speed.\n% 10/12/96 - vectorize inner loop to increase speed.\n% 6/12/98 - allow for P=1.\n% 11/11/03 - initialize dists to NaN for error return.\n\n if nargin == 0, help eucl; return; end\n dists = NaN;\n\n if (nargin < 2) % If only crds1 provided,\n [N,P] = size(crds1);\n if (N<2)\n error(' EUCL: need at least two points');\n end\n\n crds1 = crds1'; % Transpose crds\n dists = zeros(N,N); % Calculate pairwise distances\n\n for i = 1:N-1\n c1 = crds1(:,i) * ones(1,N-i);\n if (P>1)\n d = sqrt(sum((c1-crds1(:,(i+1:N))).^2));\n else\n d = abs(c1-crds1(:,(i+1:N)));\n end\n dists(i,(i+1:N)) = d;\n dists((i+1:N),i) = d';\n end\n if (N==2) % Single distance for two points\n dists = dists(1,2);\n end\n\n else % If crds1 & crds2 provided,\n [N1,P1] = size(crds1);\n [N2,P2] = size(crds2);\n if (P1~=P2)\n error(' EUCL: sets of coordinates must be of same dimension');\n else\n P = P1;\n end\n\n crds1 = crds1'; % Transpose crds\n crds2 = crds2';\n\n if (N1>1 && N2>1) % If two matrices provided,\n dists = zeros(N1,N2); % Calc all pairwise distances between them\n for i = 1:N1\n c1 = crds1(:,i) * ones(1,N2);\n if (P>1)\n d = sqrt(sum((c1-crds2).^2));\n else\n d = abs(c1-crds2);\n end\n dists(i,:) = d;\n end\n end\n\n if (N1==1 && N2==1) % If two vectors provided,\n dists = sqrt(sum((crds1-crds2).^2)); % Calc scalar\n end\n\n if (N1>1 && N2==1) % If matrix && reference point provided,\n crds1 = crds1 - (ones(N1,1)*crds2')'; % Center points on reference point\n if (P>1) % Calc euclidean distances in P-space\n dists = sqrt(sum(crds1.^2))';\n else\n dists = abs(crds1)';\n end\n end; % Return column vector\n\n if (N1==1 && N2>1) % If reference point && matrix provided,\n crds2 = crds2 - (ones(N2,1)*crds1')'; % Center points on reference point\n if (P>1) % Calc euclidean distances in P-space\n dists = sqrt(sum(crds2.^2));\n else\n dists = abs(crds2);\n end\n end; % Return row vector\n end\n\n return;\n\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/miscfunc/eucl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574668, "lm_q2_score": 0.9073122313857378, "lm_q1q2_score": 0.8696930063629352}} {"text": "function [P,R,S] = lagrangepoly(X,Y,XX)\n%LAGRANGEPOLY Lagrange interpolation polynomial fitting a set of points\n% [P,R,S] = LAGRANGEPOLY(X,Y) where X and Y are row vectors\n% defining a set of N points uses Lagrange's method to find \n% the N-1th order polynomial in X that passes through these \n% points. P returns the N coefficients defining the polynomial, \n% in the same order as used by POLY and POLYVAL (highest order first).\n% Then, polyval(P,X) = Y. R returns the x-coordinates of the N-1\n% extrema of the resulting polynomial (roots of its derivative),\n% and S returns the y-values at those extrema.\n%\n% YY = LAGRANGEPOLY(X,Y,XX) returns the values of the polynomial\n% sampled at the points specified in XX -- the same as\n% YY = POLYVAL(LAGRANGEPOLY(X,Y)). \n%\n% Example:\n% To find the 4th-degree polynomial that oscillates between \n% 1 and 0 across 5 points around zero, then plot the interpolation\n% on a denser grid inbetween:\n% X = -2:2; Y = [1 0 1 0 1];\n% P = lagrangepoly(X,Y);\n% xx = -2.5:.01:2.5;\n% plot(xx,polyval(P,xx),X,Y,'or');\n% grid;\n% Or simply:\n% plot(xx,lagrangepoly(X,Y,xx));\n%\n% Note: if you are just looking for a smooth curve passing through \n% a set of points, you can get a better fit with SPLINE, which \n% fits piecewise polynomials rather than a single polynomial.\n%\n% See also: POLY, POLYVAL, SPLINE\n\n% 2006-11-20 Dan Ellis dpwe@ee.columbia.edu\n% $Header: $\n\n% For more info on Lagrange interpolation, see Mathworld: \n% http://mathworld.wolfram.com/LagrangeInterpolatingPolynomial.html\n\n% Make sure that X and Y are row vectors\nif size(X,1) > 1; X = X'; end\nif size(Y,1) > 1; Y = Y'; end\nif size(X,1) > 1 || size(Y,1) > 1 || size(X,2) ~= size(Y,2)\n error('both inputs must be equal-length vectors')\nend\n\nN = length(X);\n\npvals = zeros(N,N);\n\n% Calculate the polynomial weights for each order\nfor i = 1:N\n % the polynomial whose roots are all the values of X except this one\n pp = poly(X( (1:N) ~= i));\n % scale so its value is exactly 1 at this X point (and zero\n % at others, of course)\n pvals(i,:) = pp ./ polyval(pp, X(i));\nend\n\n% Each row gives the polynomial that is 1 at the corresponding X \n% point and zero everywhere else, so weighting each row by the \n% desired row and summing (in this case the polycoeffs) gives \n% the final polynomial\nP = Y*pvals;\n\nif nargin==3\n % output is YY corresponding to input XX\n YY = polyval(P,XX);\n % assign to output\n P = YY;\nend\n\nif nargout > 1\n % Extra return arguments are values where dy/dx is zero\n % Solve for x s.t. dy/dx is zero i.e. roots of derivative polynomial\n % derivative of polynomial P scales each power by its power, downshifts\n R = roots( ((N-1):-1:1) .* P(1:(N-1)) );\n if nargout > 2\n % calculate the actual values at the points of zero derivative\n S = polyval(P,R);\n end\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/13151-lagrange-interpolator-polynomial/lagrangepoly/lagrangepoly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263736, "lm_q2_score": 0.9184802507195636, "lm_q1q2_score": 0.8694303525107052}} {"text": "function [X_norm, mu, sigma] = featureNormalize(X)\n%FEATURENORMALIZE Normalizes the features in X \n% FEATURENORMALIZE(X) returns a normalized version of X where\n% the mean value of each feature is 0 and the standard deviation\n% is 1. This is often a good preprocessing step to do when\n% working with learning algorithms.\n\n% You need to set these values correctly\nX_norm = X;\nmu = zeros(1, size(X, 2));\nsigma = zeros(1, size(X, 2));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: First, for each feature dimension, compute the mean\n% of the feature and subtract it from the dataset,\n% storing the mean value in mu. Next, compute the \n% standard deviation of each feature and divide\n% each feature by it's standard deviation, storing\n% the standard deviation in sigma. \n%\n% Note that X is a matrix where each column is a \n% feature and each row is an example. You need \n% to perform the normalization separately for \n% each feature. \n%\n% Hint: You might find the 'mean' and 'std' functions useful.\n% \n\n\nmu=mean(X)\nsigma=std(X)\n\nfor i = 1:size(X,2),\n X_norm(:,i) = (X(:,i) - mu(i)) / sigma(i);\nend\n\n\n\n% ============================================================\n\nend\n", "meta": {"author": "xjwhhh", "repo": "AndrewNgMachineLearning", "sha": "d9d8491b315755ea3726bc366d72ba069712c363", "save_path": "github-repos/MATLAB/xjwhhh-AndrewNgMachineLearning", "path": "github-repos/MATLAB/xjwhhh-AndrewNgMachineLearning/AndrewNgMachineLearning-d9d8491b315755ea3726bc366d72ba069712c363/code/machine-learning-ex1/ex1/featureNormalize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.9263037323284109, "lm_q1q2_score": 0.8689877822209218}} {"text": "function y = norm_pdf(x,mu,sigma)\n%NORM_PDF Normal probability density function (pdf).\n%\n% Y = NORMPDF(X,MU,SIGMA) Returns the normal pdf with\n% mean, MU, and standard deviation, SIGMA, at the values in X.\n%\n% The size of X is the common size of the input arguments. A scalar input \n% functions as a constant matrix of the same size as the other inputs. \n%\n% Default values for MU and SIGMA are 0 and 1 respectively.\n%\n% Copyright (c) 1998-2004 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\nif nargin < 3, \n sigma = 1;\nend\n\nif nargin < 2;\n mu = 0;\nend\n\nif nargin < 1, \n error('Requires at least one input argument.');\nend\n\ny = exp(-0.5 * ((x-mu)./sigma).^2 -log(sigma) -log(2*pi)/2);\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/dist/norm_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9648551576415562, "lm_q2_score": 0.9005297774417915, "lm_q1q2_score": 0.8688808003745152}} {"text": "function area = triangle_area ( t )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_AREA returns the area of a triangle.\n%\n% Location:\n%\n% http://people.sc.fsu.edu/~jburkardt/m_src/triangle_integrals/triangle_area.m\n%\n% Discussion:\n%\n% If the vertices are given in counter clockwise order, the area\n% will be positive.\n%\n% Licensing:\n%\n% This code is distributed under the GNU GPL license.\n%\n% Modified:\n%\n% 18 April 2015\n%\n% Author:\n%\n% John Burkardt.\n%\n% Parameters:\n%\n% Input, real T(2,3), the vertices of the triangle.\n%\n% Output, real AREA, the area of the triangle.\n%\n area = 0.5 * ...\n ( ...\n ( t(1,2) - t(1,1) ) * ( t(2,3) - t(2,1) ) ...\n - ( t(1,3) - t(1,1) ) * ( t(2,2) - t(2,1) ) ...\n );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/triangle_integrals/triangle_area.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.960361162033533, "lm_q2_score": 0.9046505440982949, "lm_q1q2_score": 0.8687912477645063}} {"text": "function varargout = randomAngle3d(varargin)\n%RANDOMANGLE3D Return a 3D angle uniformly distributed on unit sphere.\n%\n% usage\n% [THETA PHI] = randomAngle3d\n% Generate an angle unformly distributed on the surface of the unit\n% sphere.\n%\n% \"Mathematical\" convention is used: theta is the colatitude (angle with\n% vertical axis, 0 for north pole, +pi for south pole, pi/2 for points at\n% equator) with z=0. \n% phi is the same as matlab cart2sph: angle from Ox axis, counted\n% positively counter-clockwise.\n%\n% [THETA PHI] = randomAngle3d(N)\n% generates N random angles (N is a scalar). The result is a N-by-2\n% array.\n%\n% Example:\n% % Draw some points on the surface of a sphere\n% figure;\n% drawSphere; hold on;\n% drawPoint3d(pts, '.');\n% axis equal;\n%\n% See also:\n% angles3d, sph2cart2, cart2sph2\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% created the 18/02/2005.\n% Copyright INRA - Cepia Software platform\n\n% HISTORY\n% 2007-01-04 change angle order, update doc\n% 2011-06-27 fix bug in input parsing, add doc\n\n\nN = 1;\nif ~isempty(varargin)\n N = varargin{1};\nend\n\nphi = 2*pi*rand(N, 1);\ntheta = asin(2*rand(N, 1)-1) + pi/2;\n\nif nargout<2\n var = [theta phi];\n varargout{1} = var;\nelse\n varargout{1} = theta;\n varargout{2} = phi;\nend\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/randomAngle3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012701768144, "lm_q2_score": 0.9184802451409949, "lm_q1q2_score": 0.8686997824866648}} {"text": "% Euclidean projection on a hyperplane\n% Section 8.1.1, Boyd & Vandenberghe \"Convex Optimization\"\n% Joelle Skaf - 10/04/05\n%\n% The projection of x0 on a hyperplane C = {x | a'*x = b} is given by\n% minimize || x - x0 ||^2\n% s.t. a'*x = b\n% It is also given by P_C(x0) = x0 + (b - a'*x0)*a/||a||^2\n\n% Input data\nrandn('seed',0);\nn = 10;\na = randn(n,1);\nb = randn(1);\nx0 = randn(n,1);\n\n% Analytical solution\nfprintf(1,'Computing the analytical solution ...');\npc_x0 = x0 + (b - a'*x0)*a/norm(a)^2;\nfprintf(1,'Done! \\n');\n\n% Solution via QP\nfprintf(1,'Computing the optimal solution by solving a QP ...');\n\ncvx_begin quiet\n variable x(n)\n minimize ( norm(x-x0)^2 )\n a'*x == b; %#ok\ncvx_end\n\nfprintf(1,'Done! \\n');\n\n% Verification\ndisp('--------------------------------------------------------------------------------');\ndisp('Verifying that p_C(x0) and x_star belong to the hyperplane C: ');\ndisp(['a^T*p_C(x0) - b = ' num2str(a'*pc_x0 - b)]);\ndisp(['a^T*x_star - b = ' num2str(a'*x - b)]);\ndisp('Computing the distance between x0 and the hyperplane in each case');\ndisp(['||x0 - p_C(x0)|| = ' num2str(norm(x0 - pc_x0))]);\ndisp(['||x0 - x_star || = ' num2str(norm(x0 - x))]);\ndisp('Verifying that the analytical solution and the solution obtained via QP are equal: ');\ndisp([pc_x0 x])\n\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/examples/cvxbook/Ch08_geometric_probs/eucl_proj_hyp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012640659996, "lm_q2_score": 0.9184802406781396, "lm_q1q2_score": 0.868699772653028}} {"text": "% \n% Author: Stilian Stoev (C), sstoev@math.bu.edu\n%\n% This function computes the discrete convolution of the vectors\n% a and b, efficiently, by using the FFT algorithm.\n%\n% input:\n% a <- a vector\n% b <- a vector with the same dimensions as a\n% force <- if force == 1, then the FFT's are \"forced\" to be\n% of dyadic complexity.\n%\n% output:\n% c <- the discrete convolution of a and b, that is,\n% (a(1)*b(1), a(1)*b(2)+a(2)*b(1), ...)\n% \n% usage:\n% c = fftconv(a,b,force);\n%\n% Written by sstoev@math.bu.edu\n%\nfunction c = fftconv(a,b,force);\n\nna = length(a);\nnb = length(b);\n\nif force,\n n = 2^(fix(log2(na+nb))+1);\nelse\n n=na+nb;\nend;\nA = fft(a,n);\nB = fft(b,n);\n\nc = ifft(A.*B,n);\nc = real(c(1:na+nb-1));\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/5702-fftfgn/fftconv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877692486436, "lm_q2_score": 0.8947894675053567, "lm_q1q2_score": 0.8685611921599564}} {"text": "function [x,y]=henon(n,level,a,b,x0,y0)\n%Syntax: [x,y]=henon(n,level,a,b,x0,y0)\n%______________________________________\n%\n% Simulation of the Henon map.\n% x'=1-a*x^2+y\n% y'=b*x\n%\n% x and y are the simulated time series.\n% n is the number of the simulated points.\n% level is the noise standard deviation divided by the standard deviation of the\n% noise-free time series. We assume Gaussian noise with zero mean.\n% a is the a parameter.\n% b is the b parameter.\n% x0 is the initial value for x.\n% y0 is the initial value for y.\n%\n%\n% Reference:\n%\n% Henon M (1976):A two-dimensional mapping with a strange attractor. \n% Communications in Mathematical Physics 50: 69-77\n%\n%\n% Alexandros Leontitsis\n% Department of Education\n% University of Ioannina\n% 45110 - Dourouti\n% Ioannina\n% Greece\n% \n% University e-mail: me00743@cc.uoi.gr\n% Lifetime e-mail: leoaleq@yahoo.com\n% Homepage: http://www.geocities.com/CapeCanaveral/Lab/1421\n%\n% 5 Nov 2001\n\nif nargin<1 | isempty(n)==1\n n=500;\nelse\n % n must be scalar\n if sum(size(n))>2\n error('n must be scalar.');\n end\n % n must be positive\n if n<0\n error('n must be positive.');\n end\n % n must be an integer\n if round(n)-n~=0\n error('n must be an integer.');\n end\nend\n\nif nargin<2 | isempty(level)==1\n level=0;\nelse\n % level must be scalar\n if sum(size(level))>2\n error('level must be scalar.');\n end\n % level must be positive\n if level<0\n error('level must be positive.');\n end\nend\n\nif nargin<3 | isempty(a)==1\n a=1.4;\nelse\n % a must be scalar\n if sum(size(a))>2\n error('a must be scalar.');\n end\nend\n\nif nargin<4 | isempty(b)==1\n b=0.3;\nelse\n % b must be scalar\n if sum(size(b))>2\n error('s must be a scalar.');\n end\nend\n\nif nargin<5 | isempty(x0)==1\n x0=0.1;\nelse\n % x0 must be scalar\n if sum(size(x0))>2\n error('x0 must be scalar.');\n end\nend\n\nif nargin<6 | isempty(y0)==1\n y0=0.1;\nelse\n % y0 must be scalar\n if sum(size(y0))>2\n error('y0 must be scalar.');\n end\nend\n\n% Initialize\nx(1,1)=1-a*x0^2+b*y0;\ny(1,1)=b*x0;\n\n% Simulate\nfor i=2:n\n x(i,1)=1-a*x(i-1,1)^2+y(i-1,1);\n y(i,1)=b*x(i-1,1);\nend\n\n% Add normal white noise\nx=x+randn(n,1)*level*std(x);\ny=y+randn(n,1)*level*std(y);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/1597-chaotic-systems-toolbox/henon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488964, "lm_q2_score": 0.912436169406061, "lm_q1q2_score": 0.8685144396067824}} {"text": "function [theta] = normalEqn(X, y)\n%NORMALEQN Computes the closed-form solution to linear regression \n% NORMALEQN(X,y) computes the closed-form solution to linear \n% regression using the normal equations.\n\ntheta = zeros(size(X, 2), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the code to compute the closed form solution\n% to linear regression and put the result in theta.\n%\n\n% ---------------------- Sample Solution ----------------------\n\n\ntheta = pinv(X' * X) * X' * y;\n\n% -------------------------------------------------------------\n\n\n% ============================================================\n\nend\n", "meta": {"author": "merwan", "repo": "ml-class", "sha": "0b06b73d4aac0b8d7c726325200c3781b5c9d3b0", "save_path": "github-repos/MATLAB/merwan-ml-class", "path": "github-repos/MATLAB/merwan-ml-class/ml-class-0b06b73d4aac0b8d7c726325200c3781b5c9d3b0/mlclass-ex1/normalEqn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9585377225508371, "lm_q2_score": 0.9059898235563418, "lm_q1q2_score": 0.8684254221259307}} {"text": "function [x,y,z] = hilbert3(n)\n% Hilbert 3D curve.\n%\n% function [x,y,z] = hilbert3(n) gives the vector coordinates of points\n% in n-th order Hilbert curve of area 1.\n%\n% Example: plot the 3-rd order curve\n%\n% [x,y,z] = hilbert3(3); plot3(x,y,z)\n%\n% Inputs:\n% n number of subdivision iterations \n% Outputs:\n% x list of x coordinates\n% y list of y coordinates\n% z list of z coordinates\n%\n% Example:\n% n=3;\n% [x,y,z] = hilbert3(n);\n% P = [x;y;z]';\n% [V,F] = wire_mesh(P,[1:size(P,1)-1;2:size(P,1)]','Thickness',2^(1-n)/6);\n% [V,F] = loop(V,F,2);\n% tsurf(F,V);\n%\n\n\n\n% Copyright (c) by Ivan Martynov\n% Inspired by function [x,y] = hilbert(n) made by Federico Forte\n% Date: September 17, 2009\n\nif nargin ~= 1\n n = 2;\nend\n\nif n <= 0\n x = 0;\n y = 0;\n z = 0;\nelse\n [xo,yo,zo] = hilbert3(n-1);\n x = .5*[.5+zo .5+yo -.5+yo -.5-xo -.5-xo -.5-yo .5-yo .5+zo];\n y = .5*[.5+xo .5+zo .5+zo .5+yo -.5+yo -.5-zo -.5-zo -.5-xo];\n z = .5*[.5+yo -.5+xo -.5+xo .5-zo .5-zo -.5+xo -.5+xo .5-yo];\nend\n\n%{\nCopyright (c) 2009, Ivan Martynov\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and/or other materials provided with the distribution\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n%}\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/external/hilbert3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.9136765234137297, "lm_q1q2_score": 0.867690603397834}} {"text": "% Section 4.5.4: Frobenius norm diagonal scaling (GP)\n% Boyd & Vandenberghe \"Convex Optimization\"\n% Joelle Skaf - 01/29/06\n% Updated to use GP mode by Almir Mutapcic 02/08/06\n%\n% Given a square matrix M, the goal is to find a vector (with dii > 0)\n% such that ||DMD^{-1}||_F is minimized, where D = diag(d).\n% The problem can be cast as an unconstrained geometric program:\n% minimize sqrt( sum_{i,j=1}^{n} Mij^2*di^2/dj^2 )\n%\n\nrs = randn( 'state' );\nrandn( 'state', 0 );\n\n% matrix size (M is an n-by-n matrix)\nn = 4;\nM = randn(n,n);\n\n% formulating the problem as a GP\ncvx_begin gp\n variable d(n)\n minimize( sqrt( sum( sum( diag(d.^2)*(M.^2)*diag(d.^-2) ) ) ) )\n % Alternate formulation: norm( diag(d)*abs(M)*diag(1./d), 'fro' )\ncvx_end\n\n% displaying results\nD = diag(d);\ndisp('The matrix D that minimizes ||DMD^{-1}||_F is: ');\ndisp(D);\ndisp('The minimium Frobenius norm achieved is: ');\ndisp(norm(D*M*inv(D),'fro'));\ndisp('while the Frobunius norm of the original matrix M is: ');\ndisp(norm(M,'fro'));\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/cvxbook/Ch04_cvx_opt_probs/frob_norm_diag_scaling.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.974434786819155, "lm_q2_score": 0.8902942239389252, "lm_q1q2_score": 0.8675336623102516}} {"text": "function theta = vectorAngle3d(v1, v2)\n%VECTORANGLE3D Angle between two 3D vectors.\n%\n% THETA = vectorAngle3d(V1, V2)\n% Computes the angle between the 2 3D vectors V1 and V2. The result THETA\n% is given in radians, between 0 and PI.\n%\n%\n% Example\n% % angle between 2 orthogonal vectors\n% vectorAngle3d([1 0 0], [0 1 0])\n% ans = \n% 1.5708\n%\n% % angle between 2 parallel vectors\n% v0 = [3 4 5];\n% vectorAngle3d(3*v0, 5*v0)\n% ans = \n% 0\n%\n% See also\n% vectors3d, vectorNorm3d, crossProduct3d\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2010-10-04, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n% 2011-03-10 improve computation precision\n\n% compute angle using arc-tangent to get better precision for angles near\n% zero, see the discussion in: \n% http://www.mathworks.com/matlabcentral/newsreader/view_thread/151925#381952\ntheta = atan2(vectorNorm3d(crossProduct3d(v1, v2)), sum(bsxfun(@times, v1, v2),2));\n\n% equivalent to:\n% v1 = normalizeVector3d(v1);\n% v2 = normalizeVector3d(v2);\n% theta = acos(dot(v1, v2, 2));\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/vectorAngle3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9559813538993889, "lm_q2_score": 0.9073122307591682, "lm_q1q2_score": 0.8673735747706244}} {"text": "function [ n_data_new, n, c ] = phi_values ( n_data )\n\n%*****************************************************************************80\n%\n%% PHI_VALUES returns some values of the PHI function.\n%\n% Definition:\n%\n% PHI(N) is the number of integers between 1 and N which are\n% relatively prime to N. I and J are relatively prime if they\n% have no common factors. The function PHI(N) is known as\n% \"Euler's totient function\".\n%\n% By convention, 1 and N are relatively prime.\n%\n% First values:\n%\n% N PHI(N)\n%\n% 1 1\n% 2 1\n% 3 2\n% 4 2\n% 5 4\n% 6 2\n% 7 6\n% 8 4\n% 9 6\n% 10 4\n% 11 10\n% 12 4\n% 13 12\n% 14 6\n% 15 8\n% 16 8\n% 17 16\n% 18 6\n% 19 18\n% 20 8\n%\n% Formula:\n%\n% PHI(U*V) = PHI(U) * PHI(V) if U and V are relatively prime.\n%\n% PHI(P**K) = P**(K-1) * ( P - 1 ) if P is prime.\n%\n% PHI(N) = N * Product ( P divides N ) ( 1 - 1 / P )\n%\n% N = Sum ( D divides N ) PHI(D).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Parameters:\n%\n% Input, integer N_DATA, indicates the index of the previous test data\n% returned, or is 0 if this is the first call. For repeated calls,\n% set the input value of N_DATA to the output value of N_DATA_NEW\n% from the previous call.\n%\n% Output, integer N_DATA_NEW, the index of the test data.\n%\n% Output, integer N, the argument of the PHI function.\n%\n% Output, integer C, the value of the PHI function.\n%\n n_max = 20;\n c_vec = [ ...\n 1, 1, 2, 2, 4, 2, 6, 4, 6, 4, ...\n 8, 8, 16, 20, 16, 40, 148, 200, 200, 648 ];\n n_vec = [ ...\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...\n 20, 30, 40, 50, 60, 100, 149, 500, 750, 999 ];\n\n n_data_new = n_data;\n\n if ( n_data_new < 0 )\n n_data_new = 0;\n end\n\n n_data_new = n_data_new + 1;\n\n if ( n_max < n_data_new )\n n_data_new = 0;\n n = 0;\n c = 0;\n else\n n = n_vec(n_data_new);\n c = c_vec(n_data_new);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/phi_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068042, "lm_q2_score": 0.91243616285804, "lm_q1q2_score": 0.867189342443428}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Author: Nicholas A. Battista\n% Institution: The College of New Jersey (TCNJ)\n% Created: March 20, 2018\n% Date of Last Revision: March 22, 2018\n%\n% Written for use in MAT 331: Numerical Analysis \n%\n% PURPOSE: -To compute the error ssociated with applying Trapezoid Rule to \n% two different integral cases:\n% (1) a periodic integrand on a periodic integration domain\n% (2) non-periodic integrand\n%\n% -To demonstrate exponential convergence of Trap. Rule in Case (1)\n% above\n%\n% Inputs: \n%\n% Returns: \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Trap_Rule_Error()\n\n% Number of subintervals to test\nNVec = [1e0:1e0:9e0 1e1:1e1:9e1 1e2:1e2:9e2 1e3:1e3:9e3 1e4:1e4:9e4 1e5:1e5:9e5 1e6:1e6:9e6];\n\n%\n% Storage Initialization\nErrVecPeriodic = zeros(length(NVec));\nErrVecNonPeriodic = ErrVecPeriodic;\n\n%\n% Compute Integral Approximation for Different #'s of Subintervals\n%\nfor i=1:length(NVec)\n \n flag = 1; % For Periodic\n ErrVecPeriodic(i) = Trap_Rule( NVec(i), 0, 1, flag);\n \n flag = 0; % For Non-Periodic\n ErrVecNonPeriodic(i) = Trap_Rule( NVec(i), 0, 1, flag);\n \nend\n\n\n%\n% Print Convergence Rate Information to Screen\nslopeNonPeriodic = give_Me_Slope( ErrVecNonPeriodic,40,50 );\nfprintf('\\nConvergence Rate for Periodic Functions Appears to be Exponential, e.g.,\\n');\nfprintf(' we see a linear relationship between log(error) and # of subintervals, N\\n');\nfprintf('\\nConvergence Rate for Non-Periodic Functions Appears to be: %d\\n\\n',slopeNonPeriodic);\n\n%\n% PLOT THE ABSOLUTEL ERROR -> GIVE CONVERGENCE PLOTS!\n%\nfs = 18;\nms = 30;\nfigure(1) % PERIODIC CASE\nsemilogy(NVec(1:45),ErrVecPeriodic(1:45),'b.','MarkerSize',ms); hold on;\n%loglog(NVec(1:45),ErrVecPeriodic(1:45),'b.','MarkerSize',ms); hold on;\ntitle('Periodic Case');\nylabel('Absolute Error');\nxlabel('Number of Sub-Intervals');\nset(gca,'FontSize',fs);\n\nfigure(2) % NON-PERIODIC CASE\nloglog(NVec,ErrVecNonPeriodic,'b.','MarkerSize',ms); hold on;\ntitle('Non-Periodic Case');\nylabel('Absolute Error');\nxlabel('Number of Sub-Intervals');\nset(gca,'FontSize',fs);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: computes the absolute error using the trapezoid rule for a\n% particular number of subintervals, N.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction err = Trap_Rule(N,a,b,flagCase)\n\n% Uniformly spaced integration nodes\nx = a:(b-a)/N:b;\n\n% Compute trapezoid rule for periodic function\nint = 0;\nfor i=1:N\n int = int + (b-a)/(2*N)*( f(x(i),flagCase) + f(x(i+1),flagCase) ); \nend\n\n%\n% Return Error for Particular Case\n%\nif flagCase == 1\n \n % PERIODIC CASE\n intExactPeriodic = 0.132214293037990;\n err = abs( int - intExactPeriodic );\n\nelse\n\n % NON-PERIODIC CASE\n intExactNonPeriodic = 0.455122322888408;\n err = abs( int - intExactNonPeriodic );\n\nend\n\n% PLOT!\n%x=a:0.001:b;\n%for i=1:length(x)\n% plot( x(i) , f(x(i)), '*'); hold on;\n%end\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: returns integrand function value\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction val = f(x,flagCase)\n\n%\n% Return Function Value for Particular Case\n%\nif flagCase == 1\n\n % PERIODIC: f(x) = (cos(2*pi*x))^2 / ( 1 + e^(sin(2*pi*x)) )^2;\n val = ( cos(2*pi*x) )^2 / ( 1 + exp( sin(2*pi*x) ) )^2;\n\nelse\n \n % NON-PERIODIC: f(x) = (x^2+3)(cos(2*pi*x))^2 / ( 1 + e^(sin(2*pi*x)) )^2;\n val = (x^2+3)*(cos(2*pi*x))^2 / ( 1 + exp(sin(2*pi*x)) )^2;\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: give me slope of convergence plot\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction m = give_Me_Slope( errVec, val1, val2 )\n\nm = ( log( errVec(val1) ) - log( errVec(val2) ) ) / (log(val1) - log(val2));", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Examples_Education/Convergence/Trapezoid_Rule/Trap_Rule_Error.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001757, "lm_q2_score": 0.916109606145647, "lm_q1q2_score": 0.8671863027158638}} {"text": "function line = medianLine(varargin)\n%MEDIANLINE Create a median line between two points\n%\n% L = medianLine(P1, P2);\n% Create the median line of points P1 and P2, that is the line containing\n% all points located at equal distance of P1 and P2.\n%\n% L = medianLine(PTS);\n% Creates the median line of 2 points, given as a 2*2 array. Array has\n% the form:\n% [ [ x1 y1 ] ; [ x2 y2 ] ]\n%\n% L = medianLine(EDGE);\n% Creates the median of the edge. Edge is a 1*4 array, containing [X1 Y1]\n% coordinates of first point, and [X2 Y2], the coordinates of the second\n% point.\n% \n% Example\n% % Draw the median line of two points\n% P1 = [10 20];\n% P2 = [30 50];\n% med = medianLine(P1, P2);\n% figure; axis square; axis([0 100 0 100]);\n% drawEdge([P1 P2], 'linewidth', 2, 'color', 'k');\n% drawLine(med)\n%\n% % Draw the median line of an edge\n% P1 = [50 60];\n% P2 = [80 30];\n% edge = createEdge(P1, P2);\n% figure; axis square; axis([0 100 0 100]);\n% drawEdge(edge, 'linewidth', 2)\n% med = medianLine(edge);\n% drawLine(med)\n%\n%\n% See also:\n% lines2d, createLine, orthogonalLine\n%\n% ---------\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 31/10/2003.\n%\n\n% history\n% 2010-08-06 vectorize and change behaviour for N-by-4 inputs\n\nnargs = length(varargin);\n\nif nargs == 1\n tab = varargin{1};\n if size(tab, 2)==2\n % input is an array of two points\n x0 = tab(1,1); \n y0 = tab(1,2);\n dx = tab(2,1)-x0; \n dy = tab(2,2)-y0;\n else\n % input is an edge\n x0 = tab(:, 1); \n y0 = tab(:, 2);\n dx = tab(:, 3) - tab(:, 1); \n dy = tab(:, 4) - tab(:, 2);\n end\n \nelseif nargs==2\n % input is given as two points, or two point arrays\n p1 = varargin{1};\n p2 = varargin{2};\n x0 = p1(:, 1); \n y0 = p1(:, 2);\n dx = bsxfun(@minus, p2(:, 1), x0); \n dy = bsxfun(@minus, p2(:, 2), y0);\n \nelse\n error('Too many input arguments');\nend\n\n% compute median using middle point of the edge, and the direction vector\n% rotated by 90 degrees counter-clockwise\nline = [bsxfun(@plus, x0, dx/2), bsxfun(@plus, y0, dy/2), -dy, dx];\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom2d/medianLine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.9252299524531926, "lm_q1q2_score": 0.8671354959683693}} {"text": "function M = softMin( D, sigma )\n% Calculates the softMin of a vector.\n%\n% Let D be a vector. Then the softMin of D is defined as:\n% s = exp(-D/sigma^2) / sum( exp(-D/sigma^2) )\n% The softMin is a way of taking a dissimilarity (distance) vector D and\n% converting it to a similarity vector s, such that sum(s)==1. If D is an\n% NxK array, is is treated as N K-dimensional vectors, and the return is\n% likewise an NxK array. This is useful if D is a distance matrix,\n% generated by the likes of pdist2.\n%\n% Note that as sigma->0, softMin's behavior tends toward that of the\n% standard min function. That is the softMin of a vector D has all zeros\n% with a single 1 in the location of the smallest value of D. For example,\n% \"softMin([.2 .4 .1 .3],eps)\" returns \"[0 0 1 0]\". As sigma->inf, then\n% softMin(D,sigma) tends toward \"ones(1,n)/n\", where n==length(D).\n%\n% If D contains the squared euclidean distance between a point y and k\n% points xi, then there is a probabilistic interpretation for softMin. If\n% we think of the k points representing equal variant gaussians each with\n% mean xi and std sigma, then the softMin returns the relative probability\n% of y being generated by each gaussian.\n%\n% USAGE\n% M = softMin( D, sigma )\n%\n% INPUTS\n% D - NxK dissimilarity matrix\n% sigma - controls 'softness' of softMin\n%\n% OUTPUTS\n% M - the softMin (indexes into D)\n%\n% EXAMPLE - 1\n% C = [0 0; 1 0; 0 1; 1 1]; x=[.7,.3; .1 .2];\n% D = pdist2( x, C ), M = softMin( D, .25 )\n%\n% EXAMPLE - 2\n% fplot( 'softMin( [0.5 0.2 .4], x )', [0 5] );\n% xlabel('sigma'); ylabel('assignments')\n%\n% See also PDIST2, SOFTMAX\n%\n% Piotr's Image&Video Toolbox Version 2.0\n% Copyright 2012 Piotr Dollar. [pdollar-at-caltech.edu]\n% Please email me if you find bugs, or have suggestions or questions!\n% Licensed under the Simplified BSD License [see external/bsd.txt]\n\nif( sigma==0 ) % special case, make fast\n [~, inds] = min(D,[],2); [n, k] = size(D);\n M = subsToArray( [(1:n)' inds], ones(n,1), [n k] );\n\nelse % general case\n M = exp( -D / sigma^2 );\n M(isinf(M))=1e50;\n sumM = sum( M, 2 );\n sumMzero = (sumM==0);\n if( any(sumMzero) )\n [~, inds] = min(D,[],2); [n, k] = size(D);\n Mhard = subsToArray( [(1:n)' inds], ones(n,1), [n k] );\n M( sumMzero, : ) = Mhard( sumMzero, : );\n sumM = sum( M, 2 );\n end\n M = M ./ sumM( :, ones(1,size(M,2)) );\nend\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/SketchTokens-master/toolbox/classify/softMin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.9136765187126079, "lm_q1q2_score": 0.8670034227632887}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n% \n% \n% \n\n% analytical computation of the convolution between \n% x(t)=1,0 d(2)\n disp('WARNING - the input to chebyshevInterpolate does not lie on the domain that was specified for the function')\n disp(' --> This can lead to unpredictable outputs and is not suggested.') \nend\n\n%Get the chebyshev points\n[k,n] = size(f);\nx = chebyshevPoints(n,d);\nONE1 = ones(k,1);\nONE2 = ones(1,length(t));\n\n%Loop through each chebyshev node.\nnum = zeros(k,length(t));\nden = zeros(k,length(t));\nfor i=1:n\n val = ONE1*(1./(t-x(i)));\n if mod(i,2)==1, val=-val; end;\n if i==1 || i==n\n num = num + 0.5*(f(:,i)*ONE2).*val;\n den = den + 0.5*(val);\n else\n num = num + (f(:,i)*ONE2).*val;\n den = den + val;\n end\nend\n\n%compute the solution:\ny = num./den;\n\n%Check for any values that were too close to nodes and correct them\nnanIdx = isnan(y);\nif sum(sum(nanIdx))>0 \n nanRowIdx = max(nanIdx,[],1);\n y(:,nanRowIdx) = interp1(x',f',t(nanRowIdx)')';\nend\n\n\n%%%% Derivative Calculations %%%%\nif nargout == 2\n Df = chebyshevDerivative(f,d);\n Dy = chebyshevInterpolate(Df,t,d); \nelseif nargout == 3\n [Df, DDf] = chebyshevDerivative(f,d);\n Dy = chebyshevInterpolate(Df,t,d); \n DDy = chebyshevInterpolate(DDf,t,d); \nelseif nargout == 4\n [Df, DDf, DDDf] = chebyshevDerivative(f,d);\n Dy = chebyshevInterpolate(Df,t,d); \n DDy = chebyshevInterpolate(DDf,t,d); \n DDDy = chebyshevInterpolate(DDDf,t,d); \nend\n\n \n\n\nend\n\n\n \n% % % This block of code provides a more efficient way of computing the\n% % % derivative of the function for very high order polynomial fits. \n% % %\n% % % It turns out that computing the differentiation matrix, which is done in\n% % % chebyshevDerivative, is an order n^2 calculation, which takes a long\n% % % time to compute for high order fits. This code is faster, but it is\n% % % not as accurate, especially near (or on) the gridpoints.\n% % %\n% % % To implement this code, put it between the lines:\n% % % --> %%%% Derivative Calculations %%%%\n% % % --> if nargout == 2\n% % % CODE HERE\n% % % --> end\n% % % Note that this would prevent the code from calculating higher order\n% % % derivatives.\n% % \n% % \n% %\n% % %Loop through each chebyshev node again, slightly different math\n% % numDer = zeros(1,length(t));\n% % denDer = zeros(1,length(t));\n% % for i=1:n\n% % val = 1./(t-x(i)).^2;\n% % if mod(i,2)==1, val=-val; end;\n% % if i==1 || i==n\n% % numDer = numDer - 0.5*f(i).*(val);\n% % denDer = denDer - 0.5*(val);\n% % else\n% % numDer = numDer - f(i).*val;\n% % denDer = denDer - val;\n% % end\n% % end\n% % \n% % %Compute the derivative of the approximation\n% % Dy = (numDer.*den - num.*denDer)./(den.^2);\n% % \n% % %Check for any values that were to close to nodes\n% % % -> NOTE - It is expensive to call chebyshevDerivative because it \n% % % it computes a huge matrix just to take one or two derivatives.\n% % % -> If speed is more important than accuracy, replace the contents\n% % % of the folloging if statement with the code in comments after\n% % % the end of the function. This uses a 4th order accurate central\n% % % difference to compute the derivative.\n% % %\n% % nanIdx = isnan(Dy);\n% % nanSum = sum(nanIdx);\n% % if nanSum>0\n% % \n% % %Use a 4th order central difference to get any values that were Nan\n% % \n% % %This was determined experimentally:\n% % % --> Too Small - run into machine precision\n% % % --> Too Big - doesn't capture local shape well\n% % SMALL_NUMBER = 10^(-2*log10(length(f)));\n% % \n% % %Get a vector of times that we need function values at\n% % timeDiff = [...\n% % t(nanIdx) - 2*SMALL_NUMBER;\n% % t(nanIdx) - SMALL_NUMBER;\n% % t(nanIdx) + SMALL_NUMBER;\n% % t(nanIdx) + 2*SMALL_NUMBER];\n% % timeDiffVec = reshape(timeDiff,4*nanSum,1)';\n% % \n% % %Get the values of the function at each point in timeDiff\n% % funcDiffVec = chebyshevInterpolate(f, timeDiffVec,d)';\n% % funcDiff = reshape(funcDiffVec,4,nanSum);\n% % \n% % %From Wikipedia: Finite difference coefficient\n% % %http://en.wikipedia.org/wiki/Finite_difference_coefficient\n% % coeff = [1/12, -2/3, 2/3, -1/12];\n% % \n% % %Correct the Nan values\n% % Dy(nanIdx) = sum(coeff*funcDiff,1)/SMALL_NUMBER;\n% % end\n\n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/PendulumCart_SwingUp/Chebyshev_Grid_Soln/chebyshevInterpolate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.9111797075998823, "lm_q1q2_score": 0.8666614911609493}} {"text": "function volume = sphere_volume_nd ( dim_num, r )\n\n%*****************************************************************************80\n%\n%% SPHERE_VOLUME_ND computes the volume of an implicit sphere in ND.\n%\n% Discussion:\n%\n% An implicit sphere in ND satisfies the equation:\n%\n% sum ( ( X(1:N) - CENTER(1:N) )**2 ) = R**2\n%\n% where R is the radius and CENTER is the center.\n%\n% Results for the first few values of N are:\n%\n% DIM_NUM Volume\n% - -----------------------\n% 2 PI * R**2\n% 3 (4/3) * PI * R**3\n% 4 (1/2) * PI**2 * R**4\n% 5 (8/15) * PI**2 * R**5\n% 6 (1/6) * PI**3 * R**6\n% 7 (16/105) * PI**3 * R**7\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the dimension of the space.\n%\n% Input, real R, the radius of the sphere.\n%\n% Output, real VOLUME, the volume of the sphere.\n%\n volume = r^dim_num * sphere_unit_volume_nd ( dim_num );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_test/sphere_volume_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799451753696, "lm_q2_score": 0.8991213732152423, "lm_q1q2_score": 0.8665551477833893}} {"text": "% IM = mkSquare(SIZE, PERIOD, DIRECTION, AMPLITUDE, PHASE, ORIGIN, TWIDTH)\n% or\n% IM = mkSine(SIZE, FREQ, AMPLITUDE, PHASE, ORIGIN, TWIDTH)\n% \n% Compute a matrix of dimension SIZE (a [Y X] 2-vector, or a scalar)\n% containing samples of a 2D square wave, with given PERIOD (in\n% pixels), DIRECTION (radians, CW from X-axis, default = 0), AMPLITUDE\n% (default = 1), and PHASE (radians, relative to ORIGIN, default = 0).\n% ORIGIN defaults to the center of the image. TWIDTH specifies width\n% of raised-cosine edges on the bars of the grating (default =\n% min(2,period/3)).\n% \n% In the second form, FREQ is a 2-vector of frequencies (radians/pixel).\n\n% Eero Simoncelli, 6/96.\n\n% TODO: Add duty cycle. Allow soft threshold (using rcosFn)\n\nfunction [res] = mkSquare(sz, per_freq, dir_amp, amp_phase, phase_orig, orig_twidth, twidth)\n\n%------------------------------------------------------------\n%% OPTIONAL ARGS:\n\nif (prod(size(per_freq)) == 2)\n frequency = norm(per_freq);\n direction = atan2(per_freq(1),per_freq(2));\n if (exist('dir_amp') == 1)\n amplitude = dir_amp;\n else\n amplitude = 1;\n end\n if (exist('amp_phase') == 1)\n phase = amp_phase;\n else\n phase = 0;\n end\n if (exist('phase_orig') == 1)\n origin = phase_orig;\n end\n if (exist('orig_twidth') == 1)\n transition = orig_twidth;\n else\n transition = min(2,2*pi/(3*frequency));\n end\n if (exist('twidth') == 1)\n error('Too many arguments for (second form) of mkSine');\n end\nelse\n frequency = 2*pi/per_freq;\n if (exist('dir_amp') == 1)\n direction = dir_amp;\n else\n direction = 0;\n end\n if (exist('amp_phase') == 1)\n amplitude = amp_phase;\n else\n amplitude = 1;\n end\n if (exist('phase_orig') == 1)\n phase = phase_orig;\n else\n phase = 0;\n end\n if (exist('orig_twidth') == 1)\n origin = orig_twidth;\n end\n if (exist('twidth') == 1)\n transition = twidth;\n else\n transition = min(2,2*pi/(3*frequency));\n end\n\nend\n\n%------------------------------------------------------------\n \nif (exist('origin') == 1)\n res = sin(mkRamp(sz, direction, frequency, phase, origin));\nelse\n res = sin(mkRamp(sz, direction, frequency, phase));\nend\n\n[Xtbl,Ytbl] = rcosFn(2*sin(frequency*transition/2),0,[-amplitude amplitude]);\n\nres = pointOp(res,Ytbl,Xtbl(1),Xtbl(2)-Xtbl(1),0);\n\n% OLD threshold version: \n%res = amplitude * (mod(res,2*pi) < pi);\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/pyrTools/pyrTools/mkSquare.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350253, "lm_q2_score": 0.8991213718636754, "lm_q1q2_score": 0.8665551455453804}} {"text": "function [ x, y, seed ] = circle_segment_sample_from_height ( r, h, n, seed )\n\n%*****************************************************************************80\n%\n%% CIRCLE_SEGMENT_SAMPLE_FROM_HEIGHT samples points from a circle segment.\n%\n% Discussion:\n%\n% Begin with a circle of radius R. Choose two points P1 and P2 on the\n% circle, and draw the chord P1:P2. This chord divides the circle\n% into two pieces, each of which is called a circle segment.\n% Consider one of the pieces. The \"angle\" of this segment is the angle \n% P1:C:P2, where C is the center of the circle. Let Q be the point on \n% the chord P1:P2 which is closest to C. The \"height\" of the segment\n% is the distance from Q to the perimeter of the circle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 16 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, the radius of the circle.\n% 0 < R.\n%\n% Input, real H, the height of the circle segment.\n% 0 <= H <= 2 * R.\n%\n% Input, integer N, the number of sample points.\n%\n% Input/output, integer SEED, a seed for the random number generator.\n%\n% Output, real X(N,1), Y(N,1), the sample points.\n%\n area = circle_segment_area_from_height ( r, h );\n%\n% Pick CDF's randomly.\n%\n if ( seed == 0 )\n u = rand ( n, 1 );\n else\n [ u, seed ] = r8vec_uniform_01 ( n, seed );\n end\n%\n% Choose points randomly by choosing ordered areas randomly.\n%\n area2(1:n,1) = u(1:n,1) * area;\n%\n% Each area corresponds to a height H2. Find it.\n%\n h2 = zeros ( n, 1 );\n for i = 1 : n\n h2(i,1) = circle_segment_height_from_area ( r, area2(i,1) );\n end\n%\n% Determine the half-width WH of the segment for each H2.\n%\n wh(1:n,1) = sqrt ( h2(1:n,1) .* ( 2.0 * r - h2(1:n,1) ) );\n%\n% Choose an X position randomly in [-WH,+WH].\n%\n if ( seed == 0 )\n u = rand ( n, 1 );\n else\n [ u, seed ] = r8vec_uniform_01 ( n, seed );\n end\n\n x(1:n,1) = ( 2.0 * u(1:n,1) - 1.0 ) .* wh(1:n,1);\n%\n% Our circle center is at (0,0). Our height of H2 is subtracted\n% from the height R at the peak of the circle. Determine the Y\n% coordinate using this fact.\n% \n y(1:n,1) = r - h2(1:n,1);\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/circle_segment/circle_segment_sample_from_height.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.9263037308025663, "lm_q1q2_score": 0.8664149599899372}} {"text": "function value = i4_factorial2 ( n )\n\n%*****************************************************************************80\n%\n%% I4_FACTORIAL2 computes the double factorial N!!\n%\n% Formula:\n%\n% FACTORIAL2( N ) = Product ( N * (N-2) * (N-4) * ... * 2 ) (N even)\n% = Product ( N * (N-2) * (N-4) * ... * 1 ) (N odd)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 January 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the argument of the double factorial function.\n% If N is less than 1, the value is returned as 1.\n%\n% Output, integer VALUE, the value of N!!.\n%\n if ( n < 1 )\n value = 1;\n return\n end\n\n value = 1;\n\n while ( 1 < n )\n value = value * n;\n n = n - 2;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hermite_test_int/i4_factorial2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.9136765163620469, "lm_q1q2_score": 0.8663065283272244}} {"text": "function area = circle_segment_area_from_angle ( r, theta )\n\n%*****************************************************************************80\n%\n%% CIRCLE_SEGMENT_AREA_FROM_ANGLE computes the area of a circle segment.\n%\n% Discussion:\n%\n% Begin with a circle of radius R. Choose two points P1 and P2 on the\n% circle, and draw the chord P1:P2. This chord divides the circle\n% into two pieces, each of which is called a circle segment.\n% Consider one of the pieces. The \"angle\" of this segment is the angle \n% P1:C:P2, where C is the center of the circle. Let Q be the point on \n% the chord P1:P2 which is closest to C. The \"height\" of the segment\n% is the distance from Q to the perimeter of the circle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 17 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, the radius of the circle.\n% 0 < R.\n%\n% Input, real THETA, the angle of the circle segment.\n%\n% Output, real AREA, the area of the circle segment.\n%\n area = r * r * ( theta - sin ( theta ) ) / 2.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/circle_segment/circle_segment_area_from_angle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474233166329, "lm_q2_score": 0.9073122244934722, "lm_q1q2_score": 0.8661632772563755}} {"text": "% COST function.\n% It shows how accurate our model is based on current model parameters.\nfunction [cost] = cost_function(X, y, theta, lambda)\n % Input:\n % X - input features - (m x n) matrix.\n % theta - our model parameters - (n x 1) vector.\n % y - a vector of correct output - (m x 1) vector.\n % lambda - regularization parameter.\n %\n % Output:\n % cost - number that represents the cost (error) of our model with specified parameters theta.\n %\n % Where:\n % m - number of training examples,\n % n - number of features.\n\n % Get the size of the trainging set.\n m = size(X, 1);\n\n % Get the difference between predictions and correct output values.\n differences = hypothesis(X, theta) - y;\n\n % Calculate regularization parameter.\n % Remember that we should not regularize the parameter theta_zero.\n theta_cut = theta(2:end, 1);\n regularization_param = lambda * (theta_cut' * theta_cut);\n\n % Calculate current predictions cost.\n cost = (1 / 2 * m) * (differences' * differences + regularization_param);\nend\n", "meta": {"author": "trekhleb", "repo": "machine-learning-octave", "sha": "5f98be8c135d84cecc96ce28d0f63cfa5bca5606", "save_path": "github-repos/MATLAB/trekhleb-machine-learning-octave", "path": "github-repos/MATLAB/trekhleb-machine-learning-octave/machine-learning-octave-5f98be8c135d84cecc96ce28d0f63cfa5bca5606/linear-regression/cost_function.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992951349231, "lm_q2_score": 0.8947894689081711, "lm_q1q2_score": 0.866066096250371}} {"text": "function [X_norm, mu, sigma] = featureNormalize(X)\n%FEATURENORMALIZE Normalizes the features in X \n% FEATURENORMALIZE(X) returns a normalized version of X where\n% the mean value of each feature is 0 and the standard deviation\n% is 1. This is often a good preprocessing step to do when\n% working with learning algorithms.\n\n% You need to set these values correctly\nX_norm = X;\nmu = zeros(1, size(X, 2));\nsigma = zeros(1, size(X, 2));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: First, for each feature dimension, compute the mean\n% of the feature and subtract it from the dataset,\n% storing the mean value in mu. Next, compute the \n% standard deviation of each feature and divide\n% each feature by it's standard deviation, storing\n% the standard deviation in sigma. \n%\n% Note that X is a matrix where each column is a \n% feature and each row is an example. You need \n% to perform the normalization separately for \n% each feature. \n%\n% Hint: You might find the 'mean' and 'std' functions useful.\n% \n\n\nmu = mean(X);\nsigma = std(X);\nX_norm = (X - repmat(mu, [size(X,1), 1]))./repmat(sigma, [size(X,1), 1]);\n\n\n\n\n\n\n% ============================================================\n\nend\n", "meta": {"author": "1094401996", "repo": "machine-learning-coursera", "sha": "e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb", "save_path": "github-repos/MATLAB/1094401996-machine-learning-coursera", "path": "github-repos/MATLAB/1094401996-machine-learning-coursera/machine-learning-coursera-e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb/problem_sets/ex1/featureNormalize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409308, "lm_q2_score": 0.9263037262250327, "lm_q1q2_score": 0.8655337208283093}} {"text": "function val=erfComplex(z)\n%%ERFCOMPLEX Evaluate the error function in a manner valid for complex\n% arguemnts. Matlab's built-in function erf cannot handle\n% complex arguments. The error function is defined as\n% (2/pi)*integral_0^z exp(-t^2) dt.\n%\n%INPUTS: z A scalar, vector, or matrix of values at which one wishes to\n% evaluate the error function.\n%\n%OUTPUTS: val A matrix having the same dimensions as z in which the values\n% of the scaled error function are computed for the values in\n% z.\n%\n%For values of abs(z)<0.08, six terms of the maclaurin series in [1] are\n%used. These should be sufficient for convergence. For larger values, the\n%Faddeeva function is used through the relation \n%erf(z)=1-exp(-z^2)*Faddeeva(1i*z);\n%\n%REFERENCES:\n%[1] Weisstein, Eric W. \"Erf.\" From MathWorld--A Wolfram Web Resource\n% http://mathworld.wolfram.com/Erf.html\n%\n%November 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumVals=numel(z);\n\nzList=z;\nval=zeros(size(z));\n\nfor curVal=1:numVals\n z=zList(curVal);\n y=imag(z);\n %If the argument is real, the built-in erf function is faster.\n if(y==0)\n x=real(z);\n val(curVal)=erf(x);\n continue;\n end\n\n if(abs(z)<0.08)\n %Use the Maclaurin series. For abs(z)<0.08, convergence occurs\n %within 6 terms.\n NMax=6;\n z2=z^2;\n\n %Initialize to the n=0 term\n sumVal=z;\n prodVal=z;\n for n=1:NMax\n prodVal=prodVal*z2*(1-2*n)/(n*(1+2*n));\n sumVal=sumVal+prodVal;\n end\n\n val(curVal)=2/sqrt(pi)*sumVal;\n else%Compute using the Faddeeva function.\n val(curVal)=1-exp(-z^2)*Faddeeva(1i*z);\n end\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/erfComplex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342049451595, "lm_q2_score": 0.9046505248181417, "lm_q1q2_score": 0.8654196355626242}} {"text": "function [J, grad] = costFunctionReg(theta, X, y, lambda)\n%COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization\n% J = COSTFUNCTIONREG(theta, X, y, lambda) computes the cost of using\n% theta as the parameter for regularized logistic regression and the\n% gradient of the cost w.r.t. to the parameters. \n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost of a particular choice of theta.\n% You should set J to the cost.\n% Compute the partial derivatives and set grad to the partial\n% derivatives of the cost w.r.t. each parameter in theta\n\n\n\npredictions = sigmoid(X*theta);\n\nleftPart = -y' * log(predictions);\n\nrightPart = (1 - y') * log(1 - predictions);\n\nthetaZero = theta;\n\nthetaZero(1) = 0;\n\nlambaCostPart = (lambda / (2 * m)) * sum(thetaZero .^ 2);\n\nlambdaGradPart = lambda / m * thetaZero;\n\nJ = (1 / m) * (leftPart - rightPart) + lambaCostPart;\n\ngrad = ((1/m) * (X' * (predictions - y))) + lambdaGradPart;\n\n\n\n% =============================================================\n\nend\n", "meta": {"author": "vugsus", "repo": "coursera-machine-learning", "sha": "4c2d45cb729355593509abcd41779d19de5a1970", "save_path": "github-repos/MATLAB/vugsus-coursera-machine-learning", "path": "github-repos/MATLAB/vugsus-coursera-machine-learning/coursera-machine-learning-4c2d45cb729355593509abcd41779d19de5a1970/mlclass-ex2/costFunctionReg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811631528336, "lm_q2_score": 0.8962513765975758, "lm_q1q2_score": 0.865224196417096}} {"text": "function value = pyramid_grid_size ( n )\n\n%*****************************************************************************80\n%\n%% PYRAMID_GRID_SIZE sizes a pyramid grid.\n%\n% Discussion:\n%\n% 0: x\n%\n% 1: x x\n% x x\n%\n% 2: x x x\n% x x x\n% x x x\n%\n% 3: x x x x\n% x x x x\n% x x x x\n% x x x x\n%\n% N Size\n%\n% 0 1\n% 1 5 = 1 + 4\n% 2 14 = 1 + 4 + 9\n% 3 30 = 1 + 4 + 9 + 16\n% 4 55 = 1 + 4 + 9 + 16 + 25\n% 5 91 = 1 + 4 + 9 + 16 + 25 + 36\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 August 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of subintervals.\n%\n% Output, integer VALUE, the number of\n% nodes in the grid of size N.\n%\n np1 = n + 1;\n\n value = ( np1 * ( np1 + 1 ) * ( 2 * np1 + 1 ) ) / 6;\n\n return\nend", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/pyramid_grid/pyramid_grid_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897558991952, "lm_q2_score": 0.9196425251212038, "lm_q1q2_score": 0.8651902667232968}} {"text": "function volume = sphere_volume_nd ( dim_num, r )\n\n%*****************************************************************************80\n%\n%% SPHERE_VOLUME_ND computes the volume of an implicit sphere in ND.\n%\n% Discussion:\n%\n% An implicit sphere in ND satisfies the equation:\n%\n% sum ( ( X(1:N) - CENTER(1:N) )^2 ) = R * R\n%\n% where R is the radius and CENTER is the center.\n%\n% Results for the first few values of N are:\n%\n% DIM_NUM Volume\n% - -----------------------\n% 2 PI * R^2\n% 3 (4/3) * PI * R^3\n% 4 (1/2) * PI^2 * R^4\n% 5 (8/15) * PI^2 * R^5\n% 6 (1/6) * PI^3 * R^6\n% 7 (16/105) * PI^3 * R^7\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 03 April 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the dimension of the space.\n%\n% Input, real R, the radius of the sphere.\n%\n% Output, real VOLUME, the volume of the sphere.\n%\n volume = r^dim_num * sphere_unit_volume_nd ( dim_num );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/sphere_volume_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075777163566, "lm_q2_score": 0.899121377945727, "lm_q1q2_score": 0.8650514910083561}} {"text": "function varargout = cyl2cart(varargin)\n%CYL2CART Convert cylindrical to cartesian coordinates\n%\n% CART = cyl2cart(CYL)\n% convert the 3D cylindrical coordinates of points CYL (given by \n% [THETA R Z] where THETA, R, and Z have the same size) into cartesian\n% coordinates CART, given by [X Y Z]. \n% The transforms is the following :\n% X = R*cos(THETA);\n% Y = R*sin(THETA);\n% Z remains inchanged.\n%\n% CART = cyl2cart(THETA, R, Z)\n% provides coordinates as 3 different parameters\n%\n% Example\n% cyl2cart([-1 0 2])\n% gives : 4.7124 1.0000 2.0000\n%\n% See also angles3d, cart2pol, cart2sph2, cart2cyl\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@jouy.inra.fr\n% Created: 2006-03-23\n% Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).\n\n% process input parameters\nif length(varargin)==1\n var = varargin{1};\n theta = var(:,1);\n r = var(:,2);\n z = var(:,3);\nelseif length(varargin)==3\n theta = varargin{1};\n r = varargin{2};\n z = varargin{3};\nend\n\n% convert coordinates\ndim = size(theta);\nx = reshape(r(:).*cos(theta(:)), dim);\ny = reshape(r(:).*sin(theta(:)), dim);\n\n% process output parameters\nif nargout==0 ||nargout==1\n if length(dim)>2 || dim(2)>1\n varargout{1} = {x y z};\n else\n varargout{1} = [x y z];\n end\nelseif nargout==3\n varargout{1} = x;\n varargout{2} = y;\n varargout{3} = z;\nend\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom3d/cyl2cart.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9546474207360066, "lm_q2_score": 0.9059898305367525, "lm_q1q2_score": 0.8649008549349625}} {"text": "function [J, grad] = costFunctionReg(theta, X, y, lambda)\n%COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization\n% J = COSTFUNCTIONREG(theta, X, y, lambda) computes the cost of using\n% theta as the parameter for regularized logistic regression and the\n% gradient of the cost w.r.t. to the parameters. \n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost of a particular choice of theta.\n% You should set J to the cost.\n% Compute the partial derivatives and set grad to the partial\n% derivatives of the cost w.r.t. each parameter in theta\n\nJ = 1 / m * (- y' * log(sigmoid(X * theta)) - (1.- y)' * log(1.- sigmoid(X * theta))) + lambda / (2 * m) * theta(2:end,end)' * theta(2:end,end);\n\ngrad(1,1) = 1 / m * (X(:,1)' * (sigmoid(X * theta) - y))\ngrad(2:end,1) = (1 / m * (X(:,2:end)' * (sigmoid(X * theta) - y)) + lambda / m * theta(2:end));\n\n\n% =============================================================\n\nend\n", "meta": {"author": "xjwhhh", "repo": "AndrewNgMachineLearning", "sha": "d9d8491b315755ea3726bc366d72ba069712c363", "save_path": "github-repos/MATLAB/xjwhhh-AndrewNgMachineLearning", "path": "github-repos/MATLAB/xjwhhh-AndrewNgMachineLearning/AndrewNgMachineLearning-d9d8491b315755ea3726bc366d72ba069712c363/code/machine-learning-ex2/ex2/costFunctionReg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338079816758, "lm_q2_score": 0.8991213826762113, "lm_q1q2_score": 0.864535606922407}} {"text": "function k = triangle_to_i4 ( i, j )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_TO_I4 converts a triangular coordinate to an integer.\n%\n% Discussion:\n%\n% Triangular coordinates are handy when storing a naturally triangular\n% array (such as the lower half of a matrix) in a linear array.\n%\n% Thus, for example, we might consider storing\n%\n% (1,1)\n% (2,1) (2,2)\n% (3,1) (3,2) (3,3)\n% (4,1) (4,2) (4,3) (4,4)\n%\n% as the linear array\n%\n% (1,1) (2,1) (2,2) (3,1) (3,2) (3,3) (4,1) (4,2) (4,3) (4,4)\n%\n% Here, the quantities in parenthesis represent the natural row and\n% column indices of a single number when stored in a rectangular array.\n%\n% Thus, our goal is, given the row I and column J of the data,\n% to produce the value K which indicates its position in the linear\n% array.\n%\n% The triangular numbers are the indices associated with the\n% diagonal elements of the original array, T(1,1), T(2,2), T(3,3)\n% and so on.\n%\n% Formula:\n%\n% K = J + ( (I-1) * I ) / 2\n%\n% First Values:\n%\n% I J K\n%\n% 0 0 0\n% 1 1 1\n% 2 1 2\n% 2 2 3\n% 3 1 4\n% 3 2 5\n% 3 3 6\n% 4 1 7\n% 4 2 8\n% 4 3 9\n% 4 4 10\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 July 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer I, J, the row and column indices. I and J must\n% be nonnegative, and J must not be greater than I.\n%\n% Output, integer K, the linear index of the (I,J) element.\n%\n if ( i < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGLE_TO_I4 - Fatal error!\\n' );\n fprintf ( 1, ' I < 0.\\n' );\n fprintf ( 1, ' I = %d\\n', i );\n error ( 'TRIANGLE_TO_I4 - Fatal error!' );\n elseif ( j < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGLE_TO_I4 - Fatal error!\\n' );\n fprintf ( 1, ' J < 0.\\n' );\n fprintf ( 1, ' J = %d\\n', j );\n error ( 'TRIANGLE_TO_I4 - Fatal error!' );\n elseif ( i < j )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGLE_TO_I4 - Fatal error!\\n' );\n fprintf ( 1, ' I < J.\\n' );\n fprintf ( 1, ' I = %d\\n', i );\n fprintf ( 1, ' J = %d\\n', j );\n error ( 'TRIANGLE_TO_I4 - Fatal error!' );\n end\n\n k = j + ( ( i - 1 ) * i ) / 2;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/triangle_to_i4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140232, "lm_q2_score": 0.9252299607000298, "lm_q1q2_score": 0.8645303978257337}} {"text": "function [ n_data, n, c ] = catalan_values ( n_data )\n\n%*****************************************************************************80\n%\n%% CATALAN_VALUES returns some values of the Catalan numbers.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% Binomial[2*n,n] / ( n + 1 )\n%\n% First values:\n%\n% C(0) 1\n% C(1) 1\n% C(2) 2\n% C(3) 5\n% C(4) 14\n% C(5) 42\n% C(6) 132\n% C(7) 429\n% C(8) 1430\n% C(9) 4862\n% C(10) 16796\n%\n% Formula:\n%\n% C(N) = (2*N)! / ( (N+1) * (N!) * (N!) ) \n% = 1 / (N+1) * COMB ( 2N, N )\n% = 1 / (2N+1) * COMB ( 2N+1, N+1).\n%\n% Recursion:\n%\n% C(N) = 2 * (2*N-1) * C(N-1) / (N+1)\n% C(N) = sum ( 1 <= I <= N-1 ) C(I) * C(N-I)\n%\n% Discussion:\n%\n% The Catalan number C(N) counts:\n%\n% 1) the number of binary trees on N vertices;\n% 2) the number of ordered trees on N+1 vertices;\n% 3) the number of full binary trees on 2N+1 vertices;\n% 4) the number of well formed sequences of 2N parentheses;\n% 5) the number of ways 2N ballots can be counted, in order,\n% with N positive and N negative, so that the running sum\n% is never negative;\n% 6) the number of standard tableaus in a 2 by N rectangular Ferrers diagram;\n% 7) the number of monotone functions from [1..N} to [1..N} which \n% satisfy f(i) <= i for all i;\n% 8) the number of ways to triangulate a polygon with N+2 vertices.\n%\n% Example:\n%\n% N = 3\n%\n% ()()()\n% ()(())\n% (()())\n% (())()\n% ((()))\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, integer N, the order of the Catalan number.\n%\n% Output, integer C, the value of the Catalan number.\n%\n n_max = 11;\n\n c_vec = [ ...\n 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796 ];\n\n n_vec = [ ...\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];\n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n n = 0;\n c = 0;\n else\n n = n_vec(n_data);\n c = c_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/catalan_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.9124361616674908, "lm_q1q2_score": 0.8644247285550667}} {"text": "function centroid = polygon_centroid_2d ( n, v )\n\n%*****************************************************************************80\n%\n%% POLYGON_CENTROID_2D computes the centroid of a polygon in 2D.\n%\n% Discussion:\n%\n% Denoting the centroid coordinates by CENTROID, then\n%\n% CENTROID(1) = Integral ( Polygon interior ) x dx dy / Area ( Polygon )\n% CENTROID(2) = Integral ( Polygon interior ) y dx dy / Area ( Polygon ).\n%\n% Green's theorem states that for continuously differentiable functions\n% M(x,y) and N(x,y),\n%\n% Integral ( Polygon boundary ) ( M dx + N dy ) =\n% Integral ( Polygon interior ) ( dN/dx - dM/dy ) dx dy.\n%\n% Using M(x,y) = 0 and N(x,y) = x**2/2, we get:\n%\n% CENTROID(1) = 0.5 * Integral ( Polygon boundary ) x**2 dy\n% / Area ( Polygon ),\n%\n% which becomes\n%\n% CENTROID(1) = 1/6 sum ( 1 <= I <= N )\n% ( X(I+1) + X(I) ) * ( X(I) * Y(I+1) - X(I+1) * Y(I))\n% / Area ( Polygon )\n%\n% where, when I = N, the index \"I+1\" is replaced by 1.\n%\n% A similar calculation gives us a formula for CENTROID(2).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Gerard Bashein and Paul Detmer,\n% Centroid of a Polygon,\n% Graphics Gems IV,\n% edited by Paul Heckbert,\n% AP Professional, 1994.\n%\n% Parameters:\n%\n% Input, integer N, the number of sides of the polygon.\n%\n% Input, real V(2,N), the coordinates of the vertices.\n%\n% Output, real CENTROID(2,1), the coordinates of the centroid.\n%\n area = 0.0;\n centroid(1:2,1) = 0.0;\n\n for i = 1 : n\n\n if ( i < n )\n ip1 = i + 1;\n else\n ip1 = 1;\n end\n\n temp = ( v(1,i) * v(2,ip1) - v(1,ip1) * v(2,i) );\n\n area = area + temp;\n\n centroid(1:2,1) = centroid(1:2,1) + ( v(1:2,ip1) + v(1:2,i) )' * temp;\n\n end\n\n area = area / 2.0;\n\n if ( area == 0.0 )\n centroid(1:2,1) = v(1:2,1);\n else\n centroid(1:2,1) = centroid(1:2,1) / ( 6.0 * area );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/polygon_centroid_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.91610961358942, "lm_q1q2_score": 0.864209786508956}} {"text": "function[f]=fourier(varargin)\n%FOURIER Returns the Fourier frequencies for a given length time series.\n%\n% F=FOURIER(M) returns the one-sided (or positive) Fourier frequencies \n% for a time series of length M. \n%\n% F is a radian or angular frequency so that the Nyquist is at PI.\n%\n% F=FOURIER(M,'two') instead returns the two-sided Fourier frequencies.\n% The default behavior is equivalent to F=FOURIER(M,'one').\n%\n% F=FOURIER(DT,M) uses sample rate DT in calculating the frequencies, so\n% that the Nyquist will be at PI/DT.\n% \n% Note that the highest resolved frequency, MAX(F), differs for even or\n% odd M. For even M, it is the Nyquist PI/DT, but for odd M the Nyquist\n% is not resolved and the highest resolved frequency is (M-1)/M * PI/DT.\n%\n% For the one-sided option, F has length FLOOR(M/2)+1, or M/2+1 for even \n% M, and (M+1)/2 for odd M. For the two-sided option, F has length M.\n% __________________________________________________________________\n%\n% Array input\n%\n% F=FOURIER(M) also works if M an array instead of a scalar. In this\n% case, F is a cell array with LENGTH(M) elements.\n%\n% F=FOURIER(DT,M) with M being an array works provided DT is either a \n% scalar or an array of the same length as M. \n% __________________________________________________________________\n%\n% See also CENTEREDTIMES.\n%\n% Usage: f=fourier(M);\n% f=fourier(dt,M);\n% f=fourier(dt,M,'two');\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2011--2019 J.M. Lilly --- type 'help jlab_license' for details\n \nif strcmpi(varargin{1}, '--t')\n fourier_test,return\nend\n\nstr='one';\nif ischar(varargin{end})\n str=varargin{end}(1:3);\n varargin=varargin(1:end-1);\nend\n\nif length(varargin)==1\n N=varargin{1};\n dt=1;\nelse\n dt=varargin{1};\n N=varargin{2};\nend\n\nif length(N)==1\n f=fourier_one(dt,N,str);\nelse\n if length(dt)==1\n dt=dt+zeros(size(N));\n elseif length(dt)~=length(N)\n error('If N is an array, DT must either be a scalar or an array of the same length.')\n end\n for i=1:length(N)\n f{i,1}=fourier_one(dt,N(i),str);\n end\nend\n\nfunction[f]=fourier_one(dt,N,str)\n\nif strcmpi(str,'one')\n f=2*pi*(0:floor(N/2))'./N;\nelse\n f=2*pi*(0:N-1)'./N;\n index=find(f>pi);\n f(index)=f(index)-2*pi;\nend\n\n% if iseven(N)\n% f=(0:1./N:1/2)';\n% elseif isodd(N)\n% f=(0:1./N:1/2*frac(N-1,N))';\n% end\n\nf=f./dt;\n\nfunction[]=fourier_test\n\nreporttest('FOURIER is length N/2+1 for even N',length(fourier(10))==6);\nreporttest('FOURIER is length (N+1)/2 for odd N',length(fourier(11))==6);\n\n%Even and odd length frequencies behave differently, which you can see with \n%abs(fft(cos(pi*[1:10]'))).^2\n%abs(fft(cos(pi*[1:11]'))).^2\n%abs(fft(cos((10/11)*pi*[1:11]'))).^2\n", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jSpectral/fourier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.9161096147346158, "lm_q1q2_score": 0.8642097788346186}} {"text": "function h=sgsf_2d(x,y,px,py,flag_coupling)\n%Function:\n% 2-D Savitzky-Golay smoothing filter (i.e., the polynomial smoothing\n% filter, or the least-squares smoothing filter)\n% See Ref. [1] for details on the 1-D Savitzky-Golay smoothing filter. \n% One can also refer to the following URL where a program of\n% 1-D Savitzky-Golay smoothing (and differentiation) filter is given:\n% http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=4038&objectType=file\n% See Ref. [2] and [3] for details on the 2-D Savitzky-Golay smoothing filter. \n%Usage:\n% h=sgsf_2d(x,y,px,py,flag_coupling)\n% x = x data point, e.g., -3:3\n% y = y data point, e.g., -2:2 \n% px =x polynomial order default=1 \n% py =y polynomial order default=1\n% flag_coupling = with or without the consideration of the coupling terms, between x and y. default=0\n%Example:\n% sgsf_2d(-3:3,-3:3,2,2)\n% sgsf_2d(-3:3,-3:3,2,2,1) \n%Author:\n% Jianwen Luo 2003-12-15\n% Department of Biomedical Engineering, Department of Electrical Engineering\n% Tsinghua University, Beijing 100084, P. R. China \n%Reference\n%[1]A. Savitzky and M. J. E. Golay, \"Smoothing and Differentiation of Data by Simplified Least Squares Procedures,\" \n% Analytical Chemistry, vol. 36, pp. 1627-1639, 1964.\n%[2]K. L. Ratzlaff and J. T. Johnson, \"Computation of Two-Dimensional Polynomial Least-Squares Convolution Smoothing Integers,\" \n% Analytical Chemistry, vol. 61, pp. 1303-1305, 1989.\n%[3]J. E. Kuo, H. Wang, and S. Pickup, \"Multidimensional Least-Squares Smoothing Using Orthogonal Polynomials,\" \n% Analytical Chemistry, vol. 63, pp. 630-635, 1991.\n\nif nargin<5\n flag_coupling=0;\nend\n\nif nargin<4\n py=1;\nend\n\nif nargin<3\n px=1;\nend\n\n\n[x,y]=meshgrid(x,y);\n[ly,lx]=size(x);\n\nx=x(:);\ny=y(:);\n\nA=[];\n\nif flag_coupling\n for kx=px:-1:0\n for ky=py:-1:0\n A=[A x.^kx.*y.^ky];\n end\n end \nelse\n for k=px:-1:1\n A=[A x.^k];\n end\n for k=py:-1:0\n A=[A y.^k];\n end \nend\n\nh=inv(A'*A)*A';\nh=h(size(h,1),:);\nh=reshape(h,ly,lx);\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/4270-2-d-savitzky-golay-smoothing-filter/sgsf_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211324, "lm_q2_score": 0.9161096153072138, "lm_q1q2_score": 0.8642097779156682}} {"text": "function [g, c, tmp, m]=kMeansCluster(m,k,isRand)\n%%%%%%%%%%%%%%%%\n% \n% kMeansCluster - Simple k means clustering algorithm \n% Author: Kardi Teknomo, Ph.D. \n% \n% Purpose: classify the objects in data matrix based on the attributes \n% Criteria: minimize Euclidean distance between centroids and object points \n% For more explanation of the algorithm, see http://people.revoledu.com/kardi/tutorial/kMean/index.html \n% Output: matrix data plus an additional column represent the group of each object \n% \n% Example: m = [ 1 1; 2 1; 4 3; 5 4] or in a nice form \n% m = [ 1 1; \n% 2 1; \n% 4 3; \n% 5 4] \n% k = 2 \n% kMeansCluster(m,k) produces m = [ 1 1 1; \n% 2 1 1; \n% 4 3 2; \n% 5 4 2] \n% Input:\n% m - required, matrix data: objects in rows and attributes in columns \n% k - optional, number of groups (default = 1)\n% isRand - optional, if using random initialization isRand=1, otherwise input any number (default)\n% it will assign the first k data as initial centroids\n%\n% Local Variables\n% f - row number of data that belong to group i\n% c - centroid coordinate size (1:k, 1:maxCol)\n% g - current iteration group matrix size (1:maxRow)\n% i - scalar iterator \n% maxCol - scalar number of rows in the data matrix m = number of attributes\n% maxRow - scalar number of columns in the data matrix m = number of objects\n% temp - previous iteration group matrix size (1:maxRow)\n% z - minimum value (not needed)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin<3, isRand=0; end\nif nargin<2, k=1; end\ntmp = [];\n\n[maxRow, maxCol]=size(m);\nif maxRow<=k, \n y=[m, 1:maxRow];\nelse\n\t\n\t% initial value of centroid\n if isRand,\n p = randperm(size(m,1)); % random initialization\n for i=1:k\n c(i,:)=m(p(i),:) \n \tend\n else\n for i=1:k\n c(i,:)=m(i,:); % sequential initialization\n \tend\n end\n \n\ttemp=zeros(maxRow,1); % initialize as zero vector\n \n\twhile 1,\n d=DistMatrix(m,c); % calculate objcets-centroid distances\n [z,g]=min(d,[],2); % find group matrix g\n if g==temp,\n break; % stop the iteration\n else\n temp=g; % copy group matrix to temporary variable\n end\n for i=1:k\n f=find(g==i);\n if f % only compute centroid if f is not empty\n c(i,:)=mean(m(find(g==i),:),1);\n end\n end\n\tend\n \n\ty=[m,g];\n \nend\n\n%The Matlab function kMeansCluster above call function DistMatrix as shown in the code below. It works for multi-dimensional Euclidean distance. Learn about other type of distance here.\n\n function d=DistMatrix(A,B)\n %%%%%%%%%%%%%%%%%%%%%%%%%\n % DISTMATRIX return distance matrix between points in A=[x1 y1 ... w1] and in B=[x2 y2 ... w2]\n % Copyright (c) 2005 by Kardi Teknomo, http://people.revoledu.com/kardi/\n %\n % Numbers of rows (represent points) in A and B are not necessarily the same.\n % It can be use for distance-in-a-slice (Spacing) or distance-between-slice (Headway),\n %\n % A and B must contain the same number of columns (represent variables of n dimensions),\n % first column is the X coordinates, second column is the Y coordinates, and so on.\n % The distance matrix is distance between points in A as rows\n % and points in B as columns.\n % example: Spacing= dist(A,A)\n % Headway = dist(A,B), with hA ~= hB or hA=hB\n % A=[1 2 3; 4 5 6; 2 4 6; 1 2 3]; B=[4 5 1; 6 2 0]\n % dist(A,B)= [ 4.69 5.83;\n % 5.00 7.00;\n % 5.48 7.48;\n % 4.69 5.83]\n %\n % dist(B,A)= [ 4.69 5.00 5.48 4.69;\n % 5.83 7.00 7.48 5.83]\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\n [hA,wA]=size(A);\n [hB,wB]=size(B);\n if wA ~= wB, error(' second dimension of A and B must be the same'); end\n for k=1:wA\n C{k}= repmat(A(:,k),1,hB);\n D{k}= repmat(B(:,k),1,hA);\n end\n S=zeros(hA,hB);\n for k=1:wA\n S=S+(C{k}-D{k}').^2;\n end\n d=sqrt(S);\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/sigprocfunc/kmeanscluster.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.9219218423633527, "lm_q1q2_score": 0.8640351011098603}} {"text": "function S = cylinderSurfaceArea(cyl)\n%CYLINDERSURFACEAREA Surface area of a cylinder.\n%\n% S = cylinderSurfaceArea(CYL)\n% Computes the surface area of the cylinder defined by:\n% CYL = [X1 Y1 Z1 X2 Y2 Z2 R], \n% where [X1 Y1 Z1] and [X2 Y2 Z2] are the coordinates of the cylinder\n% extremities, and R is the cylinder radius.\n% The surface area of the cylinder comprises the surface area of the two\n% disk-shape end caps.\n%\n% Example\n% cyl = [0 0 0 1 0 0 1];\n% cylinderSurfaceArea(cyl)\n% ans =\n% 12.5664\n% % equals to 4*pi\n%\n% See also \n% geom3d, ellipsoidSurfaceArea, intersectLineCylinder\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2017-11-02, using Matlab 9.3.0.713579 (R2017b)\n% Copyright 2017-2022 INRA - Cepia Software Platform\n\nH = distancePoints3d(cyl(:, 1:3), cyl(:, 4:6));\nR = cyl(:,7);\n\nS1 = 2*pi*R .* H;\nS2 = 2 * (pi * R.^2);\n\nS = S1 + S2;\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom3d/cylinderSurfaceArea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843811, "lm_q2_score": 0.9019206857566126, "lm_q1q2_score": 0.8639608933330198}} {"text": "function [Zpca T U mu eigVecs] = myPCA(Z,r)\n%--------------------------------------------------------------------------\n% Syntax: Zpca = myPCA(Z,r);\n% [Zpca T U mu] = myPCA(Z,r);\n% [Zpca T U mu eigVecs] = myPCA(Z,r);\n% \n% Inputs: Z is an (d x n) matrix containing n samples of a\n% d-dimensional random vector\n% \n% r is the desired number of principal components\n% \n% Outputs: Zpca is a (r x n) matrix containing the r principal\n% components - scaled to variance 1 - of the input samples\n% \n% U and T are the PCA transformation matrices such that\n% Zr = U / T * Zpca + repmat(mu,1,n);\n% is the r-dimensional PCA approximation of Z\n% \n% mu is the (d x 1) sample mean of Z\n% \n% eigVecs is a (d x r) matrix containing the scaled\n% eigenvectors of the sample covariance of Z\n% \n% Description: This function performs principal component analysis (PCA)\n% on the input samples\n% \n% Author: Brian Moore\n% brimoor@umich.edu\n% \n% Date: April 26, 2015\n%--------------------------------------------------------------------------\n\n% Center data\n[Zc mu] = myCenter(Z);\n\n% Compute truncated SVD\n%[U S V] = svds(Zc,r); % Equivalent, but usually slower than svd()\n[U S V] = svd(Zc,'econ');\nU = U(:,1:r);\nS = S(1:r,1:r);\nV = V(:,1:r);\n\n% Compute principal components\nZpca = S * V';\n%Zpca = U' * Zc; % Equivalent but slower\n\n% Whiten data, if desired\n%[Zpca T] = myWhiten(Zpca);\nT = eye(r); % No whitening\n\n% Return scaled eigenvectors, if necessary\nif (nargout >= 5)\n [~,n] = size(Z);\n eigVecs = bsxfun(@times,U,diag(S)' / sqrt(n));\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/分类算法/deephypercnn-master/Matlab-Sat-Data/pca_ica/myPCA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.9059898254600902, "lm_q1q2_score": 0.8636574907551141}} {"text": "% EUCL: Calculates the euclidean distances among a set of points, or between a\n% reference point and a set of points, or among all possible pairs of two \n% sets of points, in P dimensions. Returns a single distance for two points.\n%\n% Syntax: dists = eucl(crds1,crds2)\n%\n% crds1 = [N1 x P] matrix of point coordinates. If N=1, it is taken to\n% be the reference point.\n% crds2 = [N2 x P] matrix of point coordinates. If N=1, it is taken to\n% be the reference point.\n% -----------------------------------------------------------------------\n% dists = [N1 x N1] symmetric matrix of pairwise distances (if only crds1\n% is specified);\n% [N1 x 1] col vector of euclidean distances (if crds1 & ref\n% are specified);\n% [1 x N2] row vector of euclidean distances (if ref & crds2\n% are specified);\n% [N1 x N2] rectangular matrix of pairwise distances (if crds1\n% & crds2 are specified);\n% [1 x 1] scalar (if crds1 is a [2 x P] matrix or ref1 & ref2\n% are specified);\n%\n\n% RE Strauss, 5/4/94\n% 10/28/95 - output row (rather than column) vector for the (reference\n% point)-(set of points) case; still outputs column vector for the\n% (set of points)-(reference point) case.\n% 10/30/95 - for double for-loops, put one matrix-col access in outer loop\n% to increase speed.\n% 10/12/96 - vectorize inner loop to increase speed.\n% 6/12/98 - allow for P=1.\n% 11/11/03 - initialize dists to NaN for error return.\n\nfunction dists = eucl(crds1,crds2)\n if (~nargin) help eucl; return; end;\n dists = NaN;\n\n if (nargin < 2) % If only crds1 provided,\n [N,P] = size(crds1);\n if (N<2)\n error(' EUCL: need at least two points');\n end;\n\n crds1 = crds1'; % Transpose crds\n dists = zeros(N,N); % Calculate pairwise distances\n\n for i = 1:N-1\n c1 = crds1(:,i) * ones(1,N-i);\n if (P>1)\n d = sqrt(sum((c1-crds1(:,(i+1:N))).^2));\n else\n d = abs(c1-crds1(:,(i+1:N)));\n end;\n dists(i,(i+1:N)) = d;\n dists((i+1:N),i) = d';\n end;\n if (N==2) % Single distance for two points\n dists = dists(1,2);\n end;\n\n else % If crds1 & crds2 provided,\n [N1,P1] = size(crds1);\n [N2,P2] = size(crds2);\n if (P1~=P2)\n error(' EUCL: sets of coordinates must be of same dimension');\n else\n P = P1;\n end;\n\n crds1 = crds1'; % Transpose crds\n crds2 = crds2';\n\n if (N1>1 & N2>1) % If two matrices provided,\n dists = zeros(N1,N2); % Calc all pairwise distances between them\n for i = 1:N1\n c1 = crds1(:,i) * ones(1,N2);\n if (P>1)\n d = sqrt(sum((c1-crds2).^2));\n else\n d = abs(c1-crds2);\n end;\n dists(i,:) = d;\n end;\n end;\n\n if (N1==1 & N2==1) % If two vectors provided,\n dists = sqrt(sum((crds1-crds2).^2)); % Calc scalar\n end;\n\n if (N1>1 & N2==1) % If matrix & reference point provided,\n crds1 = crds1 - (ones(N1,1)*crds2')'; % Center points on reference point\n if (P>1) % Calc euclidean distances in P-space\n dists = sqrt(sum(crds1.^2))';\n else\n dists = abs(crds1)';\n end;\n end; % Return column vector\n\n if (N1==1 & N2>1) % If reference point & matrix provided,\n crds2 = crds2 - (ones(N2,1)*crds1')'; % Center points on reference point\n if (P>1) % Calc euclidean distances in P-space\n dists = sqrt(sum(crds2.^2));\n else\n dists = abs(crds2);\n end;\n end; % Return row vector\n end;\n\n return;\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/miscfunc/eucl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813488829417, "lm_q2_score": 0.9032942021480235, "lm_q1q2_score": 0.8635324098076081}} {"text": "function area = triangleArea(pt1, pt2, pt3)\n%TRIANGLEAREA Signed area of a triangle.\n%\n% AREA = triangleArea(P1, P2, P3)\n% Computes area of the triangle whose vertices are given by P1, P2 and\n% P3. Each vertex is a 1-by-2 row vector. \n%\n% AREA = triangleArea(PTS)\n% Concatenates vertex coordinates in a 3-by-2 array. Each row of the\n% array contains coordinates of one vertex.\n%\n%\n% Example\n% % Compute area of a Counter-Clockwise (CCW) oriented triangle\n% triangleArea([10 10], [30 10], [10 40])\n% ans = \n% 300\n%\n% % Compute area of a Clockwise (CW) oriented triangle\n% triangleArea([10 40], [30 10], [10 10])\n% ans = \n% -300\n%\n% See also \n% polygonArea, triangleArea3d\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2011-08-23, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011-2022 INRA - Cepia Software Platform\n\n% if data is given as one array, split vertices\nif nargin == 1\n pt2 = pt1(2,:);\n pt3 = pt1(3,:);\n pt1 = pt1(1,:);\nend\n\n% compute individual vectors\nv12 = bsxfun(@minus, pt2, pt1);\nv13 = bsxfun(@minus, pt3, pt1);\n\n% compute area from cross product\narea = (v13(:,2) .* v12(:,1) - v13(:,1) .* v12(:,2)) / 2;\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom2d/triangleArea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172615983309, "lm_q2_score": 0.9099070127565249, "lm_q1q2_score": 0.8634264708540391}} {"text": "%SOLVELP Solve given (non-integer) linear programming problem using the Simplex Algorithm\n%\n% [z, res] = cv.solveLP(Func, Constr)\n% [...] = cv.solveLP(..., 'OptionName', optionValue, ...)\n%\n% ## Input\n% * __Func__ This row-vector corresponds to `c` in the LP problem formulation\n% (see below). It should contain 32- or 64-bit floating-point numbers. As a\n% convenience, column-vector may be also submitted, in the latter case it is\n% understood to correspond to `c'`.\n% * __Constr__ m-by-n+1 matrix, whose rightmost column corresponds to `b` in\n% formulation above and the remaining to `A`. It should contain 32 or 64-bit\n% floating-point numbers.\n%\n% ## Output\n% * __z__ The solution will be returned here as a column-vector, it\n% corresponds to `x` in the formulation above. It will contain 64-bit\n% floating-point numbers.\n% * __res__ Return code. One of:\n% * __Unbounded__ problem is unbounded (target function can achieve\n% arbitrary high values)\n% * __Unfeasible__ problem is unfeasible (there are no points that satisfy\n% all the constraints imposed)\n% * __Single__ there is only one maximum for target function\n% * __Multi__ there are multiple maxima for target function, the arbitrary\n% one is returned\n%\n% What we mean here by \"linear programming problem\" (or LP problem, for short)\n% can be formulated as:\n%\n% Maximize c*x\n% subject to A*x <= b\n% x >= 0\n%\n% Where `c` is fixed 1-by-n row-vector, `A` is fixed m-by-n matrix, `b` is\n% fixed m-by-1 column vector and `x` is an arbitrary n-by-1 column vector,\n% which satisfies the constraints.\n%\n% Simplex algorithm is one of many algorithms that are designed to handle this\n% sort of problems efficiently. Although it is not optimal in theoretical\n% sense (there exist algorithms that can solve any problem written as above in\n% polynomial type, while simplex method degenerates to exponential time for\n% some special cases), it is well-studied, easy to implement and is shown to\n% work well for real-life purposes.\n%\n% The particular implementation is taken almost verbatim from:\n%\n% > Introduction to Algorithms, 3rd edition\n% > by T. H. Cormen, C. E. Leiserson, R. L. Rivest and Clifford Stein.\n%\n% In particular, the [Bland's rule](https://en.wikipedia.org/wiki/Bland%27s_rule)\n% is used to prevent cycling.\n%\n% See also: linprog\n%\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/+cv/solveLP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.9136765292901317, "lm_q1q2_score": 0.8634194883895653}} {"text": "function value = zeta ( p )\n\n%*****************************************************************************80\n%\n%% ZETA estimates the Riemann Zeta function.\n%\n% Discussion:\n%\n% For 1 < P, the Riemann Zeta function is defined as:\n%\n% ZETA ( P ) = Sum ( 1 <= N < Infinity ) 1 / N**P\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Daniel Zwillinger, editor,\n% CRC Standard Mathematical Tables and Formulae,\n% 30th Edition,\n% CRC Press, 1996.\n%\n% Parameters:\n%\n% Input, real P, the power to which the integers are raised.\n% P must be greater than 1. For integral P up to 20, a\n% precomputed value of ZETA is returned; otherwise the infinite\n% sum is approximated.\n%\n% Output, real VALUE, an approximation to the Riemann\n% Zeta function.\n%\n if ( p <= 1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ZETA - Fatal error!\\n' );\n fprintf ( 1, ' Exponent P <= 1.0.\\n' );\n error ( 'ZETA - Fatal error!' );\n elseif ( p == 2.0 )\n value = pi^2 / 6.0;\n elseif ( p == 3.0 )\n value = 1.2020569032;\n elseif ( p == 4.0 )\n value = pi^4 / 90.0;\n elseif ( p == 5.0 )\n value = 1.0369277551;\n elseif ( p == 6.0 )\n value = pi^6 / 945.0;\n elseif ( p == 7.0 )\n value = 1.0083492774;\n elseif ( p == 8.0 )\n value = pi^8 / 9450.0;\n elseif ( p == 9.0 )\n value = 1.0020083928;\n elseif ( p == 10.0 )\n value = pi^10 / 93555.0;\n elseif ( p == 11.0 )\n value = 1.0004941886;\n elseif ( p == 12.0 )\n value = 1.0002460866;\n elseif ( p == 13.0 )\n value = 1.0001227133;\n elseif ( p == 14.0 )\n value = 1.0000612482;\n elseif ( p == 15.0 )\n value = 1.0000305882;\n elseif ( p == 16.0 )\n value = 1.0000152823;\n elseif ( p == 17.0 )\n value = 1.0000076372;\n elseif ( p == 18.0 )\n value = 1.0000038173;\n elseif ( p == 19.0 )\n value = 1.0000019082;\n elseif ( p == 20.0 )\n value = 1.0000009540;\n else\n\n zsum = 0.0;\n n = 0;\n\n while ( 1 )\n\n n = n + 1;\n zsum_old = zsum;\n zsum = zsum + 1.0 / n^p;\n\n if ( zsum <= zsum_old )\n break\n end\n\n end\n\n value = zsum;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/zeta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966098909522, "lm_q2_score": 0.9046505447409665, "lm_q1q2_score": 0.8630059510429138}} {"text": "function [theta] = normalEqn(X, y)\n%NORMALEQN Computes the closed-form solution to linear regression \n% NORMALEQN(X,y) computes the closed-form solution to linear \n% regression using the normal equations.\n\ntheta = zeros(size(X, 2), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the code to compute the closed form solution\n% to linear regression and put the result in theta.\n%\n\n% ---------------------- Sample Solution ----------------------\n\n\ntheta = pinv(X' * X) * X' * y;\n\n\n% -------------------------------------------------------------\n\n\n% ============================================================\n\nend\n", "meta": {"author": "vugsus", "repo": "coursera-machine-learning", "sha": "4c2d45cb729355593509abcd41779d19de5a1970", "save_path": "github-repos/MATLAB/vugsus-coursera-machine-learning", "path": "github-repos/MATLAB/vugsus-coursera-machine-learning/coursera-machine-learning-4c2d45cb729355593509abcd41779d19de5a1970/mlclass-ex1/normalEqn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9566342012360932, "lm_q2_score": 0.9019206811430764, "lm_q1q2_score": 0.86280817038362}} {"text": "function h=hermfun(t,j)\n%HERMFUN Orthonormal Hermite functions. [with F. Rekibi]\n%\n% H=HERMFUN(T,N) generates the fisrt N+1 orthonormal Hermite functions\n% [H0,...HN] on a time axis specfied by the column vector T.\n%\n% HERMFUN uses the expression of Simons et al. 2003.\n% \n% Note that H(:,1) is the zeroth-order Hermite function, which is equal\n% to a Gaussian. H(:,2) is the first-order function, and so forth. \n% \n% See also HERMPOLY.\n%\n% 'hermfun --f' generates a sample figure; compare with the Hermite \n% function figure at\n%\n% http://en.wikipedia.org/wiki/Hermite_polynomials#Definition\n%\n% Usage: h=hermfun(t,n);\n% _________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information \n% (C) 2004--2015 F. Rekibi and J. M. Lilly\n% --- type 'help jlab_license' for details\n\n% 05.08.07 JML fixed bug to include N+1 columns\n\n% 'hermfun --f' generates a sample figure; compare with Figure 2 \n% of Simons, van der Hilst, and Zuber (2003), JGR 108 B5.\n\nif strcmpi(t,'--f')\n type makefigs_hermfun\n makefigs_hermfun;\n return\nend\n\nif size(t,1)==1\n t=t';\nend\n\nH=hermpoly(t,j);\n\nE=exp(-t.^2/2)*ones(1,j+1);\nHE=H.*E;\n\nh=zeros(length(t),j);\nfor k=1:j+1\n\th(:,k)=HE(:,k)*frac(1,pi^(1/4))*frac(1,sqrt(2^(k-1)*factorial(k-1)));\nend\n\n", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jCommon/hermfun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001757, "lm_q2_score": 0.9111797100118214, "lm_q1q2_score": 0.8625196794511518}} {"text": "function intVal=ellipIntInc1Kind(phi,m)\n%%ELLIPINTINC1KIND Evaluate Legendre's incomplete elliptical integral of\n% the first kind. This is the integral from 0 to phi of\n% (1-m*sin(theta)^2)^(-1/2) dtheta. Alternatively, this\n% can be written as the integral from 0 to x of\n% ((1-t^2)*(1-m*t^2))^(-1/2) dt where x=sin(phi). This\n% integral is sometimes referred to as F.\n%\n%INPUTS: phi A scalar or matrix of the real upper bounds of integration.\n% These can be positive, negative or zero.\n% m A value between 0 and 1. The integral diverges when m=1 and\n% phi=pi/2.\n%\n%OUTPUTS: intVal The values of the incomplete elliptic integral of the\n% first kind evaluated at each entry in phi.\n%\n%The expression used to implement the function comes from [1], whereby\n%negative values are handled by switching the sign of the result. The above\n%algorithm also only considers values with magnitudes up to pi/2. To get\n%the correct result, however, for larger values, the value up to pi/2\n%(times the number of multiples of the value up to pi/2) is added to a\n%fractional part with magnitude less than pi/2. Note however, that due to\n%the odd symmetry of sin(x)^2, if the integer part is odd, then the\n%computation subtracts the fractional part from pi/2 and the value added is\n%the value of the complete integral MINUS the modified fractional part.\n%\n%REFERENCES:\n%[1] B. C. Carlson, \"Numerical computation of real or complex elliptic\n% integrals,\" Numerical Algorithms, vol. 10, no. 1, pp. 13-26, 1995.\n%\n%September 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumItems=length(phi(:));\nintVal=zeros(size(phi));\n\nfor curItem=1:numItems\n phiCur=phi(curItem);\n \n phiSign=sign(phiCur);\n phiCur=abs(phiCur);\n \n %Separate out the multiples of pi/2 from the rest of the values.\n intPart=fix(phiCur/(pi/2));\n if(intPart>0)\n completeVal=symIntFirstKind(0,1-m,1);\n phiCur=phiCur-intPart*(pi/2);\n else\n completeVal=0;\n end\n \n %The test deals with precision limitations that would prevent the other\n %integral from converging.\n if(phiCur rotation angle\n theta = varargin{1};\n \nelseif length(varargin) == 2\n % origin point (as array) and angle\n var = varargin{1};\n dx = var(1);\n dy = var(2);\n dz = var(3);\n theta = varargin{2};\n \nelseif length(varargin) == 4\n % origin (x and y) and angle\n dx = varargin{1};\n dy = varargin{2};\n dz = varargin{3};\n theta = varargin{4};\nend\n\n% compute coefs\ncot = cos(theta);\nsit = sin(theta);\n\n% create transformation\ntrans = [...\n cot -sit 0 0;...\n sit cot 0 0;...\n 0 0 1 0;...\n 0 0 0 1];\n\n% add the translation part\nt = [1 0 0 dx;0 1 0 dy;0 0 1 dz;0 0 0 1];\ntrans = t * trans / t;\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom3d/createRotationOz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762057376384, "lm_q2_score": 0.8976952948443462, "lm_q1q2_score": 0.8615738830769093}} {"text": "function hits = buffon_simulate ( a, l, trial_num )\n\n%*****************************************************************************80\n%\n%% BUFFON_SIMULATE simulates a Buffon needle experiment.\n%\n% Discussion:\n%\n% In the Buffon needle experiment, we suppose that the plane has been\n% ruled by vertical lines with a spacing of A units, and that a\n% needle of length L is dropped \"at random\" onto this grid.\n%\n% Because of the various symmetries, we may assume that this eye of\n% this needle lands in the first infinite strip, and we may further\n% assume that its Y coordinate is 0. Thus, we have\n% the eye as (X1,Y1) with 0 <= X1 <= A and Y1 = 0.\n%\n% ANGLE, the angle that the needle makes is taken to be uniformly random.\n% The point of the needle, (X2,Y2), therefore lies at\n%\n% (X2,Y2) = ( X1+L*cos(ANGLE), Y1+L*sin(ANGLE) )\n%\n% The needle will have crossed at least one grid line if any of the\n% following are true:\n%\n% X2 <= 0, A <= X2.\n%\n% The probability of a crossing on a single trial is\n%\n% P(A,L) = ( 2 * L ) / ( PI * A )\n%\n% and therefore, a record of the number of hits for a given number of\n% trials can be used as a very roundabout way of estimating PI.\n%\n% Note that this routine will try to generate 4 * TRIAL_NUM random\n% double precision values at one time, using automatic arrays.\n% When I tried this with TRIAL_NUM = 1,000,000, the program failed,\n% because of internal system limits on such arrays.\n%\n% Such a problem could be avoided by using a DO loop running through\n% each trial individually, but this tend to run much more slowly than\n% necessary.\n%\n% Since this routine invokes the FORTRAN90 random number generator,\n% the user should initialize the random number generator, particularly\n% if it is desired to control whether the sequence is to be varied\n% or repeated.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 March 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, the horizontal spacing between the\n% vertical grid lines. 0 <= A.\n%\n% Input, real L, the length of the needle.\n%\n% Input, integer TRIAL_NUM, the number of times the needle is\n% to be dropped onto the grid.\n%\n% Output, integer BUFFON_SIMULATE, the number of times the needle\n% crossed at least one line of the grid of cells.\n%\n% Local Parameters:\n%\n% Local, integer BATCH_SIZE, specifies the number of trials to be done\n% in a single batch. Setting BATCH_SIZE to 1 will be very slow.\n% Replacing it by TRIAL_NUM would be fine except that your system\n% may have a limit on the size of automatic arrays. We have set a default\n% value of 10,000 here which should be large enough to be efficient\n% but small enough not to annoy the system.\n%\n batch_size = 10000;\n\n hits = 0;\n\n for batch = 1 : batch_size: trial_num\n\n n = min ( batch_size, trial_num + 1 - batch );\n%\n% Randomly choose the location (X1,Y1) of the eye of the needle\n% in [0,0]x[A,0], and the angle the needle makes.\n%\n x1(1:n) = a * rand ( 1, n );\n angle(1:n) = 2.0D+00 * pi * rand ( 1, n );\n%\n% Compute the location of the point of the needle.\n% We only need to know the value of X2, not Y2!\n%\n x2(1:n) = x1(1:n) + l * cos ( angle(1:n) );\n%\n% Count the end locations that lie outside the cell.\n%\n hits = hits + length ( find ( x2(1:n) <= 0.0 | a <= x2(1:n) ) );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/buffon_simulate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542283, "lm_q2_score": 0.9173026584553408, "lm_q1q2_score": 0.8613699676439628}} {"text": "function trans = createRotationOx(varargin)\n%CREATEROTATIONOX Create the 4x4 matrix of a 3D rotation around x-axis.\n%\n% TRANS = createRotationOx(THETA);\n% Returns the transform matrix corresponding to a rotation by the angle\n% THETA (in radians) around the Ox axis. A rotation by an angle of PI/2\n% would transform the vector [0 1 0] into the vector [0 0 1].\n%\n% The returned matrix has the form:\n% [1 0 0 0]\n% [0 cos(THETA) -sin(THETA) 0]\n% [0 sin(THETA) cos(THETA) 0]\n% [0 0 0 1]\n%\n% TRANS = createRotationOx(ORIGIN, THETA);\n% TRANS = createRotationOx(X0, Y0, Z0, THETA);\n% Also specifies origin of rotation. The result is similar as performing\n% translation(-X0, -Y0, -Z0), rotation, and translation(X0, Y0, Z0).\n%\n% See also \n% transforms3d, transformPoint3d, createRotationOy, createRotationOz\n%\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2005-02-18\n% Copyright 2005-2022 INRA - TPV URPOI - BIA IMASTE\n\n% default values\ndx = 0;\ndy = 0;\ndz = 0;\ntheta = 0;\n\n% get input values\nif length(varargin) == 1\n % only one argument -> rotation angle\n theta = varargin{1};\n \nelseif length(varargin) == 2\n % origin point (as array) and angle\n var = varargin{1};\n dx = var(1);\n dy = var(2);\n dz = var(3);\n theta = varargin{2};\n \nelseif length(varargin) == 4\n % origin (x and y) and angle\n dx = varargin{1};\n dy = varargin{2};\n dz = varargin{3};\n theta = varargin{4};\nend\n\n% compute coefs\ncot = cos(theta);\nsit = sin(theta);\n\n% create transformation\ntrans = [...\n 1 0 0 0;...\n 0 cot -sit 0;...\n 0 sit cot 0;...\n 0 0 0 1];\n\n% add the translation part\nt = [1 0 0 dx;0 1 0 dy;0 0 1 dz;0 0 0 1];\ntrans = t * trans / t;\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom3d/createRotationOx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798184, "lm_q2_score": 0.8991213867309121, "lm_q1q2_score": 0.8612794072021281}} {"text": "function y=polyValGen(p,x,direction)\n%%POLYVALGEN Return the value of a scalar polynomial evaluated at the point\n% or points given in x. The polynomial can be specified in the format\n% y=p(1)*x^N+p(2)*x^(N-1)+...+p(N)*x+p(N+1)\n% or in the format\n% y=p(N+1)*x^N+p(N)*x^(N-1)+...+p(2)*x+p(1)\n% as specified by the direction option. This function is similar to\n% polyval, but allows one to choose between the formats without\n% calling flip to reverse the order of the elements in p.\n%\n%INPUTS: p An NX1 or 1XN set of real or complex polynomial coefficients;\n% wN>=1.\n% x A real or complex scalar point or a matrix of points at which\n% the scalar polynomial should be evaluated.\n% direction An optional parameter specifying which of the two polynomial\n% formats is used. Possible values are:\n% 0 (The default if omitted or an empty matrix is passed) p(1) is\n% the coefficient of the highest order x term.\n% 1 p(1) is the coefficient of the lowest order x term.\n%\n%OUTPUTS: y The value or values of the polynomial in p evaluated at the\n% point(s) in x. This is the same size as x, unless x is an empty\n% matrix, in which case y is 0.\n%\n%The function is evaluated using Horner's rule, which is described in [1].\n%\n%REFERENCES:\n%[1] Weisstein, Eric W. \"Horner's Rule.\" From MathWorld--A Wolfram Web\n% Resource. http://mathworld.wolfram.com/HornersRule.html\n%\n%July 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(direction))\n direction=0; \nend\n\nnumP=length(p);\n\ny=zeros(size(x));\nif(direction==0)\n if(numP>0)\n y(:)=p(1);\n end\n \n for k=2:numP\n y=x.*y+p(k);\n end\nelse\n if(numP>0)\n y(:)=p(numP);\n end\n \n for k=(numP-1):-1:1\n y=x.*y+p(k);\n end\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Polynomials/polyValGen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620468, "lm_q2_score": 0.942506716354847, "lm_q1q2_score": 0.8611462532469284}} {"text": "function [ p ] = ml_explained_variance( L, Var )\n%EXPLAINED_VARIANCE Function that returns the optimal p given a desired\n% explained variance. The student should convert the Eigenvalue matrix \n% to a vector and visualize the values as a 2D plot.\n% input -----------------------------------------------------------------\n% \n% o L : (N x N), Diagonal Matrix composed of lambda_i \n% \n% output ----------------------------------------------------------------\n%\n% o p : optimal principal components wrt. explained variance\n\n\n% ====================== Implement Eq. 8 Here ====================== \neigs = diag(L);\nexpl_var = eigs./sum(eigs);\n\n% ====================== Implement Eq. 9 Here ====================== \ncum_expl_var = cumsum(expl_var); \n\n% ====================== Implement Eq. 10 Here ====================== \np = sum(cum_expl_var <= Var) + 1;\n\n% Visualize Explained Variance from Eigenvalues\nfigure;\nplot(cum_expl_var, '--r', 'LineWidth', 2) ; hold on;\nplot(p,cum_expl_var(p),'or')\ntitle('Explained Variance from EigenValues')\nset(gca,'XTick',[1:1:length(eigs)])\nylabel('% Cumulative Variance Explained')\nxlabel('Eigenvector index')\ngrid on\n\nend\n\n", "meta": {"author": "epfl-lasa", "repo": "ML_toolbox", "sha": "61cc1245a2abe0c86a737d7b48bd645b28ffebee", "save_path": "github-repos/MATLAB/epfl-lasa-ML_toolbox", "path": "github-repos/MATLAB/epfl-lasa-ML_toolbox/ML_toolbox-61cc1245a2abe0c86a737d7b48bd645b28ffebee/methods/projection/ml_explained_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739076, "lm_q2_score": 0.9032941969413321, "lm_q1q2_score": 0.8610878129620589}} {"text": "function [Zpca, U, mu, eigVecs] = PCA(Z,r)\n%\n% Syntax: Zpca = PCA(Z,r);\n% [Zpca, U, mu] = PCA(Z,r);\n% [Zpca, U, mu, eigVecs] = PCA(Z,r);\n% \n% Inputs: Z is an d x n matrix containing n samples of d-dimensional\n% data\n% \n% r is the number of principal components to compute\n% \n% Outputs: Zpca is an r x n matrix containing the r principal\n% components - scaled to variance 1 - of the input samples\n% \n% U is a d x r matrix of coefficients such that\n% Zr = U * Zpca + repmat(mu,1,n);\n% is the r-dimensional PCA approximation of Z\n% \n% mu is the d x 1 sample mean of Z\n% \n% eigVecs is a d x r matrix containing the scaled\n% eigenvectors of the sample covariance of Z\n% \n% Description: Performs principal component analysis (PCA) on the input\n% data\n% \n% Author: Brian Moore\n% brimoor@umich.edu\n% \n% Date: April 26, 2015\n% November 7, 2016\n%\n\n% Center data\n[Zc, mu] = centerRows(Z);\n\n% Compute truncated SVD\n%[U, S, V] = svds(Zc,r); % Equivalent, but usually slower than svd()\n[U, S, V] = svd(Zc,'econ');\nU = U(:,1:r);\nS = S(1:r,1:r);\nV = V(:,1:r);\n\n% Compute principal components\nZpca = S * V';\n%Zpca = U' * Zc; % Equivalent but slower\n\nif nargout >= 4\n % Scaled eigenvectors\n eigVecs = bsxfun(@times,U,diag(S)' / sqrt(size(Z,2)));\nend\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/ref functions/pca_ica/PCA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109713976399, "lm_q2_score": 0.9059898165759307, "lm_q1q2_score": 0.8610626616482998}} {"text": "%% Systems of linear equations\n% At its heart, the subject of linear algebra is concerned with how to\n% solve the seemingly simple equation:\n%\n% $${\\bf{A}}x=b$,\n% where $${\\bf{A}}$ is a matrix and $$x$ and $$b$ are vectors.\n%%\n%\n% This might seem surprising, but this problem is right at the heart of\n% almost all problems in scientific computing, from differential equations\n% to eigenvalue problems to interpolation and curve fitting. \n\n%%\n% Of course, for a single scalar variable, x, we know what that means:\n% $$ a\\times x = y$\n% from which we can deduce that \n% $$ x = y/a$, for non-zero $$a$.\n%%\n% The question is how do we solve such a problem when we have more than one\n% unknown variable, or, equivalently, when x is a vector? To investigate this\n% question, let's consider the following electrical circuit:\n%\n[c,m]=imread('circuit2.gif','gif');\n\nfigure('color',[1 1 1]),\nimage(c), colormap(m), axis equal, axis off\n\n%%\n% We want to calculate the currents $$I_1,I_2,I_3$ \n%%\n% Using Kirchoff's voltage laws we get the following three equations for\n% the three unknown currents:\n%%\n% \n% $\\left\\{\\begin{array}{ccc}\n% I_1 + 25(I_1-I_2)+50(I_1-I_3) & = & 10 \\\\\n% 25(I_2-I_1) + 30I_2 + I_2 -I_3 & = & 0 \\\\\n% 50(I_3-I_1)+I_3-I_2+55I_3 & = & 0 \\end{array}\\right . $\n% \n%%\n% which, with a little re-arranging becomes:\n%%\n% \n% $\\left\\{\\begin{array}{ccc}\n% 76I_1 - 25I_2-50I_3 & = & 10 \\\\\n% -25I_1 +56I_2 -I_3 & = & 0 \\\\\n% -50I_1-I_2+106I_3 & = & 0 \\end{array}\\right .$\n% \n%%\n% Finally, we can gather all the coefficients into a matrix, and the\n% unknowns into a vector, to write the single matrix linear equation:\n%%\n% \n% $\\left( {\\begin{array}{ccc}\n% 76 & -25 & -50 \\\\\n% -25 & 56 & -1 \\\\\n% -50& -1 & 106 \\end{array}} \\right)\n% \\times \\left(\\begin{array}{c}\n% I_1\\\\\n% I_2\\\\\n% I_3 \\end{array}\\right) = \\left( \\begin{array}{c}\n% 10 \\\\\n% 0\\\\\n% 0 \\end{array}\\right)$\n% \n%%\n% In this way we have got the system of equations into the form that we\n% described above, namely:\n% $${\\bf{A}}x=b$\n%%\n% Of course, for a small system (3 by 3 in this case) we can solve this by\n% hand. For a larger system, however, we need a computer. The basic\n% approach to solving such a system is an extension of that used by hand,\n% namely we add and subtract multiples of one row to one another until we\n% finally end up with an upper triangular matrix. This action\n% of adding and subtrating multiples of one row to another is known as a\n% basic row operation. Let us illustrate the process with MATLAB. Before we\n% begin, we augment the right hand side vector to be an extra column in our\n% matrix $$\\bf A$, so it is now three rows by four columns.\nA=[76 -25 -50 10;-25 56 -1 0; -50 -1 106 0]\nrrefexample(A)\n%%\n% What is the advantage of reducing $${\\bf A}$ to be upper triangular?\n% Starting from the last row, we see that we now have an equation that\n% depends only on $$I_3$, that is $$I_3 = 0.117$. The row above depends on\n% $$I_3$ and $$I_2$ only, and we now know what $$I_3$ is! In this way, we\n% work our way up through the rows substituting as we go, and in each row\n% there is only a single unknown variable. This process is called _back\n% substitution_. This entire process - that of reducing the matrix to a\n% triangular form and solving via back substitution - is the way most\n% computer packages solve these linear systems. In MATLAB, the shorthand\n% way of solving such systems is with the backslash character ``\\''\nA=[76 -25 -50;-25 56 -1; -50 -1 106]\nb =[10;0;0]\nI= A\\b\n%%\n% In the example above, we have performed a special case of what is a more \n% general idea - that of transforming a matrix into a special form, so that \n% the equations can be solved more easily. In general, the idea of\n% transforming a matrix through a series of elementary row operations is a\n% powerful one. May special types of _matrix factorisations_ exist, and two\n% of the most important examples are:\n%%\n% *QR decomposition *\n% In this case, a general matrix is written as the product of two matrices,\n% one orthogonal and one upper triangular:\n% $${\\bf A = QR}$\n% As the inverse of an orthogonal matrix is equal to its transpose, we find\n% the solution to the general system $${\\bf A}x=b$ can be calculated as:\n%%\n% \n% $\\begin{array}{l}\n% {\\bf A}x = b \\\\\n% {\\bf QR}x = b \\\\\n% {\\bf Q}({\\bf R}x)=b \\\\\n% {\\bf R}x = {\\bf Q^T} \\times b \\\\\n% x = {\\bf R}\\setminus{\\bf Q^T} \\times b \\end{array}$\n% \n%%\n% *LU Decomposition*\n% In this case the matrix is decomposed into two, a lower and an upper\n% triangular matrix. As both the matrices are triangular, the back (and\n% forward) substitution process is very quick:\n%%\n% \n% $\\begin{array}{l}\n% {\\bf A}x = b \\\\\n% {\\bf LU}x = b \\\\\n% {\\bf U}({\\bf L}x)=b \\\\\n% {\\bf U}x = {\\bf L}\\setminus b \\\\\n% x = {\\bf U}\\setminus({\\bf L}\\setminus b) \\end{array}$\n% \n\n% Copyright 2008-2009 The MathWorks, Inc.\n% $Revision: 35 $ $Date: 2009-05-29 15:27:34 +0100 (Fri, 29 May 2009) $\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23039-matlab-in-physics-matrices/Lecture3/systemEq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582426, "lm_q2_score": 0.9263037338542555, "lm_q1q2_score": 0.8609441146362898}} {"text": "function val=intCotPow(u,n)\n%%INTCOTPOWER Evaluate the integral of cot(u)^n du. A definite integral\n% can be evaluated, or an indefinite integral (with a\n% particular additive constant).\n%\n%INPUTS: u A 2XN (for definite integral) or a 1XN (for indefinite\n% integrals) set of N points. For definite integrals, u(1,:) are\n% the real lower bounds and u(2,:) are the real upper bounds. For\n% indefinite integrals, the integral is evaluated at the points in\n% u. The values in u should be real.\n% n The positive integer exponent of the cotangent term.\n%\n%OUTPUTS: val The 1XN set of values of the integral of cot(u)^n.\n%\n%This function simply implements the recursion that arises from integration\n%by parts from basic calculus, as are given in the tables in the back of\n%[1].\n%\n%REFERENCES:\n%[1] J. Stewart, Calculus, 7th ed. Belmont, CA: Brooks/Cole, 2012.\n%\n%October 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumDim=size(u,1);\n\nif(isempty(u))\n val=[];\n return;\nend\n\nif(numDim==1)%An indefinite integral\n val=indefIntCotPow(u,n);\nelse%A definite integral\n val=indefIntCotPow(u(2,:),n)-indefIntCotPow(u(1,:),n);\nend\n\nend\n\nfunction val=indefIntCotPow(u,n)\n\nif(n==0)\n val=u;\n return;\nelseif(n==1)\n val=log(abs(sin(u)));\n return;\nend\n\n%If here, n>=1\ncotVal=cot(u);\n\nval=0;\nif(mod(n,2)==0)%If n is even\n endVal=2;\nelse\n endVal=3;\nend\n\ncoeffProd=1;\nfor k=n:-2:endVal\n val=val-coeffProd*(1/(k-1))*cotVal.^(k-1);\n coeffProd=-coeffProd;\nend\n\nif(endVal==2)\n %The final integral is over cot^0\n val=val+coeffProd*u;\nelse\n %The final integral is over cot^1\n val=val+coeffProd*log(abs(sin(u)));\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Specific_Integrals/intCotPow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416412, "lm_q2_score": 0.9184802390045689, "lm_q1q2_score": 0.8608095868530345}} {"text": "%% Homework 10\n% We Wish to solve the following partial differential equation:\n%\n% $\\frac{\\partial T}{\\partial t}+u \\frac{\\partial T}{\\partial x}=\\alpha \\frac{\\partial^2 T}{\\partial x^2}$\n%\n%% Part 2: Convection and Diffusion (Assume $\\alpha=0.001$)\n% Now using the same initial boundary conditions in Part 1, Solve the\n% convection-diffusion equation. Repeat part(a): i and ii with the\n% addition of the second-order central difference for the diffusion term.\n%\n% Following the condition: $cfl < 1$\n% where $cfl = u \\frac{\\Delta t}{\\Delta x}$\n%\n% And now define $\\alpha*\\frac{\\Delta t}{(\\Delta x)^2}$ in the range [0,1]\n\nclc\nclear all\nclose all\n\n% Initial Parameters\ncfl = 0.7;\nu = 0.08;\ndx = 1/50; % at least 51 grid points\ndt = cfl*dx/u;\nalpha = 0.001;\nbeta = alpha*dt/dx^2;\nt_end = 8;\n\n% Grid\nx = 0:dx:1;\nt = 0:dt:t_end;\nX = length(x);\nN = length(t);\nT = zeros(N,X);\n\n% Initial Condition\nT(1,1:12) = 1.-(10.*x(1:12)-1).^2;\nT(1,12:51) = 0;\n\n% Plot options\nxmin=1; xmax=51; ymin=-0.2; ymax=1.7;\n\n%% Barckward Euler time advancement\n% a) Using Explicit Euler time advancement and second-order central\n% difference for the spatial derivate.\n\n% Numerical Scheme:\nT(:,1) = 0; T(:,X) = 0;\nfor n = 1:N-1\n for j = 2:X-1\n T(n+1,j) = T(n,j) - 1/2*cfl*(T(n,j+1) - T(n,j-1))...\n + beta*(T(n,j+1) - 2*T(n,j) + T(n,j-1));\n end\nend\n\n% Plot Figures:\nfigure\nAxis([xmin xmax ymin ymax])\nTitle(['Backward Euler Scheme',', CFL = ',num2str(cfl),', Beta = ',num2str(beta)])\nhold on\nplot(T(1,:),'ro')\nplot(T(floor(N/2),:),'b+')\nplot(T(N,:),'gs')\nlegend('@ t = 0','@ t = 4','@ t = 8')\nhold off\n\n%% Leapfrog time advancement\n% b) Using Leapfrog time advancement and second-order central\n% difference for the spatial derivate and a central difference for the\n% diffusion term.\n%\n% This is a multistep method that is we need to use the first two lines on\n% the forward euler to start our new scheme.\n\nT2 = zeros(N,X);\nT2(1,:) = T(1,:);\nT2(2,:) = T(2,:);\nT2(1,1) = 0; T2(1,X) = 0;\n\n% Numerical Scheme:\nT2(:,1) = 0; T2(:,X) = 0;\nfor n = 2:N-1\n for j = 2:X-1\n T2(n+1,j) = T2(n-1,j) - cfl*(T2(n,j+1) - T2(n,j-1))...\n + 2*beta*(T2(n,j+1) - 2*T2(n,j) + T2(n,j-1));\n end\nend\n\n% Plot Figures:\nfigure\n%Axis([xmin xmax ymin ymax])\nTitle(['Leapfrog Scheme',', CFL = ',num2str(cfl),', Beta = ',num2str(beta)])\nhold on\nplot(T2(1,:),'-.ro')\nplot(T2(floor(N/2),:),'-.b+')\nplot(T2(N,:),'-.gs')\nlegend('@ t = 0','@ t = 4','@ t = 8')\nhold off\n\n%% Leapfrog time advancement with the diffusion term lagged in time.\n% c) Using Leapfrog time advancement and second-order central\n% difference for the spatial derivate and a central difference for the\n% diffusion term. But this time the diffusion term would be evaluated at\n% step \"n-1\" rather than \"n\".\n%\n% This is a multistep method that is we need to use the first two lines on\n% the forward euler to start our new scheme.\n\nT3 = zeros(N,X);\nT3(1,:) = T(1,:);\nT3(2,:) = T(2,:);\nT3(1,1) = 0; T3(1,X) = 0;\n\n% Numerical Scheme:\nT3(:,1) = 0; T3(:,X) = 0;\nfor n = 2:N-1\n for j = 2:X-1\n T3(n+1,j) = T3(n-1,j) - cfl*(T3(n,j+1) - T3(n,j-1))...\n + 2*beta*(T3(n-1,j+1) - 2*T3(n-1,j) + T3(n-1,j-1));\n end\nend\n\n% Plot Figures:\nfigure\nAxis([xmin xmax ymin ymax])\nTitle(['Leapfrog with diff-term lagged Scheme',', CFL = ',num2str(cfl),', Beta = ',num2str(beta)])\nhold on\nplot(T3(1,:),'ro')\nplot(T3(floor(N/2),:),'b+')\nplot(T3(N,:),'gs')\nlegend('@ t = 0','@ t = 4','@ t = 8')\nhold off\n\n%% Discusion\n% How the presence of the diffusion term affected the physical behavior of\n% the solution and stability properties of the numerical solution?\n\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/NumericalMethods/CFL2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.9099070121457543, "lm_q1q2_score": 0.8605912120004491}} {"text": "function [J, grad] = costFunction(theta, X, y)\n%COSTFUNCTION Compute cost and gradient for logistic regression\n% J = COSTFUNCTION(theta, X, y) computes the cost of using theta as the\n% parameter for logistic regression and the gradient of the cost\n% w.r.t. to the parameters.\n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost of a particular choice of theta.\n% You should set J to the cost.\n% Compute the partial derivatives and set grad to the partial\n% derivatives of the cost w.r.t. each parameter in theta\n%\n% Note: grad should have the same dimensions as theta\n%\n\nH_theta = sigmoid(X * theta);\n\nJ = -1/m * sum(y .* log(H_theta) + (1 - y) .* log(1 - H_theta));\n\ngrad = 1/m .* X' * (H_theta - y);\n\n% =============================================================\n\nend\n", "meta": {"author": "rmarquis", "repo": "coursera-machinelearning", "sha": "5b165935e6fecfab977b2af1b0e9c588c75ca8f4", "save_path": "github-repos/MATLAB/rmarquis-coursera-machinelearning", "path": "github-repos/MATLAB/rmarquis-coursera-machinelearning/coursera-machinelearning-5b165935e6fecfab977b2af1b0e9c588c75ca8f4/homework/mlclass-ex2/costFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.8976952921073469, "lm_q1q2_score": 0.8604748050942435}} {"text": "\nfunction level=isodata(I)\n% ISODATA Compute global image threshold using iterative isodata method.\n% LEVEL = ISODATA(I) computes a global threshold (LEVEL) that can be\n% used to convert an intensity image to a binary image with IM2BW. LEVEL\n% is a normalized intensity value that lies in the range [0, 1].\n% This iterative technique for choosing a threshold was developed by Ridler and Calvard .\n% The histogram is initially segmented into two parts using a starting threshold value such as 0 = 2B-1, \n% half the maximum dynamic range. \n% The sample mean (mf,0) of the gray values associated with the foreground pixels and the sample mean (mb,0) \n% of the gray values associated with the background pixels are computed. A new threshold value 1 is now computed \n% as the average of these two sample means. The process is repeated, based upon the new threshold, \n% until the threshold value does not change any more. \n \n%\n% Class Support\n% -------------\n% The input image I can be of class uint8, uint16, or double and it\n% must be nonsparse. LEVEL is a double scalar.\n%\n% Example\n% -------\n% I = imread('blood1.tif');\n% level = graythresh(I);\n% BW = im2bw(I,level);\n% imshow(BW)\n%\n% See also IM2BW.\n%\n% Reference :T.W. Ridler, S. Calvard, Picture thresholding using an iterative selection method, \n% IEEE Trans. System, Man and Cybernetics, SMC-8 (1978) 630-632.\n\n% Convert all N-D arrays into a single column. Convert to uint8 for\n% fastest histogram computation.\nI = im2uint8(I(:));\n\n% STEP 1: Compute mean intensity of image from histogram, set T=mean(I)\n[counts,N]=imhist(I);\ni=1;\nmu=cumsum(counts);\nT(i)=(sum(N.*counts))/mu(end);\nT(i)=round(T(i));\n\n% STEP 2: compute Mean above T (MAT) and Mean below T (MBT) using T from\n% step 1\nmu2=cumsum(counts(1:T(i)));\nMBT=sum(N(1:T(i)).*counts(1:T(i)))/mu2(end);\n\nmu3=cumsum(counts(T(i):end));\nMAT=sum(N(T(i):end).*counts(T(i):end))/mu3(end);\ni=i+1;\n% new T = (MAT+MBT)/2\nT(i)=round((MAT+MBT)/2);\n\n% STEP 3 to n: repeat step 2 if T(i)~=T(i-1)\nwhile abs(T(i)-T(i-1))>=1\n mu2=cumsum(counts(1:T(i)));\n MBT=sum(N(1:T(i)).*counts(1:T(i)))/mu2(end);\n \n mu3=cumsum(counts(T(i):end));\n MAT=sum(N(T(i):end).*counts(T(i):end))/mu3(end);\n \n i=i+1;\n T(i)=round((MAT+MBT)/2); \n Threshold=T(i);\nend\n\n % Normalize the threshold to the range [i, 1].\nlevel = (Threshold - 1) / (N(end) - 1);\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/3195-automatic-thresholding/isodata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693688269985, "lm_q2_score": 0.9059898146721821, "lm_q1q2_score": 0.8603907754634205}} {"text": "function [W, S, latent] = PCA(X, pcaDims)\n%% [W, S, latent] = PCA(X, pcaDims)\n% \n% Function for learning a Principle Component Analysis (PCA) subspace.\n% \n% Inputs:\n% X: training data, with rows corresponding to samples and columns features.\n% pcaDims: optional parameter specifying the output PCA subspace\n% dimensions.\n% \n% Outputs:\n% W: the learned PCA subspace projection matrix.\n% S: projected coefficients of X by W.\n% latent: latent values of the covariant matrix\n% \n% Version: 1.0\n% Date: 2014-07-22\n%\n% Author: Shengcai Liao\n% Institute: National Laboratory of Pattern Recognition,\n% Institute of Automation, Chinese Academy of Sciences\n% Email: scliao@nlpr.ia.ac.cn\n\n[n, d] = size(X);\n\nif nargin == 1\n pcaDims = min(d,n) - 1;\nend\n\nif pcaDims <= 0 || pcaDims >= min(d,n)\n error('Incorrect pcaDims.');\nend\n\nfprintf('Start to train PCA...');\nt0 = tic;\n\nmu = mean(X);\nX = bsxfun(@minus, X, mu);\n\nif n >= d\n C = X' * X; %[d,d]\nelse\n C = X * X'; %[n,n]\nend\n\n[W, D] = eig(C);\nlatent = diag(D);\n[latent, index] = sort(latent, 'descend');\nW = W(:, index);\n\nW = W(:, 1:pcaDims);\nlatent = latent(1:pcaDims);\n\nif n < d\n W = X' * W * diag(1 ./ sqrt(latent));\nend\n\nif nargout >= 2 && ~isempty(S)\n S = X * W;\nend\n\nfprintf('%.3g seconds.\\n', toc(t0));\n", "meta": {"author": "happynear", "repo": "FaceVerification", "sha": "c8c2b4d805abf7240d9d39d7b57151e04958f6bf", "save_path": "github-repos/MATLAB/happynear-FaceVerification", "path": "github-repos/MATLAB/happynear-FaceVerification/FaceVerification-c8c2b4d805abf7240d9d39d7b57151e04958f6bf/BLUFR/PCA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273499, "lm_q2_score": 0.900529776774399, "lm_q1q2_score": 0.8602933226416836}} {"text": "function [xi,w]=thirdOrderExpCubPoints(numDim,algorithm)\n%%THIRDORDEREXPCUBPOINTS Generate third-order cubature points for\n% integration over real space involving the weighting\n% function w(x)=exp(-sqrt(sum(x.*x))).\n%\n%INPUTS: numDim An integer specifying the dimensionality of the points to\n% be generated.\n% algorithm A value indicating which algorithm should be used. Possible\n% values are:\n% 0 (The default if omitted or an empty matrix is passed)\n% Formula E_n^r 3-1 in [1], pg. 329, 2*numDim points.\n% 1 Formula E_n^r 3-2 in [1], pg. 329, 2^numDim points.\n%\n%OUTPUTS: xi A numDim X numCubaturePoints matrix containing the cubature\n% points. (Each \"point\" is a vector)\n% w A numCubaturePoints X 1 vector of the weights associated with\n% the cubature points.\n%\n%REFERENCES:\n%[1] A.H. Stroud, Approximate Calculation of Multiple Integrals. Cliffs,\n% NJ: Prentice-Hall, Inc., 1971.\n%\n%October 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release\n\nif(nargin<2||isempty(algorithm))\n algorithm=0; \nend\n\nswitch(algorithm)\n case 0%E_n^r 3-1 in [1], pg. 329, 2*numDim points.\n V=2*pi^(numDim/2)*exp(gammaln(numDim)-gammaln(numDim/2));\n r=sqrt(numDim*(numDim+1));\n \n w=V/(2*numDim)*ones(2*numDim,1);\n xi=fullSymPerms([r;zeros(numDim-1,1)]);\n case 1%E_n^r 3-2 in [1], pg. 329, 2^numDim points.\n V=2*pi^(numDim/2)*exp(gammaln(numDim)-gammaln(numDim/2));\n r=sqrt(numDim+1);\n \n xi=PMCombos(r*ones(numDim,1));\n w=2^(-numDim)*V*ones(2^numDim,1);\n otherwise\n error('Unknown algorithm specified'); \nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Numerical_Integration/Cubature_Points/Exp_Weight/thirdOrderExpCubPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697695, "lm_q2_score": 0.9124361640485893, "lm_q1q2_score": 0.859977214334362}} {"text": "%% Laplace Operator\n%\n% In this demo, we show how to use the OpenCV function |cv.Laplacian| to\n% implement a discrete analog of the _Laplacian operator_.\n%\n% Sources:\n%\n% * \n% * \n%\n\n%% Theory\n%\n% In a previous demo, we learned how to use the _Sobel Operator_. It was based\n% on the fact that in the edge area, the pixel intensity shows a \"jump\" or a\n% high variation of intensity. Getting the first derivative of the intensity,\n% we observed that an edge is characterized by a maximum, as it can be seen in\n% the figure:\n%\n% <>\n%\n% And what happens if we take the second derivative?\n%\n% <>\n%\n% You can observe that the second derivative is zero! So, we can also use this\n% criterion to attempt to detect edges in an image. However, note that zeros\n% will not only appear in edges (they can actually appear in other meaningless\n% locations); this can be solved by applying filtering where needed.\n%\n%% Laplacian Operator\n%\n% From the explanation above, we deduce that the second derivative can be used\n% to _detect edges_. Since images are \"2D\", we would need to take the\n% derivative in both dimensions. Here, the Laplacian operator comes handy.\n%\n% The _Laplacian operator_ is defined by:\n%\n% $$Laplace(f) = \\frac{\\partial^{2} f}{\\partial x^{2}} +\n% \\frac{\\partial^{2} f}{\\partial y^{2}}$$\n%\n% The Laplacian operator is implemented in OpenCV by the function\n% |cv.Laplacian|. In fact, since the Laplacian uses the gradient of images, it\n% calls internally the _Sobel_ operator to perform its computation.\n%\n\n%% Code\n%\n% The program:\n%\n% * Loads an image\n% * Remove noise by applying a Gaussian blur and then convert the original\n% image to grayscale\n% * Applies a Laplacian operator to the grayscale image and stores the output\n% image\n% * Display the result in a window\n%\n\n%%\n% load source image\nsrc = cv.imread(fullfile(mexopencv.root(),'test','butterfly.jpg'), 'Color',true);\n\n%%\n% apply a Gaussian blur to reduce the noise\nsrc = cv.GaussianBlur(src, 'KSize',[3 3]);\n\n%%\n% convert filtered image to grayscale\ngray = cv.cvtColor(src, 'RGB2GRAY');\n\n%%\n% apply the Laplacian operator to the grayscale image\n% (input is 8-bit, we set the output image depth to 16-bit to avoid overflow)\ndst = cv.Laplacian(gray, 'KSize',3, 'DDepth','int16');\n\n%%\n% take absolute value and convert results back to 8-bit\ndstabs = cv.convertScaleAbs(dst);\n\n%%\n% show result\nimshow(dstabs)\ntitle('Laplace Demo')\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/samples/laplace_operator_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766225, "lm_q2_score": 0.9149009584734676, "lm_q1q2_score": 0.8599276200181347}} {"text": "function [x,f,exitCode]=convexQuadProg(G,a,C,b,numEqConst,epsVal,maxIter)\n%%CONVEXQUADPROG Perform quadratic programming on a convex problem with\n% equality and inequality constraints. Specifically, this\n% algorithm solves the optimization problem: \n% minimize_x a'*x+(1/2)*x'*G*x\n% such that C(:,1:numEqConst)'*x=b(1:numEqConst)\n% and C(:,(numEqConst+1):end)'*x>=b((numEqConst+1):end)\n% A dual active set algorithm for strictly convex problems\n% is used. Strict convexity means that G is positive\n% definite. The algorithm is robust to poorly conditioned\n% matrices. Thus, to handle the semidefinite case,\n% eigenvalue thresholding is applied prior to running the\n% algorithm.\n%\n%INPUTS: G An nXn real, positive (semi)definite symmetric matrix (n>0).\n% a An nX1 real vector.\n% C An nXm real matrix (m>=0). The first numEqConst constraints (the\n% equality constraints) must be linearly independent or the\n% algorithm will identify the problem as infeasible.\n% b An mX1 vector.\n% numEqConst The number of constraints in C that are equality constraints\n% (numEqConst<=m). If this parameter is omitted or an empty matrix\n% is passed, the default numEqConst=0 is used.\n% epsVal A small value that is used to determine whether there is no step\n% in the primal space such that a constraint becomes feasible,\n% meaning that a step must be taken in the dual space and a\n% constraint dropped. This value should be >0 due to finite\n% precision errors. If this parameter is omitted or an empty\n% matrix is passed, the default value of eps() is used.\n% maxIter The maximum number of iterations to allow. The default value if\n% this parameter is omitted or an empty matrix is passed is 200.\n%\n%OUTPUTS: x The nX1 solution to the optimization problem or an empty matrix\n% if the problem is infeasible.\n% f The value of the objective function at x, or an empty ,matrix\n% if the problem is infeasible.\n% exitCode A value indicating how the algorithm terminated. Possible\n% values are:\n% 0 The algorithm found the optimal value x.\n% 1 The maximum number of iterations elapsed.\n% -1 The optimization problem is infeasible.\n% \n%The algorithm of [1] is implemented. However, the algorithmic description\n%in [1] omits a few minor details regarding deleting elements from uPlus\n%and updating s removing a constraint. The changes are commented in the\n%code. Also, the algorithm of [1] is only described for inequality\n%constraints. The change to allow equality constraints is performed by\n%forcing the first numEqConst columns of C to be chosen to be added to the\n%active set and then making sure that they are never removed from the\n%active set. If an attempt is made to remove them from the active set, then\n%the corresponding dual variables are set to zero rather than removed.\n%\n%Another change from the algorithm of [1] deals with the qr formulation of\n%certain terms. Though the qr formulation of the H and NStar matrices is\n%used, the single column deletions and insertions are not performed. Though\n%slower than the algorithm in the paper, one does not need to worry about\n%cumulative finite precision errors due to many incremental updates.\n%\n%Also, algorithm [1] did not include an epsVal term to try to deal with\n%finite precision effects limiting the ability to determine whether no\n%primal step can activate a certain constraint.\n%\n%EXAMPLE 1:\n%This is the example worked out step-by-step in [1]:\n% G=[4, -2;-2, 4];\n% b=[0;0;2];\n% a=[6;0];\n% C=[1,0,1;\n% 0,1,1]; \n% [x,f,exitCode]=convexQuadProg(G,a,C,b)\n%The optimal solution can be seen to be x=[0.5;1.5] and f=6.5;\n%\n%EXAMPLE 2:\n%In [1], the algorithm was tested on many random problems. Below is an\n%implementation of the method described in the paper for n=81 dimensions\n%and m=3*n=243 constraints. The first qStar=m/3=81 constraints end up being\n%enforced.\n% n=81;\n% m=3*n;\n% qStar=m/3;\n% \n% G=rand(n,n);\n% G=G+G';\n% %G is not symmetric and all elements are in the range of -1 to 1\n% SCur=sum(G(1,2:end));\n% G(1,1)=1+SCur+rand(1);\n% for curRow=2:n\n% SPrev=SCur;\n% SCur=sum(G(curRow,[1:(curRow-1),(curRow+1):end]));\n% G(curRow,curRow)=G(curRow-1,curRow-1)+SCur+SPrev+rand();\n% end\n% \n% xStar=-0.5+rand(n,1);\n% C=-1+2*rand(n,m);\n% C=bsxfun(@times,C,1./sqrt(sum(C.*C,1)));\n% s=zeros(m,1);\n% s((qStar+1):end)=rand(m-qStar,1);\n% b=-(s-C'*xStar);%Sign changed from description in paper to be feasible.\n% u=30*rand(m,1);\n% u((qStar+1):end)=0;\n% a=C*u-G*xStar;\n% [x,f,exitCode]=convexQuadProg(G,a,C,b)\n%\n%EXAMPLE 3:\n%This is an example of a problem having both inequality and equality\n%constraints:\n% G=[4, -2;-2, 4];\n% b=[2;1.6];\n% a=[6;0];\n% C=[1,0;\n% 1,1];\n% numEqConst=1;%One equality constraint.\n% [x,f,exitCode]=convexQuadProg(G,a,C,b,numEqConst)\n%The optimal solution is x=[0.4;1.6] and f=6.56.\n%\n%REFERENCES:\n%[1] D.Goldfarb and A. Idnani, \"A numerically stable dual method for\n% solving strictly convex quadratic programs,\" Mathematical Programming,\n% vol. 27, no. 1, pp. 1-33, Sep. 1983.\n%\n%January 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<5||isempty(numEqConst))\n numEqConst=0; \nend\n\nif(numEqConst>size(C,1))\n error('numEqConst is larger than the number of constraints in C')\nend\n\nif(nargin<6||isempty(epsVal))\n epsVal=eps();\nend\n\nif(nargin<7||isempty(maxIter))\n maxIter=200;\nend\n\n%This portion is to compensate for the possibility that G is positive\n%semidefinite.\n[V,D]=eig(G);\nd=diag(D);\ndNew=max(d,2*max(size(G))*eps(max(d)));\nif(~all(dNew==d))\n %Only change G if some eigenvalues were too small.\n D=diag(dNew);\n G=V*D/V;\n G=(G+G')/2;%Ensure symmetry.\nend\n\n%If there are no constraints, the return the unconstrained solution.\nif(isempty(b))\n x=-G\\a;\n f=(1/2)*a'*x;\n exitCode=0;\n return\nend\n\n%Step 0: Find the unconstrained minimum and initialize parameters.\nH=inv(G);\nx=-G\\a;\nf=(1/2)*a'*x;\n%Values are added to and deleted from A. Though this is inefficient, it is\n%questionable whether any particular data structure could make it notably\n%more efficient than what Matlab does without reprogramming this function\n%in C.\nA=[];\nq=0;\nu=[];\nNStar=[];\nL=chol(G,'lower');\n\nskipStep1=false;\nfor curIter=1:maxIter\n %Step 1: Choose a violated constant, if any. We shall choose the most\n %violated constant.\n if(skipStep1==false)\n s=C'*x-b;\n %Force the equality constraints to be added first.\n if(curIter<=numEqConst)\n p=curIter;\n else\n [~,p]=min(s);\n\n if(any(p==A)||s(p)>=0)\n %If no constraints are violated, the current solution is\n %feasible and optimal.\n exitCode=0;\n return;\n end\n end\n \n uPlus=[u;0];%Dual variables with one for constraint p added.\n nPlus=C(:,p);\n end\n\n %Step 2: Check for feasibility and determine a new S-pair\n %Step 2a) Determine the step direction.\n z=H*nPlus;\n \n %r is empty when no constraints have been added.\n if(q==0)\n r=[];\n else\n r=NStar*nPlus;\n end\n \n %Step 2b) Determine the step length\n %Step 2bi) Find t1, the maximum step without violating dual\n % feasibility.\n t1=Inf;\n l=[];\n for i=1:q\n %The added requirement that uPlus(i)>0 arises due to the equality\n %constraints. Otherwise, all of the dual variables enforced would\n %be greater than zero due to the nature of the dual problem.\n if(r(i)>0&&uPlus(i)>0)\n t1Cur=uPlus(i)/r(i);\n if(t1CurnumEqConst)%Do not delete equality constraints\n %Delete constraint A(l).\n A(l)=[];\n %Delete the dual variables associated with the constraint.\n %This deletion is not mentioned in the steps given in the paper,\n %but is necessary.\n uPlus(l)=[];\n q=q-1;\n\n %x did not change, so s(p) does not need to be recomputed.\n\n [NStar,H]=updateNStarH(q,A,C,L);\n else\n uPlus(l)=0;\n end\n skipStep1=true;\n else\n %Step 2ciii: Take a step in primal and dual space.\n x=x+t*z;\n f=f+t*z'*nPlus*((1/2)*t+uPlus(q+1));\n uPlus=uPlus+t*[-r;1];\n \n if(t==t2)%If a full step is taken, add constraint p\n u=uPlus;\n q=q+1;\n A(q)=p;\n\n [NStar,H]=updateNStarH(q,A,C,L);\n skipStep1=false;\n else%If a partial step is taken, then drop constraint k=A(l)\n if(l>numEqConst)%Do not delete equality constraints\n A(l)=[];\n %Delete the dual variables associated with the constraint.\n %This deletion is not mentioned in the steps given in the\n %paper, but is necessary.\n uPlus(l)=[];\n q=q-1;\n\n [NStar,H]=updateNStarH(q,A,C,L);\n else\n uPlus(l)=0;\n end\n %s must be recomputed for a partial step. This is not mentioned\n %in the paper.\n s=C'*x-b;\n skipStep1=true;\n end\n end\nend\n\n%Maximum number of iterations exceeded.\nexitCode=1;\nend\n\nfunction [NStar,H]=updateNStarH(q,A,C,L)\n%UPDATENSTARH This function is based on the discussion in Section 4 of [1].\n% It uses a qr decomposition, but does not use any of the qr\n% updating methods.\n N=C(:,A);\n\n opts.LT=true;\n opts.UT=false;\n %Solve B=L\\N;\n B=linsolve(L,N,opts);\n [Q,R]=qr(B);\n R=R(1:q,1:q);\n \n opts.LT=false;\n opts.UT=true;\n %Solve J=(L')\\Q;\n J=linsolve(L',Q,opts);\n J1=J(:,1:q);\n J2=J(:,(q+1):end);\n \n H=J2*J2';\n NStar=R\\(J1');\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Continuous_Optimization/Quadratic_Programming/convexQuadProg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951711746926, "lm_q2_score": 0.8947894604912848, "lm_q1q2_score": 0.8598494637122085}} {"text": "function [M,R] = ballatsq(N)\n% BALLATSQ - Balanced Latin Square\n% M = BALLATSQ(N) creates a balanced latin square of size N containing\n% the numbers 1 to N. N should be an even positive integer.\n%\n% [M, R] = BALLATSQ(N) also returns a randomized balanced latin square in R. \n%\n% A latin square of size M is a MxM matrix filled with the M different\n% numbers in such a way that each number occurs exactly once in each row\n% and exactly once in each column. A balanced latin square has the further\n% restriction that each sequence of two values in a row does not occur\n% more than once in the whole matrix. They have applications in the\n% design of experiments.\n% More information: http://en.wikipedia.org/wiki/Latin_square\n%\n% Example:\n% M = ballatsq(6) % ->\n% % 1 2 6 3 5 4\n% % 2 3 1 4 6 5\n% % 3 4 2 5 1 6\n% % 4 5 3 6 2 1\n% % 5 6 4 1 3 2\n% % 6 1 5 2 4 3\n%\n% Note that \"sort(ballatsq(N),1-2)\" will return 1:N in each column-row.\n%\n% See also MAGIC, GALLERY, CIRCSHIFT\n% LATSQ, CIRCULANT (FEX)\n\n% for Matlab R13 and up\n% version 2.2 (mar 2009)\n% (c) Jos van der Geest\n% email: jos@jasen.nl\n\n% History\n% 1.0 (feb 2006) created\n% 2.0 (apr 2006) previous algorithm was faulty. Thanks to Jen M. (UK)\n% 2.1 (sep 2006) can now also return a randomize balanced latin square\n% 2.2 (mar 2009) added internal comments, changed variable names, improved\n% randomization\n\n\nif nargin ~= 1 || ~isnumeric(N) || numel(N)~=1 || N<2 || rem(N,2) || fix(N)~=N,\n error('Single argument should be a positive even integer') ;\nend\n\nV = 1:N ; % values in each column\nCSI = [V ; -V] ; % circular shift index\nM = zeros(N) ; % pre-allocation\n\n% the first colum just contains the numbers 1 to N\nM(:,1) = V(:) ;\nfor i=2:N,\n % every column contains the numbers 1 to N shifted circularly according\n % to CSI \n M(:,i) = rem(V(:)+CSI(i-1)+(N-1),N) + 1 ;\nend\n\nif nargout==2,\n % randomize the values 1:N\n rN = randperm(N) ;\n R = rN(M) ;\nend\n\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9996-ballatsq/ballatsq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.9230391701259804, "lm_q1q2_score": 0.8597763724105806}} {"text": "function f = polyVal2D(p,x,y,n,m)\n%POLYVAL2D Evaluate a 2-D polynomial using Horner's method.\n% F = POLYVAL2D(P,X,Y) evaluates the 2-D polynomial P at the points \n% specified by X and Y, which must have the same dimensions. The output F\n% will have the same dimensions as X and Y. N and M specify the order of X\n% and Y respectively. Polynomial coefficients are in the following order.\n%\n% F(X,Y) = P_1 * X^N * Y^M + P_2 * X^{N-1} * Y^M + ... + P_{N+1} * Y^M + ...\n% P_{N+2} * X^N * Y^{M-1} + P_{N+3} * X^{N-1} * Y^{M-1} + ... + P_{2*(N+1)} * Y^{M-1} + ...\n% ...\n% P_{M*(N+1)+1} * X^N + P_{M*(N+1)+2} * X^{N-1} + ... + P_{(N+1)*(M+1)}\n%\n%\n% See also: POLYFITN by John D'Errico on MathWorks MATLAB Central FEX\n% http://www.mathworks.com/matlabcentral/fileexchange/34765-polyfitn\n%\n% Mark Mikofski, http://poquitopicante.blogspot.com\n% Version 1-0, 2013-03-13\n\n%% LaTex\n%\n% $$f\\left(x,y\\right)=p_1 x^n y^m+p_2 x^{\\left(n-1\\right)} y^m+\\ldots+p_{n+1} y^m+\\ldots$$\n%\n% $$p_{n+2}x^ny^{\\left(m-1\\right)}+p_{n+3}x^{\\left(n-1\\right)}y^{\\left(m-1\\right)}+\\ldots+p_{2\\left(n+1\\right)}y^{\\left(m-1\\right)}+\\ldots$$\n%\n% $$\\ldots$$\n%\n% $$p_{m\\left(n+1\\right)+1}*x^n+p_{m\\left(n+1\\right)+2}*x^{\\left(n-1\\right)}+\\ldots+p_{\\left(n+1\\right)\\left(m+1\\right)}$$\n\n%% check input args\nvalidateattributes(p,{'numeric'},{'2d','nonempty','real','finite'}, ...\n 'polyVal2D','p',1)\nvalidateattributes(x,{'numeric'},{'nonempty','real','finite'}, ...\n 'polyVal2D','x',2)\nvalidateattributes(y,{'numeric'},{'nonempty','real','finite'}, ...\n 'polyVal2D','y',3)\nassert(all(size(x)==size(y)),'polyVal2D:sizeMismatch', ...\n 'X and Y must be the same size.')\n% use size of p to set n & m\npdims = size(p);\nif nargin<4 && all(pdims>1)\n n = pdims(1)-1;\n m = pdims(2)-1;\nend\nvalidateattributes(n,{'numeric'},{'scalar','integer','positive','<',10}, ...\n 'polyVal2D','n',4)\nvalidateattributes(m,{'numeric'},{'scalar','integer','positive','<',10}, ...\n 'polyVal2D','m',5)\nif all(pdims>1) \n assert(pdims(1)==n+1,'polyVal2D:xOrderMismatch', ...\n 'The number of x coefficients doesn''t match the order n.')\n assert(pdims(2)==m+1,'polyVal2D:yOrderMismatch', ...\n 'The number of y coefficients doesn''t match the order m.')\nend\n%% evaluate polynomial P\nf = p(1);\nfor ni = 1:n\n f = f.*x+p(1+ni);\nend\nfor mi = 1:m\n mj = (n+1)*mi+1;\n g = p(mj);\n for ni = 1:n\n g = g.*x+p(mj+ni);\n end\n f = f.*y+g;\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/41097-polyval2d-and-polyfit2d/polyVal2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.9059898114992677, "lm_q1q2_score": 0.8597093761991048}} {"text": "function [VG,A,PPG]= colorgrad(f,T)\n%COLORGRAD Computes the vector gradient of an RGB image.\n% [VG,VA,PPG] = COLORGRAD(F,T) computes the vector gradient, VG, and\n% corresponding angle array, VA, (in radians) of RGB image F. It also\n% computes PPG, the per-plane composite gradient obtained by summing\n% the 2-D gradients of the individual color planes. Input T is a\n% threshold in the range [0,1]. If it is included in the input,\n% outputs VG and PPG are logical matrices such that VG(x,y) = 0 for\n% values <= T and VG(x,y) = 1 otherwise. Similar comments apply to\n% PPG. If T is not included in the input argument, then both output\n% gradients are scaled to the double range [0,1].\n%\n% All equations on which this function is based are from Chapter 7 of\n% DIPUM3E.\n%\n% Copyright 2002-2020 Gatesmark\n%\n% This function, and other functions in the DIPUM Toolbox, are based \n% on the theoretical and practical foundations established in the \n% book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark \n% Press, 2020.\n%\n% Book website: http://www.imageprocessingplace.com\n% License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt\n\nif size(f,3) ~= 3\n error('Input image must be of size M-by-N-by-3');\nend\n\nif nargin == 2 && (T < 0 || T > 1)\n error('T must be in the range [0 1]')\nend\n\n% Compute the x and y derivatives of the three component images using\n% Sobel operators.\nsh = fspecial('sobel');\nsv = sh';\nRx = imfilter(double(f(:,:,1)),sh,'replicate');\nRy = imfilter(double(f(:,:,1)),sv,'replicate');\nGx = imfilter(double(f(:,:,2)),sh,'replicate');\nGy = imfilter(double(f(:,:,2)),sv,'replicate');\nBx = imfilter(double(f(:,:,3)),sh,'replicate');\nBy = imfilter(double(f(:,:,3)),sv,'replicate');\n\n% Compute the parameters of the vector gradient. \ngxx = Rx.^2 + Gx.^2 + Bx.^2;\ngyy = Ry.^2 + Gy.^2 + By.^2;\ngxy = Rx.*Ry + Gx.*Gy + Bx.*By;\nA = 0.5*(atan(2*gxy./(gxx - gyy + eps)));\nG1 = 0.5*((gxx + gyy) + (gxx - gyy).*cos(2*A) + 2*gxy.*sin(2*A));\n\n% Now repeat for angle + pi/2. Then select the maximum at each point.\nA = A + pi/2;\nG2 = 0.5*((gxx + gyy) + (gxx - gyy).*cos(2*A) + 2*gxy.*sin(2*A));\nG1 = G1.^0.5;\nG2 = G2.^0.5;\n\n% Form VG by picking the maximum at each (x,y) and then scale\n% to the range [0,1] using function mat2gray.\nVG = mat2gray(max(G1,G2));\n\n% Select the corresponding angles. Where G2 is greater than G1, pick\n% values from array A + pi/2. Else, use values from A, which correspond\n% to G1. The angles are in radians.\nA(G2 > G1) = A(G2 > G1) + pi/2;\n\n% Compute the per-plane gradients.\nRG = hypot(Rx,Ry);\nGG = hypot(Gx,Gy);\nBG = hypot(Bx,By);\n% Form the composite by adding the individual results and scale to\n% [0,1].\nPPG = mat2gray(RG + GG + BG);\n\n% If T was provided, threshold the result.\nif nargin == 2\n VG = VG > T;\n PPG = PPG > T;\nend\n", "meta": {"author": "dipum", "repo": "dipum-toolbox", "sha": "9ce653c4c0c4b7c56e46194c24bf152db4ab6832", "save_path": "github-repos/MATLAB/dipum-dipum-toolbox", "path": "github-repos/MATLAB/dipum-dipum-toolbox/dipum-toolbox-9ce653c4c0c4b7c56e46194c24bf152db4ab6832/dipum/colorgrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.9219218343187415, "lm_q1q2_score": 0.859649061460103}} {"text": "function [J, grad] = lrCostFunction(theta, X, y, lambda)\n%LRCOSTFUNCTION Compute cost and gradient for logistic regression with \n%regularization\n% J = LRCOSTFUNCTION(theta, X, y, lambda) computes the cost of using\n% theta as the parameter for regularized logistic regression and the\n% gradient of the cost w.r.t. to the parameters. \n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost of a particular choice of theta.\n% You should set J to the cost.\n% Compute the partial derivatives and set grad to the partial\n% derivatives of the cost w.r.t. each parameter in theta\n%\n% Hint: The computation of the cost function and gradients can be\n% efficiently vectorized. For example, consider the computation\n%\n% sigmoid(X * theta)\n%\n% Each row of the resulting matrix will contain the value of the\n% prediction for that example. You can make use of this to vectorize\n% the cost function and gradient computations. \n%\n% Hint: When computing the gradient of the regularized cost function, \n% there're many possible vectorized solutions, but one solution\n% looks like:\n% grad = (unregularized gradient for logistic regression)\n% temp = theta; \n% temp(1) = 0; % because we don't add anything for j = 0 \n% grad = grad + YOUR_CODE_HERE (using the temp variable)\n%\n\n\n\nhtheta = sigmoid(X * theta);\nJ = 1 / m * sum(-y .* log(htheta) - (1 - y) .* log(1 - htheta)) + lambda / (2 * m) * sum(theta(2:end) .^ 2);\ntemp = theta;\ntemp(1) = 0;\ngrad = 1 / m * (X' * (htheta - y) + lambda * temp);\n\n\n\n\n\n\n% =============================================================\n\nend\n", "meta": {"author": "merwan", "repo": "ml-class", "sha": "0b06b73d4aac0b8d7c726325200c3781b5c9d3b0", "save_path": "github-repos/MATLAB/merwan-ml-class", "path": "github-repos/MATLAB/merwan-ml-class/ml-class-0b06b73d4aac0b8d7c726325200c3781b5c9d3b0/mlclass-ex3/lrCostFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522863, "lm_q2_score": 0.9073122263731811, "lm_q1q2_score": 0.8595704066618404}} {"text": "function area = annulus_sector_area_2d ( r1, r2, theta1, theta2 )\n\n%*****************************************************************************80\n%\n%% ANNULUS_SECTOR_AREA_2D computes the area of an annular sector in 2D.\n%\n% Discussion:\n%\n% An annular sector with center (XC,YC), inner radius R1 and\n% outer radius R2, and angles THETA1, THETA2, is the set of points\n% (X,Y) so that\n%\n% R1**2 <= (X-XC)**2 + (Y-YC)**2 <= R2**2\n%\n% and\n%\n% THETA1 <= THETA ( X - XC, Y - YC ) <= THETA2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 August 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R1, R2, the inner and outer radii.\n%\n% Input, real THETA1, THETA2, the angles.\n%\n% Output, real AREA, the area.\n%\n area = 0.5 * ( theta2 - theta1 ) * ( r2 + r1 ) * ( r2 - r1 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/annulus_sector_area_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799430946808, "lm_q2_score": 0.8918110440002045, "lm_q1q2_score": 0.859509597237725}} {"text": "function [J, grad] = costFunction(theta, X, y)\n%COSTFUNCTION Compute cost and gradient for logistic regression\n% J = COSTFUNCTION(theta, X, y) computes the cost of using theta as the\n% parameter for logistic regression and the gradient of the cost\n% w.r.t. to the parameters.\n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost of a particular choice of theta.\n% You should set J to the cost.\n% Compute the partial derivatives and set grad to the partial\n% derivatives of the cost w.r.t. each parameter in theta\n%\n% Note: grad should have the same dimensions as theta\n%\n\nJ = (-1/m)*((y'*log(sigmoid(X*theta))) + ((1-y)'*log(1 - sigmoid(X*theta))));\n\ngrad = (1/m)*(X' * (sigmoid(X*theta) - y));\n\n% =============================================================\n\nend\n", "meta": {"author": "UtkarshPathrabe", "repo": "Machine-Learning-Stanford-University-Coursera", "sha": "0e5855855b5ddd475775b75bad69b47c2ebe84ef", "save_path": "github-repos/MATLAB/UtkarshPathrabe-Machine-Learning-Stanford-University-Coursera", "path": "github-repos/MATLAB/UtkarshPathrabe-Machine-Learning-Stanford-University-Coursera/Machine-Learning-Stanford-University-Coursera-0e5855855b5ddd475775b75bad69b47c2ebe84ef/Programming Exercises/machine-learning-ex2/ex2/costFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9621075722839015, "lm_q2_score": 0.8933094124452288, "lm_q1q2_score": 0.8594597501060376}} {"text": "function [J, grad] = lrCostFunction(theta, X, y, lambda)\n%LRCOSTFUNCTION Compute cost and gradient for logistic regression with \n%regularization\n% J = LRCOSTFUNCTION(theta, X, y, lambda) computes the cost of using\n% theta as the parameter for regularized logistic regression and the\n% gradient of the cost w.r.t. to the parameters. \n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost of a particular choice of theta.\n% You should set J to the cost.\n% Compute the partial derivatives and set grad to the partial\n% derivatives of the cost w.r.t. each parameter in theta\n%\n% Hint: The computation of the cost function and gradients can be\n% efficiently vectorized. For example, consider the computation\n%\n% sigmoid(X * theta)\n%\n% Each row of the resulting matrix will contain the value of the\n% prediction for that example. You can make use of this to vectorize\n% the cost function and gradient computations. \n%\n% Hint: When computing the gradient of the regularized cost function, \n% there're many possible vectorized solutions, but one solution\n% looks like:\n% grad = (unregularized gradient for logistic regression)\n% temp = theta; \n% temp(1) = 0; % because we don't add anything for j = 0 \n% grad = grad + YOUR_CODE_HERE (using the temp variable)\n%\n\nH = sigmoid(X*theta);\nT = y.*log(H) + (1 - y).*log(1 - H);\nJ = -1/m*sum(T) + lambda/(2*m)*sum(theta(2:end).^2);\n\nta = [0; theta(2:end)];\ngrad = X'*(H - y)/m + lambda/m*ta;\n\n% =============================================================\n\nend\n", "meta": {"author": "zhouxc", "repo": "Stanford-Machine-Learning-Course", "sha": "cb1002771b33ac3af4a14be2afa0431212a66ea5", "save_path": "github-repos/MATLAB/zhouxc-Stanford-Machine-Learning-Course", "path": "github-repos/MATLAB/zhouxc-Stanford-Machine-Learning-Course/Stanford-Machine-Learning-Course-cb1002771b33ac3af4a14be2afa0431212a66ea5/Multi-class classification and neural networks/mlclass-ex3/lrCostFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.9032942151647513, "lm_q1q2_score": 0.8591612638675336}} {"text": "function [U, S] = pca(X)\n%PCA Run principal component analysis on the dataset X\n% [U, S, X] = pca(X) computes eigenvectors of the covariance matrix of X\n% Returns the eigenvectors U, the eigenvalues (on diagonal) in S\n%\n\n% Useful values\n[m, n] = size(X);\n\n% You need to return the following variables correctly.\nU = zeros(n);\nS = zeros(n);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: You should first compute the covariance matrix. Then, you\n% should use the \"svd\" function to compute the eigenvectors\n% and eigenvalues of the covariance matrix. \n%\n% Note: When computing the covariance matrix, remember to divide by m (the\n% number of examples).\n%\n\nSigma = 1.0/m .* X' * X;\n\n[U, S, V] = svd(Sigma);\n\n% =========================================================================\n\nend\n", "meta": {"author": "atinesh-s", "repo": "Coursera-Machine-Learning-Stanford", "sha": "4d128c09373e5513505734ed05c2f13c3fd0f05e", "save_path": "github-repos/MATLAB/atinesh-s-Coursera-Machine-Learning-Stanford", "path": "github-repos/MATLAB/atinesh-s-Coursera-Machine-Learning-Stanford/Coursera-Machine-Learning-Stanford-4d128c09373e5513505734ed05c2f13c3fd0f05e/Week 8/Programming Assignment/machine-learning-ex7/ex7/pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.909907002984195, "lm_q1q2_score": 0.8591131387957772}} {"text": "function y = norm_lpdf(x,mu,sigma)\n%NORM_LPDF Normal log-probability density function (lpdf).\n%\n% Y = NORM_LPDF(X,MU,SIGMA) Returns the log of the normal pdf with\n% mean, MU, and standard deviation, SIGMA, at the values in X.\n%\n% The size of Y is the common size of the input arguments. A scalar input \n% functions as a constant matrix of the same size as the other inputs. \n%\n% Default values for MU and SIGMA are 0 and 1 respectively.\n\n% Copyright (c) 1998-2004 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\nif nargin < 3, \n sigma = 1;\nend\n\nif nargin < 2;\n mu = 0;\nend\n\nif nargin < 1, \n error('Requires at least one input argument.');\nend\n\ny = -0.5 * ((x-mu)./sigma).^2 -log(sigma) -log(2*pi)/2;\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/dist/norm_lpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551505674444, "lm_q2_score": 0.8902942181173146, "lm_q1q2_score": 0.8590049618709068}} {"text": "function [J, grad] = costFunctionReg(theta, X, y, lambda)\n%COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization\n% J = COSTFUNCTIONREG(theta, X, y, lambda) computes the cost of using\n% theta as the parameter for regularized logistic regression and the\n% gradient of the cost w.r.t. to the parameters. \n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost of a particular choice of theta.\n% You should set J to the cost.\n% Compute the partial derivatives and set grad to the partial\n% derivatives of the cost w.r.t. each parameter in theta\n\nH_theta = sigmoid(X * theta);\n\nJ = -1/m * sum(y .* log(H_theta) + (1 - y) .* log(1 - H_theta)) + ...\n lambda/(2 * m) * norm(theta([2:end]))^2;\n\n% extra term for gradient\nG = lambda/m .* theta;\nG(1) = 0;\n\ngrad = 1/m .* X' * (H_theta - y) + G;\n\n% =============================================================\n\nend\n", "meta": {"author": "rmarquis", "repo": "coursera-machinelearning", "sha": "5b165935e6fecfab977b2af1b0e9c588c75ca8f4", "save_path": "github-repos/MATLAB/rmarquis-coursera-machinelearning", "path": "github-repos/MATLAB/rmarquis-coursera-machinelearning/coursera-machinelearning-5b165935e6fecfab977b2af1b0e9c588c75ca8f4/homework/mlclass-ex2/costFunctionReg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639686018701, "lm_q2_score": 0.8840392924390585, "lm_q1q2_score": 0.8589007233620809}} {"text": "function Angles = QUADangles(vertices)\n\n% Purpose: To find the angles of Quadrilateral when vertices are known \n% Synopsis: Angles = FindAngles(vertices)\n% \n% Variable description:\n% INPUT: vertices - coordinates of Quadrilateral in order 4X2 . The vertices \n% are given input in anticlock wise direction.\n% \n% OUTPUT: Angles - Row vector of angles of Quadrilateral in degrees of order 4X1\n% \n% Example: vertices = [4 4;4 6;5 6; 5 4] \n% angles = FindAngles(vertices); \n% angles = [90 90 90 90]\n% \n% Algorithm: Calculates the angles using dot product\n% theta = arccos((a.b)/(|a||b|)\n% \n% Release : 1.0\n% Release Date: 03/07/2012 \n%--------------------------------------------------------------------------\n% Author : Siva Srinivas Kolukula \n% Senior Research Fellow \n% Structural Mechanics Laboratory \n% Indira Gandhi Center for Atomic Research \n% India \n% E-mail : allwayzitzme@gmail.com \n% http://sites.google.com/site/kolukulasivasrinivas/ \n%--------------------------------------------------------------------------\n\nAngles = zeros(1,4) ;\norder = [ 1 2 4; 2 1 3; 3 4 2;4 3 1] ;\nfor i = 1:4\n % Form the vectors along the vertices\n data1 = [vertices(i,:); vertices(order(i,2),:)];\n data2 = [vertices(i,:); vertices(order(i,3),:)];\n % Use dor ptodict to find the angle between vector1 and vector2\n Angles(i) = acos((diff(data1)*diff(data2)')/.....\n (sqrt(sum(diff(data1,[],1).^2,2))*sqrt(sum(diff(data2,[],1).^2,2)))) ; \nend\n% Convert the angles in radians to degrees\nAngles = Angles*180./pi ; %", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/37389-find-angles/FindAngles/QUADangles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321807, "lm_q2_score": 0.9046505312448598, "lm_q1q2_score": 0.8584385087329672}} {"text": "% File: lognormpdf.m\n%\n% Copyright (C) Daphne Koller, Stanford Univerity, 2012\n\nfunction [log_prob] = lognormpdf(x,mu,sigma)\n\n% LOGNORMPDF Natural logarithm of the normal probability density function (pdf)\n% Y = lognormpdf(X,MU,SIGMA) returns the log of the pdf of the normal\n% distribution parameterized by mean MU and standard deviation SIGMA evaluated\n% at each value in the vector X. Thus, the size of the return\n% vector Y is the size of X. \n% \n% MU and X should have the same dimensions.\n\nlog_prob = -log(sigma*sqrt(2*pi))-(x-mu).^2 ./ (2*sigma.^2);\n", "meta": {"author": "anhncs", "repo": "Probabilistic-Graphical-Models", "sha": "7fd4ef255db59ecbfe1a134cadbc4be5ca839894", "save_path": "github-repos/MATLAB/anhncs-Probabilistic-Graphical-Models", "path": "github-repos/MATLAB/anhncs-Probabilistic-Graphical-Models/Probabilistic-Graphical-Models-7fd4ef255db59ecbfe1a134cadbc4be5ca839894/9.Learnign with Incomplete Data/lognormpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9609517106286379, "lm_q2_score": 0.8933094159957173, "lm_q1q2_score": 0.8584272114217542}} {"text": "function value = i4_factorial2 ( n )\n\n%*****************************************************************************80\n%\n%% I4_FACTORIAL2 computes the factorial N!!\n%\n% Formula:\n%\n% FACTORIAL2( N ) = Product ( N * (N-2) * (N-4) * ... * 2 ) (N even)\n% = Product ( N * (N-2) * (N-4) * ... * 1 ) (N odd)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the argument of the double factorial function.\n% If N is less than 1, VALUE is returned as 1.\n%\n% Output, integer VALUE, the value of N!!.\n%\n value = 1;\n\n if ( n < 1 )\n return\n end\n\n while ( 1 < n )\n value = value * n;\n n = n - 2;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/i4_factorial2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.9032942093072239, "lm_q1q2_score": 0.8578308403311538}} {"text": "function [ x, seed ] = sphere_unit_sample2_nd ( dim_num, seed )\n\n%*****************************************************************************80\n%\n%% SPHERE_UNIT_SAMPLE2_ND picks a random point on the unit sphere in ND.\n%\n% Discussion:\n%\n% The unit sphere in ND satisfies:\n%\n% sum ( 1 <= I <= DIM_NUM ) X(I) * X(I) = 1\n%\n% DIM_NUM independent normally distributed random numbers are generated,\n% and then scaled to have unit norm.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the dimension of the space.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real X(DIM_NUM), the random point.\n%\n% Output, integer SEED, a seed for the random number generator.\n%\n [ x, seed ] = r8vec_normal_01 ( dim_num, seed );\n\n norm = sqrt ( sum ( x(1:dim_num).^2 ) );\n\n x(1:dim_num) = x(1:dim_num) / norm;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/sphere_unit_sample2_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.9032942119105696, "lm_q1q2_score": 0.8578308402300306}} {"text": "function y=lagrange(x,pointx,pointy)\n%\n%LAGRANGE approx a point-defined function using the Lagrange polynomial interpolation\n%\n% LAGRANGE(X,POINTX,POINTY) approx the function definited by the points:\n% P1=(POINTX(1),POINTY(1)), P2=(POINTX(2),POINTY(2)), ..., PN(POINTX(N),POINTY(N))\n% and calculate it in each elements of X\n%\n% If POINTX and POINTY have different number of elements the function will return the NaN value\n%\n% function wrote by: Calzino\n% 7-oct-2001\n%\nn=size(pointx,2);\nL=ones(n,size(x,2));\nif (size(pointx,2)~=size(pointy,2))\n fprintf(1,'\\nERROR!\\nPOINTX and POINTY must have the same number of elements\\n');\n y=NaN;\nelse\n for i=1:n\n for j=1:n\n if (i~=j)\n L(i,:)=L(i,:).*(x-pointx(j))/(pointx(i)-pointx(j));\n end\n end\n end\n y=0;\n for i=1:n\n y=y+pointy(i)*L(i,:);\n end\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/899-lagrange-polynomial-interpolation/lagrange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966101527047, "lm_q2_score": 0.8991213847035617, "lm_q1q2_score": 0.857731322165257}} {"text": "function [y, slope] = groundHeight(x)\n%\n% This function returns the height (y) and slope (Dy) of the ground as a\n% function of the horizontal position. An interesting ground profile is\n% generated by summing three sine waves. This also makes the derivative\n% (slope) easy to compute.\n%\n\n%Parameters for each of the three sine ewaves:\n Amp1 = 0.3;\n Freq1 = 1;\n Phase1 = 1.58;\n\n Amp2 = 0.1;\n Freq2 = 6;\n Phase2 = 1.9;\n\n Amp3 = 0.2;\n Freq3 = 3.7;\n Phase3 = 1.58;\n\n%Compute the ground height\ny = Amp1*sin(Freq1*x+Phase1)+...\n Amp2*sin(Freq2*x+Phase2)+...\n Amp3*sin(Freq3*x+Phase3);\n\n%Compute the ground slope\nslope = Amp1*Freq1*cos(Freq1*x+Phase1)+...\n Amp2*Freq2*cos(Freq2*x+Phase2)+...\n Amp3*Freq3*cos(Freq3*x+Phase3);\n\nend", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/bouncingBall/groundHeight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668690081642, "lm_q2_score": 0.87407724336544, "lm_q1q2_score": 0.8576156321441559}} {"text": "function [retPath,retDist,cycleNodes]=BellmanFordAlg(adjMat,sourceIdx,destIdx)\n%%BELLMANFORDALG Use the Bellman-Ford algorithm to find the shortest path\n% from a given source node through a graph represented using\n% an adjacency matrix. Negative edge costs are allowed and\n% if a negative cycle reachable from the source exists in\n% the graph, then that cycle will be returned (and no\n% minimum distance path will exist).\n%\n%INPUTS: adjMat An adjacency matrix full of costs for the graph.\n% adjMat(i,j) is the cost of going from vertex i to vertex\n% j. If there is no connection between the vertices in the\n% graph, then set that element to infinity. Cycles\n% accessible from the source involving negative edge weights\n% are detected by the algorithm and mean that no solution\n% exists.\n% sourceIdx The index of the node (vertex) from which the shortest\n% paths to other vertices is desired.\n% destIdx The index of the destination path. If this parameter is\n% provided, then the path of nodes from the source to the\n% destination is returned along with the path length.\n% Otherwise, information allowing one to reconstruct the\n% whole path is returned if this parameter is omtted.\n% \n%OUTPUTS: retPath If destIdx is given, this is the minimum cost sequence of\n% nodes to get from sourceIdx to destIdx, including the end\n% nodes; if there is no path to the node, an empty matrix\n% is returned. Otherwise, this is prevNodes, such that one\n% can recreate all shortest paths. Starting at index idx,\n% the next node on the path in the reverse direction from\n% destimation to source is retPath(idx). By looping, one\n% can recreate the whole path. If there is no path to a\n% node, then retPath(idx)=0. If a negative cycle exists\n% in the path, then an empty matrix is returned. \n% retDist If destIdx is given, this is the shortest distance from\n% the source to the destination. If destIdx is not given,\n% then this is an array where each index holds the shortest\n% distance from the source to that node. If a negative\n% cycle exists in the graph, then an empty matrix is\n% returned.\n% cycleNodes If no negative cost cycles exist in the graph, then this\n% is an empty matrix. If any negative cycles exist, then\n% this will be the nodes in order of the first negative\n% cycle found. The last node in cycleNodes is connected\n% back to the first node, finishing the loop. A cycle is a\n% loop in the graph; a negative cost cycle is one where the\n% sum of the costs in the cycle is negative.\n%\n%The algorithm implemented is that of Chapter 24.1 of [1], where the\n%extraction of a negative cost cycle accessible from the source is added\n%when a negative cost cycle is detected.\n%\n%Ad an example, consider the adjacency matric with two negative cost\n%cycles:\n% adjMat=[Inf, -20, Inf;\n% Inf, Inf, 10,\n% 5, -15, Inf];\n% [retPath,retDist,cycleNodes]=BellmanFordAlg(adjMat,1,3);\n%Looking for a path from 1 to 3, the algorithm would encounter the cycle.\n%Thus, the return values would be [] and [] for retPath and retDist and \n%cycleNodes=[3;2], because that is the first cycle found.\n%\n%REFERENCES:\n%[1] T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein,\n% Introduction to Algorithms, 2nd ed. Cambridge, MA: The MIT Press,\n% 2001.\n%\n%June 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%The number of vertices.\nnumNodes=length(adjMat);\n\n%The shortest distance yet found from the source to each of the nodes.\ndist=inf(numNodes,1);\n%The distance from the source to itself is zero. This is the first node to\n%be visited.\ndist(sourceIdx)=0;\n%The previous node in the optimal path from the given node to the source.\nprevNodes=zeros(numNodes,1);\n\nfor i=1:(numNodes-1)\n for curNode=1:numNodes\n %We have to go over all edges from the current node. If\n %adjMat(curNode,destNode) is infinite, then no edge exists to destNode.\n for destNode=1:numNodes\n w=adjMat(curNode,destNode);%The edge weight\n if(~isfinite(w))\n continue;\n end\n\n %Perform the relaxation step.\n if(dist(curNode)+w<=dist(destNode))\n dist(destNode)=dist(curNode)+w;\n prevNodes(destNode)=curNode;\n end\n end\n end\nend\n\n%Now, we check for a negative weight cycle (reachable from the source). If\n%a negative weight cycle is found, then return it. We have to look at all\n%edges in the graph.\ncycleStart=[];\nfor curNode=1:numNodes\n for destNode=1:numNodes\n w=adjMat(curNode,destNode);%The edge weight\n if(~isfinite(w))\n continue;\n end\n \n if(dist(curNode)+w2)\n %If there is no path to the desired node.\n if(~isfinite(dist(destIdx)))\n retPath=[];\n retDist=Inf;\n return;\n end\n\n path=zeros(numNodes,1);\n path(1)=destIdx;\n pathStep=1;\n while(path(pathStep)~=sourceIdx)\n path(pathStep+1)=prevNodes(path(pathStep));\n pathStep=pathStep+1;\n end\n retPath=flipud(path(1:pathStep));\n retDist=dist(destIdx);\nelse\n retPath=prevNodes;\n retDist=dist;\nend\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Graph_Algorithms/BellmanFordAlg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.9124361682155118, "lm_q1q2_score": 0.8576109353698343}} {"text": "function value = v_hofstadter ( n )\n\n%*****************************************************************************80\n%\n%% V_HOFSTADTER computes the Hofstadter V sequence.\n%\n% Discussion:\n%\n% V(N) = 0 if N = 0\n% = 1 if 1 <= N <= 4\n% = V(N-V(N-1)) + V(N-V(N-4)), otherwise.\n%\n% V(N) is defined for all nonnegative integers.\n%\n% Table:\n%\n% N V(N)\n% -- ----\n%\n% 0 0\n% 1 1\n% 2 1\n% 3 1\n% 4 1\n% 5 2\n% 6 3\n% 7 4\n% 8 5\n% 9 5\n% 10 6\n% 11 6\n% 12 7\n% 13 8\n% 14 8\n% 15 9\n% 16 9\n% 17 10\n% 18 11\n% 19 11\n% 20 11\n% 21 12\n% 22 12\n% 23 13\n% 24 14\n% 25 14\n% 26 15\n% 27 15\n% 28 16\n% 29 17\n% 30 17\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 July 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the argument of the function.\n%\n% Output, integer VALUE, the value of the function.\n%\n if ( n <= 0 )\n value = 0;\n elseif ( n <= 4 )\n value = 1;\n else\n value = v_hofstadter ( n - v_hofstadter(n-1) ) ...\n + v_hofstadter ( n - v_hofstadter(n-4) );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/v_hofstadter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697695, "lm_q2_score": 0.90990700787036, "lm_q1q2_score": 0.8575934676455863}} {"text": "function ellipsLat=reducedLat2EllipsLat(reducedLat,f)\n%%REDUCEDLAT2ELLIPSLAT Convert reduced (parameteric) latitude into an\n% ellipsoidal (geodetic) latitude. A parameteric\n% latitude is an angle of elevation drawn from the\n% center of a sphere whose radius is equal to the\n% semi-major axis of the ellipsoid. The parametric\n% latitude is the angle of the point on the sphere\n% where a vertical line drawn from the major axis of\n% the ellipse through the point on the ellipse\n% intersects the sphere. This is a way of mapping an\n% ellipsoid onto a sphere.\n%\n%INPUTS: reducedLat A vector or matrix of reduced latitudes in radians.\n% These typically range from -pi/2 to pi/2.\n% f The flattening factor of the reference ellipsoid. If\n% this argument is omitted, the value in\n% Constants.WGS84Flattening is used.\n%\n%OUTPUTS: reducedLat The ellipsoidal (geodetic) latitude ranging from\n% -pi/2 to pi/2, for each reduced latitude.\n%\n%%The definition of the reduced (parameteric) latitude from Chapter 3 (pg.\n%18) of [1] is used. The conversion relation between the latitudes is in\n%Section 3.4 of [2].\n%\n%The reduced latitude has been used for solving geodescic problems on an\n%ellipsoid by transforming the problem to an equivalent problem on a\n%sphere.\n%\n%The inverse of this function is ellipsLat2ReducedLat.\n%\n%REFERENCES:\n%[1] J. P. Snyder, \"Map projections- a working manual,\" U.S. Geological\n% Survey, Tech. Rep. 1395, 1987.\n%[2] R. H. Rapp, \"Geometric geodesy, part I,\" Ohio State University\n% Department of Geodetic Science and Surveying, Tech. Rep., Apr. 1991.\n% [Online]. Available: http://hdl.handle.net/1811/24333\n%\n%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2)\n f=Constants.WGS84Flattening;\nend\n\n%The first numerical eccentricity of the ellipsoid.\ne=sqrt(2*f-f^2);\n\n%The wrapping helps deal with precision limitations that might push the\n%input value slightly above or below +/-pi/2. If the wrapping were not\n%done, then instead of getting, for example, pi/2, one will get pi/2 as a\n%return value.\nreducedLat=wrapRange(reducedLat,-pi/2,pi/2,true);\n\nellipsLat=atan(tan(reducedLat)/sqrt(1-e^2));\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Coordinate_Systems/Latitude_Conversion/reducedLat2EllipsLat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305307578324, "lm_q2_score": 0.8902942341267435, "lm_q1q2_score": 0.857558587668541}} {"text": "function area = sphere_triangle_angles_to_area ( r, a, b, c )\n\n%*****************************************************************************80\n%\n%% SPHERE_TRIANGLE_ANGLES_TO_AREA computes the area of a spherical triangle.\n%\n% Discussion:\n%\n% A sphere centered at 0 in 3D satisfies the equation:\n%\n% X*X + Y*Y + Z*Z = R*R\n%\n% A spherical triangle is specified by three points on the surface\n% of the sphere.\n%\n% The area formula is known as Girard's formula.\n%\n% The area of a spherical triangle is:\n%\n% AREA = ( A + B + C - PI ) * R*R\n%\n% where A, B and C are the (surface) angles of the triangle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, the radius of the sphere.\n%\n% Input, real A, B, C, the angles of the triangle.\n%\n% Output, real AREA, the area of the spherical triangle.\n%\n\n%\n% Apply Girard's formula.\n%\n area = r * r * ( a + b + c - pi );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/sphere_triangle_angles_to_area.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620585273153, "lm_q2_score": 0.8933093975331751, "lm_q1q2_score": 0.8573644662782359}} {"text": "function value = i4_log_2 ( i )\n\n%*****************************************************************************80\n%\n%% I4_LOG_2 returns the integer part of the logarithm base 2 of |I|.\n%\n% Discussion:\n%\n% For positive I4_LOG_2(I), it should be true that\n% 2**I4_LOG_2(X) <= |I| < 2**(I4_LOG_2(I)+1).\n% The special case of I4_LOG_2(0) returns -HUGE().\n%\n% Example:\n%\n% I Value\n%\n% 0 -1\n% 1, 0\n% 2, 1\n% 3, 1\n% 4, 2\n% 5, 2\n% 6, 2\n% 7, 2\n% 8, 3\n% 9, 3\n% 10, 3\n% 127, 6\n% 128, 7\n% 129, 7\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 April 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer I, the number whose logarithm base 2 is desired.\n%\n% Output, integer VALUE, the integer part of the logarithm base 2 of\n% the absolute value of I.\n%\n i = floor ( i );\n\n if ( i == 0 )\n\n value = -inf;\n\n else\n\n value = 0;\n\n i = abs ( i );\n\n while ( 2 <= i )\n i = i / 2;\n value = value + 1;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_laguerre/i4_log_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.9032942008463507, "lm_q1q2_score": 0.8571514647044269}} {"text": "function [B,C]=nearestKronProd(A,m1,m2,n1,n2)\n%%NEARESTKRONPRODSVD Given an (m1*m2)X(n1*n2) matrix, determine the set of\n% matrices B and C that minimize norm(A-kron(B,C),'fro'). B is\n% m1Xn1 and C is m2Xn2. B and C are not unique. One can always\n% replace them with x*B and (1/x)*C for some arbitrary scalar x.\n%\n%INPUTS: A An (m1*m2)X(n1*n2) real matrix which is an m1Xn1 collection of\n% blocks of size m2Xn2. It has the form\n% A=[A_{1,1} ... A_{1,n1};\n% ... ... ...;\n% A_{m1,1} ... A_{m1,n1}];\n% m1,m2,n1,n2 The dimensions specifying A and its submatrices as described\n% above. These specify the dimensions of B and C.\n%\n%OUTPUTS: B The m1Xn1 left matrix in the Kronecker product.\n% C The m2Xn2 right matrix in the Kronecker product.\n%\n%This function implements the algorithm described in Section 12.3.6 of [1].\n%\n%EXAMPLE:\n%Here, we compute A explicitely from a Kronecker product of B and C\n%matrices. The nearest Kronecker product obtained by this function should\n%thus have zero error, which, within finite precision limits, is\n%demonstrated.\n% m1=2;\n% m2=3;\n% n1=5;\n% n2=4;\n% B=randn(m1,n1);\n% C=randn(m2,n2);\n% A=kron(B,C);\n% \n% [BK,CK]=nearestKronProd(A,m1,m2,n1,n2);\n% norm(A-kron(BK,CK),'fro')%The error will be close to 0.\n%\n%REFERENCES:\n%[1] G. H. Golub and C. F. Van Loan, Matrix Computations, 4th ed.\n% Baltimore: Johns Hopkins University Press, 2013.\n%\n%September 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n[sigma,U,V]=KroneckerProdSVD(A,m1,n1,m2,n2);\n\nsqrtSigma1=sqrt(sigma(1));\n\nB=sqrtSigma1*U(:,:,1);\nC=sqrtSigma1*V(:,:,1);\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Continuous_Optimization/nearestKronProd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.9086179037377831, "lm_q1q2_score": 0.8571424914712594}} {"text": "function [X_norm, mu, sigma] = featureNormalize(X)\n%FEATURENORMALIZE Normalizes the features in X \n% FEATURENORMALIZE(X) returns a normalized version of X where\n% the mean value of each feature is 0 and the standard deviation\n% is 1. This is often a good preprocessing step to do when\n% working with learning algorithms.\n\n% You need to set these values correctly\nX_norm = X;\nmu = zeros(1, size(X, 2));\nsigma = zeros(1, size(X, 2));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: First, for each feature dimension, compute the mean\n% of the feature and subtract it from the dataset,\n% storing the mean value in mu. Next, compute the \n% standard deviation of each feature and divide\n% each feature by it's standard deviation, storing\n% the standard deviation in sigma. \n%\n% Note that X is a matrix where each column is a \n% feature and each row is an example. You need \n% to perform the normalization separately for \n% each feature. \n%\n% Hint: You might find the 'mean' and 'std' functions useful.\n% \n\n\nmu = mean(X_norm);\nsigma = std(X_norm);\n\ntf_mu = X_norm - repmat(mu,length(X_norm),1);\ntf_std = repmat(sigma,length(X_norm),1);\n\nX_norm = tf_mu ./ tf_std;\n\n\n% ============================================================\n\nend\n", "meta": {"author": "Borye", "repo": "machine-learning-coursera-1", "sha": "033fdc2e6da393eeb1179a09aafe92362021effb", "save_path": "github-repos/MATLAB/Borye-machine-learning-coursera-1", "path": "github-repos/MATLAB/Borye-machine-learning-coursera-1/machine-learning-coursera-1-033fdc2e6da393eeb1179a09aafe92362021effb/Week 2 Assignments/Linear Regression with Multiple Variables/mlclass-ex1/featureNormalize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.9136765157744067, "lm_q1q2_score": 0.8571418838895435}} {"text": "function area = triangleArea3d(pt1, pt2, pt3)\n%TRIANGLEAREA3D Area of a 3D triangle.\n%\n% AREA = triangleArea3d(P1, P2, P3)\n% Computes area of the 3D triangle whose vertices are given by P1, P2 and\n% P3. Each vertex is either a 1-by-3 row vector, or an array with 3\n% columns, each column representing coordinate of a vertex.\n% The result AREA has as many rows as the number of rows of the largest\n% input array.\n% Compared to polygonArea3d, this function is assumed to be faster, as it\n% does not requires iteration over vertices. Moreover, it can be used to\n% computes the area of several triangles simultaneously.\n%\n% AREA = triangleArea3d(PTS)\n% Concatenates vertex coordinates in a 3-by-3 array. Each row of the\n% array contains coordinates of one vertex.\n%\n%\n% Example\n% triangleArea3d([10 10 10], [30 10 10], [10 40 10])\n% ans = \n% 300\n%\n% See also\n% polygons3d, polygonArea3d\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2011-08-23, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n% if data is given as one array, split vertices\nif nargin == 1\n pt2 = pt1(2,:);\n pt3 = pt1(3,:);\n pt1 = pt1(1,:);\nend\n\n% compute individual vectors\nv12 = bsxfun(@minus, pt2, pt1);\nv13 = bsxfun(@minus, pt3, pt1);\n\n% compute area from cross product\narea = vectorNorm3d(cross(v12, v13, 2)) / 2;\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/triangleArea3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9546474207360066, "lm_q2_score": 0.8976952852648487, "lm_q1q2_score": 0.8569824886849614}} {"text": "function dist = lines_imp_dist_2d ( a1, b1, c1, a2, b2, c2 )\n\n%*****************************************************************************80\n%\n%% LINES_IMP_DIST_2D determines the distance between two implicit lines in 2D.\n%\n% Discussion:\n%\n% If the lines intersect, then their distance is zero.\n% If the two lines are parallel, then they have a nonzero distance.\n%\n% The implicit form of a line in 2D is:\n%\n% A * X + B * Y + C = 0\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A1, B1, C1, define the first line.\n% At least one of A1 and B1 must be nonzero.\n%\n% Input, real A2, B2, C2, define the second line.\n% At least one of A2 and B2 must be nonzero.\n%\n% Output, real DIST, the distance between the two lines.\n%\n dim_num = 2;\n%\n% Refuse to handle degenerate lines.\n%\n if ( a1 == 0.0 & b1 == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LINES_IMP_DIST_2D - Fatal error!\\n' );\n fprintf ( 1, ' Line 1 is degenerate.\\n' );\n error ( 'LINES_IMP_DIST_2D - Fatal error!' );\n elseif ( a2 == 0.0 & b2 == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LINES_IMP_DIST_2D - Fatal error!\\n' );\n fprintf ( 1, ' Line 2 is degenerate.\\n' );\n error ( 'LINES_IMP_DIST_2D - Fatal error!' );\n end\n%\n% Determine if the lines intersect.\n%\n if ( a1 * b2 ~= a2 * b1 )\n dist = 0.0;\n return\n end\n%\n% Determine the distance between the parallel lines.\n%\n dist = abs ( c2 / sqrt ( a2 * a2 + b2 * b2 ) - c1 / sqrt ( a1 * a1 + b1 * b1 ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/lines_imp_dist_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360067, "lm_q2_score": 0.8976952811593495, "lm_q1q2_score": 0.8569824847656574}} {"text": "function pdf = cardioid_pdf ( x, a, b )\n\n%*****************************************************************************80\n%\n%% CARDIOID_PDF evaluates the Cardioid PDF.\n%\n% Discussion:\n%\n% The cardioid PDF can be thought of as being applied to points on\n% a circle. Compare this distribution with the \"Cosine PDF\".\n%\n% PDF(A,B;X) = ( 1 / ( 2 * PI ) ) * ( 1 + 2 * B * COS ( X - A ) )\n% for 0 <= B <= 1/2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 August 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% N I Fisher,\n% Statistical Analysis of Circular Data,\n% Cambridge, 1993.\n%\n% Parameters:\n%\n% Input, real X, the argument of the PDF.\n%\n% Input, real A, B, the parameters of the PDF.\n% 0.0 <= B <= 0.5.\n%\n% Output, real PDF, the value of the PDF.\n%\n pdf = ( 1.0 + 2.0 * b * cos ( x - a ) ) / ( 2.0 * pi );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/cardioid_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900508, "lm_q2_score": 0.8933094103149355, "lm_q1q2_score": 0.8568215479215273}} {"text": "function [means,Nmeans] = simple_kmeans(X,K,maxerr)\n\n% function [medias,Nmedias] = simple_kmedias(X,K,maxerr)\n% Finds K prototypes representing the samples in data matrix X,\n% where each row of X represents a sample. \n% Iterates until maximum norm difference between\n% prototypes found in successive iterations is < maxerr\n% \n% This script uses square Euclidean distance, \n% but can be easily modified to use other metrics\n%\n% Output arguments\n% means: matrix with each row a cluster prototype\n% Nmeans: Number of samples in each cluster\n%\n% Example:\n% X = [randn(100,1) ; 2+randn(100,1)];\n% K = 2;\n% [means Nmeans] = simple_kmeans(X,K,0)\n%\n% Mauricio Martinez-Garcia, 2003,2007\n\n[Ndata, dims] = size(X);\ndist = zeros(1,K);\n\n% Initial prototype assignment (arbitrary)\nfor i=1:K-1\n means(i,:) = X(i,:);\nend\nmeans(K,:) = mean(X(K:Ndata,:));\n\ncmp = 1 + maxerr;\nwhile (cmp > maxerr)\n % Sums (class) and data counters (Nclass) initialization\n class = zeros(K,dims);\n Nclass = zeros(K,1);\n\n % Groups each elements to the nearest prototype\n for i=1:Ndata\n for j=1:K\n % Euclidean distance from data to each prototype\n dist(j) = norm(X(i,:)-means(j,:))^2;\n end\n % Find indices of minimum distance\n index_min = find(~(dist-min(dist)));\n % If there are multiple min distances, decide randomly\n index_min = index_min(ceil(length(index_min)*rand));\n class(index_min,:) = class(index_min,:) + X(i,:);\n Nclass(index_min) = Nclass(index_min) + 1;\n end\n for i=1:K\n class(i,:) = class(i,:) / Nclass(i);\n end\n\n % Compare results with previous iteration\n cmp = 0;\n for i=1:K\n cmp = norm(class(i,:)-means(i,:)); \n end\n\n % Prototype update\n means = class;\nend\n\nNmeans = Nclass;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/16762-k-means-algorithm-demo/simple_kmeans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.9032941988938413, "lm_q1q2_score": 0.8564624922768176}} {"text": "classdef PoissonD\n%%POISSOND Functions to handle the Poisson distribution.\n%Implemented methods are: mean, var, PMF, CDF, momentGenFun, cumGenFun,\n% rand\n%\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nmethods(Static)\n\nfunction val=mean(lambda)\n%%MEAN Obtain the mean of the Poisson distribution for the specified mean\n% parameter.\n%\n%INPUTS: lambda The mean (and variance) of the Poisson distribution.\n%\n%OUTPUTS: val The mean of the Poisson distribution under consideration.\n%\n%The Poisson distribution is discussed in Chapter 2.8 of [1].\n%\n%EXAMPLE:\n%We verify the computed mean by comparing it to the sample mean.\n% lambda=10;\n% meanVal=PoissonD.mean(lambda)\n% numSamp=1e5;\n% sampMeanVal=mean(PoissonD.rand([1,numSamp],lambda))\n%One will find both values are about 10.\n%\n%REFERENCES:\n%[1] S. M. Ross, Simulation, 4th ed. Amsterdam: Academic Press, 2006.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=lambda;\nend\n\nfunction val=var(lambda)\n%%VAR Obtain the variance of the Poisson distribution for the specified\n% mean parameter\n%\n%INPUTS: lambda The mean (and variance) of the Poisson distribution,\n%\n%OUTPUTS: val The variance of the Poisson distribution.\n%\n%The Poisson distribution is discussed in Chapter 2.8 of [1].\n%\n%EXAMPLE:\n%We verify that the computed variance by comparing it to the sample\n%variance.\n% lambda=10;\n% varVal=PoissonD.var(lambda)\n% numSamp=1e5;\n% sampVarVal=var(PoissonD.rand([1,numSamp],lambda))\n%One will find both values are about 10.\n%\n%REFERENCES:\n%[1] S. M. Ross, Simulation, 4th ed. Amsterdam: Academic Press, 2006.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=lambda;\nend\n\nfunction val=PMF(x,lambda)\n%%PMF Evaluate the Poisson probability mass function (PMF) at given points\n% with a specified mean parameter.\n%\n%INPUTS: x The point(s) at which the Poisson PMF is to be evaluated. x is\n% an integer. For nonzero PMF values, x>=0.\n% lambda The mean (and variance) of the Poisson distribution under\n% consideration.\n%\n%OUTPUTS: val The value(s) of the Poisson PMF with mean lambda.\n%\n%The Poisson distribution is discussed in Chapter 2.8 of [1].\n%\n%EXAMPLE:\n%Here, we validate the PMF by generating random samples and comparing the\n%PMF plot with a histogram of the random samples.\n% lambda=6;\n% numSamples=1e5;\n% figure(1)\n% clf\n% histogram(PoissonD.rand([numSamples,1],lambda),'BinWidth',1,'Normalization','pdf')\n% hold on\n% x=0:16;\n% vals=PoissonD.PMF(x,lambda);\n% stem(x,vals,'linewidth',2)\n% h1=xlabel('x');\n% h2=ylabel('PDF(x)');\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%One will see that the histogram matches well with the plot.\n%\n%REFERENCES:\n%[1] S. M. Ross, Simulation, 4th ed. Amsterdam: Academic Press, 2006.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n \n val=zeros(size(x));\n sel=(x>=0);\n\n val(sel)=(lambda.^x(sel)./factorial(x(sel)))*exp(-lambda);\nend\n\nfunction [FVal,pVal]=CDF(x,lambda)\n%%CDF Evaluate the cumulative distribution function of the Poisson\n% distribution at desired points.\n%\n%INPUTS: x The integer point(s) at which the Poisson CDF is evaluated.\n% lambda The mean (and variance) of the Poisson distribution.\n%\n%OUTPUTS: FVal The CDF of the Poisson distribution evaluated at the desired\n% point(s).\n% pVal The value of the PMF of the Poisson distribution at the\n% desired point(s).\n%\n%The recursion is from Chapter 4.2 of [1].\n%\n%EXAMPLE:\n%We validate the CDF value by comparing it to a value computed from random\n%samples.\n% lambda=6;\n% x=3;\n% numSamples=1e5;\n% prob=PoissonD.CDF(x,lambda)\n% probSamp=mean(PoissonD.rand([numSamples,1],lambda)<=x)\n%One will find the values ot both be about 0.151.\n%\n%REFERENCES:\n%[1] S. M. Ross, Simulation, 4th ed. Amsterdam: Academic Press, 2006.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n \n FVal=zeros(size(x));\n pVal=zeros(size(x));\n \n x=floor(x);%In case decimals were passed.\n numEls=numel(x);\n\n for curEl=1:numEls\n p=exp(-lambda);\n F=p;\n for I=1:fix(x(curEl))\n p=p*lambda/I;\n F=F+p;\n end\n FVal(curEl)=F;\n pVal(curEl)=p;\n end\n FVal(x<0)=0;\n pVal(x<0)=0;\nend\n\nfunction momentVal=momentGenFun(lambda,numDerivs,t)\n%%MOMENTGENFUN Evaluate the moment generating function (or one of its\n% derivatives) of the Poisson distribution. Taking the kth\n% derivative of the moment generating function and evaluating\n% it at t=0 provides the kth noncentral moment of the\n% distribution.\n%\n%INPUTS: lambda The mean (and variance) of the Poisson distribution.\n% numDerivs The number of derivatives to take with respect to the\n% argument of the moment generating function. numDerivs>=0.\n% t The numPointsX1 or 1XnumPoints vector of points where the\n% moment generating function should be evaluated. If this\n% parameter is omitted or an empty matrix is passed, the\n% default value of 0 is used.\n%\n%OUTPUTS: momentVal A numPointsX1 vector of the values of the derivatives\n% of the moment generating function given at the points\n% in t or at t=0 if t is omitted.\n%\n%The moment generating function of a random variable is defined to be\n%E(exp(t*x)) where E is the expected value operator, x is the random\n%variable and t is a real parameter. It can be shown that the moment\n%generating function of the Poisson distribution is\n%f^0(t)=exp(lambda*(exp(t)-1))\n%By noting the pattern in differentiation (using the chain rule), it can be\n%seen that the derivatives of the moment generating function can be\n%recurively expressed. Specifically, if f^n(t) is the nth derivative, the\n%value for n>0 is \n%f^n(t)=lambda*exp(t)*(sum_{k=0}^(n-1) binomial(n-1,k)*f^k(t))\n%This function evaluates the moments using the above recursion. The\n%binomial terms are computed recurively using the recursion inherent to\n%Pascal's triangle.\n%\n%Note that because the function recursively accumulates values for the\n%derivatives, a lot of memory will be used if numDerivs is very large.\n%\n%August 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nif(nargin<3||isempty(t))\n t=0; \nend\n\nnumT=length(t);\nmomentVal=zeros(numT,1);%Allocate Space\nfor curT=1:numT\n tVal=t(curT);\n \n fVals=zeros(numDerivs+1,1);\n fVals(1)=exp(lambda*(exp(tVal)-1));%The moment generating function value.\n\n pascalTriangleRowOld=zeros(numDerivs+1,1);\n pascalTriangleRowOld(1)=1;\n expCoeff=exp(tVal)*lambda;\n for curDeriv=1:numDerivs\n %Get the next row of Pascal's triangle\n pascalTriangleRow=zeros(numDerivs+1,1);\n pascalTriangleRow(1)=1;\n for i=2:(curDeriv-1)\n pascalTriangleRow(i)=pascalTriangleRowOld(i-1)+pascalTriangleRowOld(i);\n end\n pascalTriangleRow(curDeriv)=1;\n\n fVals(curDeriv+1)=expCoeff*sum(pascalTriangleRow.*fVals);\n pascalTriangleRowOld=pascalTriangleRow;\n end\n\n momentVal(curT)=fVals(end);\nend\n\nend\n\nfunction cumVal=cumGenFun(lambda,numDerivs,t)\n%%CUMGENFUN Evaluate the cumulant generating function (or one of its\n% derivatives) of the Poisson distribution. The cumulant\n% generating function is the natural logarithm of the moment\n% generating function.\n%\n%INPUTS: lambda The mean (and variance) of the Poisson distribution.\n% numDerivs The number of derivatives to take with respect to the\n% argument of the cumulant generating function, numDerivs>=0.\n% t The numPointsX1 or 1XnumPoints vector of points where the\n% moment generating function should be evaluated. If this\n% parameter is omitted or an empty matrix is passed, the\n% default value of 0 is used.\n%\n%OUTPUTS: cumVal A numPointsX1 or 1XnumPoints vector of the values of the\n% derivatives of the cumulant generating function given at\n% the points in t or at t=0 if t is omitted.\n%\n%The moment generating function of a random variable is defined to be\n%E(exp(t*x)) where E is the expected value operator, x is the random\n%variable and t is a real parameter. The cumulant generating function is\n%defined as the natural logarithm of the moment generating function. It can\n%be shown that the moment generating function of the Poisson distribution\n%is\n%E(exp(t*x))=exp(lambda*(exp(t)-1))\n%Thus, the cumulant generating function is just\n%lambda*(exp(t)-1)\n%All derivatives of the cumulant generating function are consequently\n%exp(t)*lambda.\n%\n%September 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nif(nargin<3||isempty(t))\n t=0; \nend\n\nif(numDerivs==0)\n cumVal=lambda*(exp(t)-1);\nelse\n cumVal=exp(t)*lambda;\nend\n \nend\n\nfunction vals=rand(N,lambda)\n%%RAND Generate Poisson random variables with a given mean.\n%\n%INPUTS: N If N is a scalar, then rand returns an NXN matrix of random\n% variables. If N=[M,N1] is a two-element row vector, then rand\n% returns an MXN1 matrix of random variables.\n% lambda The mean (and variance) of the Poisson distribution.\n%\n%OUTPUTS: vals A matrix whose dimensions are determined by N of the\n% generated Poisson random variables.\n%\n%The Poisson random variables are generated according to the simple\n%method given in Chapter 4.2 of [1].\n%\n%The algorithm can handle small and large values of lambda. However, there\n%is always a possibility that the value desired might be on the tail\n%end of the distribution and be very slow. Thus, the number of iterations\n%(the offset from the mean) is set to the maximum of 10 and 10* the\n%variance.\n%\n%REFERENCES:\n%[1] S. M. Ross, Simulation, 4th ed. Amsterdam: Academic Press, 2006.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n if(isscalar(N))\n dims=[N, N];\n else\n dims=N;\n end\n\n maxIter=max(10,10*lambda);\n\n vals=zeros(dims);\n for curRow=1:dims(1)\n for curCol=1:dims(2)\n I=fix(lambda);\n [F,p]=PoissonD.CDF(I,lambda);\n U=rand(1);\n\n if(U<=F)\n %This means that the random number being generated is less than \n %or equal to I and we must search downward.\n while(U-1)\n F=F-p;\n p=p*(I/lambda);\n I=I-1;\n end\n I=I+1;\n else\n %This means that the random number being generated is greater \n %than I and we must search upward starting from I+1.\n curIter=0;\n while(U>F&&curIter 2\n% h = h(3:n) - h(1:n-2);\n% g(2:n-1,:) = (f(3:n,:)-f(1:n-2,:))./h(:,ones(p,1));\n% end\n%\n% with...\n% % Take centered differences on interior points\n% if n > 2\n% if all(abs(diff(h,2)) < eps) % only use for uniform h (RAC)\n% h = h(3:n) - h(1:n-2);\n% g(2:n-1,:) = (f(3:n,:)-f(1:n-2,:))./h(:,ones(p,1));\n% else % new formula for un-evenly spaced coordinates (RAC)\n% h = diff(h); h_i=h(1:end-1,ones(p,1)); h_ip1=h(2:end,ones(p,1));\n% g(2:n-1,:) = (-(h_ip1./h_i).*f(1:n-2,:) + ...\n% (h_i./h_ip1).*f(3:n,:) )./ (h_i + h_ip1) + ...\n% ( 1./h_i - 1./h_ip1 ).*f(2:n-1,:);\n% end\n% end\n\n\n% Ensure compatible vectors and x monotonically increasing or decreasing\nif nargin<2\n\tm = 1;\n h = 1;\n x = 1;\nelse\n\tm = length(x);\nend\nTflag = 0;\nif ndims(F)==2 & size(F,1)==1 % Treat row vector as a column vector\n F = F.';\n Tflag = 1;\nend;\n\n[n,p] = size(F);\nif m==0\n error('x cannot be null')\nelseif m~=1 & m~=n\n\terror('First dimension of F and x must be the same.')\nelseif m>1 & ~( all(diff(x)>0) | all(diff(x)<0) )\n\terror('Vector x must be monotonically increasing or decreasing.')\nelseif n<=1\n Fx = F / x;\n return\nend\n\nFx = zeros(size(F));\nx = x(:);\n\n% Forward difference at left end\nif m==1\n\th = x;\nelse\n\th = x(2) - x(1); \nend\nFx(1,:) = ( F(2,:) - F(1,:) ) / h;\n\n% Backward difference at right end\nif m>1, h = x(m) - x(m-1); end\nFx(n,:) = ( F(n,:) - F(n-1,:) ) / h;\n\n% Central Difference in interior\nif n > 3\n\tif m==1 | all(diff(x)==h) % Evenly spaced formula used in MATLAB's gradient routine\n\t\tFx(2:n-1) = ( F(3:n,:) - F(1:n-2,:) ) / (2*h);\n else\n\t\th = diff(x); h_i=h(1:m-2,ones(p,1)); h_ip1=h(2:m-1,ones(p,1));\n\t\tFx(2:n-1,:) = (-(h_ip1./h_i).*F(1:n-2,:) + ...\n\t\t (h_i./h_ip1).*F(3:n,:) )./ (h_i + h_ip1) + ...\n\t\t ( 1./h_i - 1./h_ip1 ).*F(2:n-1,:);\n\tend\nend\nif Tflag, Fx=Fx.'; end", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/12-centraldiff-m/central_diff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145364, "lm_q2_score": 0.9086178913651383, "lm_q1q2_score": 0.8563784710812109}} {"text": "function [ s, r, l ] = r8_mant ( x )\n\n%*****************************************************************************80\n%\n%% R8_MANT computes the \"mantissa\" or \"fraction part\" of X.\n%\n% Formula:\n%\n% X = S * R * 2^L\n%\n% S is +1 or -1,\n% R is a real value between 1.0 and 2.0,\n% L is an integer.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 20 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the number to be decomposed.\n%\n% Output, integer S, the \"sign\" of the number.\n% S will be -1 if X is less than 0, and +1 if X is greater\n% than or equal to zero.\n%\n% Output, real R, the mantissa of X. R will be greater\n% than or equal to 1, and strictly less than 2. The one\n% exception occurs if X is zero, in which case R will also\n% be zero.\n%\n% Output, integer L, the integer part of the logarithm (base 2) of X.\n%\n\n%\n% Determine the sign.\n%\n if ( x < 0.0 )\n s = -1;\n else\n s = 1;\n end\n%\n% Set R to the absolute value of X, and L to zero.\n% Then force R to lie between 1 and 2.\n%\n if ( x < 0.0 )\n r = -x;\n else\n r = x;\n end\n\n l = 0;\n%\n% Time to bail out if X is zero.\n%\n if ( x == 0.0 )\n return\n end\n\n while ( 2.0 <= r )\n r = r / 2.0;\n l = l + 1;\n end\n\n while ( r < 1.0 )\n r = r * 2.0;\n l = l - 1;\n end\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8_mant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140233, "lm_q2_score": 0.9161096130168221, "lm_q1q2_score": 0.8560083890865152}} {"text": "%ELIIPSOID Plots the upper half of a parametric ellipsoid of rotation\n% Figure 13.10.For explanations see Subsection 13.26 in the book.\n\n% define axes\na = 5;\nb = 3;\nc = 2;\n% plot the boundary of the patch and define frame\nw = 0: 0.01: 1;\nx = a*cos(2*pi*w);\ny = b*sin(2*pi*w);\nz = zeros(size(x));\nplot3(x, y, z, 'k-')\naxis off, axis equal\naxis([ -1.1*a 1.1*a -1.1*b 1.1*b -0.3 1.2*c ])\nt = [ 'Ellipsoid x^2/a^2 + y^2/b^2 + z^2/c^2 = 1, a = ' num2str(a) ];\nt = [ t ', b = ' num2str(b) ' c = ' num2str(c) ]\nHt = title(t);\nset(Ht, 'FontSize', 14)\nhold on\n% plot now family of constant-w curves\nu = 0: 0.01: 1;\nfor w = 0: 0.1: 1\n x = a*cos(pi*u).*cos(2*pi*w);\n y = b*cos(pi*u).*sin(2*pi*w);\n z = c*sin(pi*u);\n plot3(x, y, z, 'k-')\nend \nfor w1 = 0.5: 0.1: 0.9\n t = [ 'w = ' num2str(w1) ];\n xt = a*cos(2*pi*w1);\n yt = b*sin(2*pi*w1);\n zt = -0.3;\n Ht = text(xt, yt, zt, t);\n set(Ht, 'FontSIze', 12)\nend \n\n% plot now family of constant-u curves\nw2 = 0: 0.01: 1;\nfor u2 = 0: 0.1: 1\n x = a*cos(pi/2*u2).*cos(2*pi*w2);\n y = b*cos(pi/2*u2).*sin(2*pi*w2);\n z = c*sin(pi/2*u2).*ones(size(x));\n plot3(x, y, z, 'k-')\nend \nw3 = 0.6;\nfor u3 = 0: 0.1: 1\n x3 = a*cos(pi/2*u3).*cos(2*pi*w3);\n y3 = b*cos(pi/2*u3).*sin(2*pi*w3);\n z3 = c*sin(pi/2*u3).*ones(size(x3));\n t3 = [ 'u = ' num2str(u3) ];\n % xt1 = a*cos(2*pi*w3);\n % yt1 = b*sin(2*pi*w);\n % zt1 = c*sin(pi/2*u);\n Ht = text(x3, y3, z3, t3);\n set(Ht, 'FontSIze', 12)\nend\nhold off", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/4233-ship-hydrostatics-and-stability/ellipsoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.9073122282528898, "lm_q1q2_score": 0.8559107900107816}} {"text": "function p = perms1(n,b)\n\n% PERMS1(n,b), where n is a positive integer, creates a vector with n\n% columns containing one permutation of the numbers from 1 to n. Input b is\n% a number between 1 and n! which is the index of the required permutation,\n% such that the output of PERMS1(n,b) for b from 1 to n! is equivalent to \n% the output from perms(1:n). The order of the permutations is, however, \n% different (e.g.,PERMS1(n,5) does not give the fifth row of the PERMS(1:n) output).\n\n% The algorithm is based on imagining that the permutations are obtained by\n% using n nested loops. The counter in each inner loop skips the values of all\n% outer loops to generate the required permutations. A counter (index) in the\n% innermost loop would count n! permutations. Working backwards, given the value\n% of an index between 1 and n! this algorithm figures out the state of the\n% counter in each these imaginary loops, which are actually the required\n% permutation indices.\n\n%K. H. Hamed, \n%Sultan Qaboos University, Muscat, Oman\n%khhamed@squ.edu.om\n%21 November 2006\n\nif nargin <2\n error('PERMS1:minrhs','Two Input Arguments are required.')\nend;\nif fix(n) ~= n || fix(b) ~= b ||n < 0 || b < 0 || ~isa(n,'double') || ~isa(b,'double') || ~isreal(n) || ~isreal(b)\n error('PERMS1:nnegint','Input Parameters n and b Must be Non-negative Integers');\nend\na=factorial(n:-1:1);\nif b>a;\n error('PERMS1:brange','Input Parameter b Should be between 1 and n!')\nend;\n\np=zeros(1,n); %initialize output variable\nidx=ones(1,n); %initialize loop counters\nid=find(a\nif exist('OCTAVE_VERSION', 'builtin')\n x = x * 1.0;\n if (exist('L'))\n [y,L] = omdwt(x,h,L);\n else \n [y,L] = omdwt(x,h);\n end\nelse\n error('You must compile wavelet toolbox before use')\nend\n", "meta": {"author": "ricedsp", "repo": "D-AMP_Toolbox", "sha": "6e597d98c84755697b65554d59485d50a549c01a", "save_path": "github-repos/MATLAB/ricedsp-D-AMP_Toolbox", "path": "github-repos/MATLAB/ricedsp-D-AMP_Toolbox/D-AMP_Toolbox-6e597d98c84755697b65554d59485d50a549c01a/Packages/rwt/bin/mdwt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.9173026505426832, "lm_q1q2_score": 0.8553418968904469}} {"text": "%% Unstructured Grid\n% This examples shows how to use ConstructProjector2D on unstructured\n% grids. Two sets of points are generated randomly. \nclear;clc;\n%% Initializing Part I\ndisp('- Initializing')\nrSource=2*pi;\nrDestination=rSource*1.05; % This slightly bigger radius causes some points\n % on destination grid being outside of the\n % source grid; hence, on those points it is\n % actually extrapolation and not interpolation.\n\nns=300;\nnd=50;\n\nnPoly=4; % We gonna fit a fourth order polynomial, \n % i.e. sum_{n,m=0}^{n,m=nPoly} x^n*y^m \nnInterp=35; % nPoly=4 requires 25 points. However, \n % we are going to use 35 points. This would be \n % the least-square fit of the surface.\n % Note that: min(nInterp)=(nPoly+1)^2. Otherwise it won't work.\n%% Generating the Source grid\ndisp('- Generating the Source grid')\nxs=rand(ns,1)*2*rSource-rSource;\nys=rand(ns,1)*2*rSource-rSource;\n\n%% Generating the Destination Grid\ndisp('- Generating the Destination Grid')\nxd=rand(nd,1)*2*rDestination-rDestination;\nyd=rand(nd,1)*2*rDestination-rDestination;\n\nfigure\nplot(xs,ys,'b.');\nhold on\nplot(xd,yd,'k.');\naxis tight\naxis square\nlegend('Source Grid','Destination Grid')\ntitle('Distribution of the points')\n\n%% Generating the interpolant\ndisp('- Generating the interpolant')\nP=ConstructProjector2D(xs,ys,xd,yd,nPoly,nInterp);\n\n%% Generating sum data\ndisp('- Generating sum data and interpolating')\nF1=@(x,y) (sin(sqrt(x.^2+y.^2)));\nF2=@(x,y) (sin(x).*cos(y));\nF3=@(x,y) (exp(-sqrt(x.^2+y.^2)));\nF4=@(x,y,x0,y0) (exp(-sqrt((x-x0).^2+(y-y0).^2)));\n\nz=zeros(ns,4);\nz(:,1)=F1(xs,ys);\nz(:,2)=F2(xs,ys);\nz(:,3)=F3(xs,ys);\nz(:,4)=F4(xs,ys,0,0);\n\nz_Analytic=zeros(nd,4);\nz_Analytic(:,1)=F1(xd,yd);\nz_Analytic(:,2)=F2(xd,yd);\nz_Analytic(:,3)=F3(xd,yd);\nz_Analytic(:,4)=F4(xd,yd,0,0);\n\n% Interpolating\nz_interp=P*z;\n\n% Note that since the points are randomly generated the RMSE would change\n% each time. Depending on how the points are distributed you may get very\n% good or very bad RMSE.\nRMSE=sqrt(mean( (z_interp-z_Analytic).^2 ));\n\n%% plotting\nfigure\nfor i=1:4\n subplot(2,2,i)\n plot(z_interp(:,i),'b.');\n hold on\n plot(z_Analytic(:,i),'r.');\n legend('Interpolated','Analytic');\n title(['RMSE= ' num2str(RMSE(i))]);\nend\n\n\n\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/41669-interpolantextrapolant-2d3d-data/Projector/Test_UnstructuredGrid_2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.9173026522382527, "lm_q1q2_score": 0.8553418915841082}} {"text": "classdef BernoulliD\n%%BERNOULLID Functions to handle the Bernoulli distribution. This is just a\n% binary distribution having a certain probability p of being 1.\n%Implemented methods are: mean, var, PMF, CDF, rand, momentGenFun, entropy\n%\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nmethods(Static)\nfunction val=mean(p)\n%%MEAN Obtain the mean of the Bernoulli distribution.\n%\n%INPUTS: p The probability of success of a Bernoulli trial.\n%\n%OUTPUTS: val The mean of the Bernoulli distribution.\n%\n%As noted on the page opposite the inside front cover of [1], the mean is\n%just p.\n%\n%EXAMPLE:\n%We show that the mean matches the sample mean.\n% p=0.75;\n% meanVal=BernoulliD.mean(p)\n% numRuns=1e6;\n% meanSamp=mean(BernoulliD.rand([numRuns,1],p))\n%One will see that both values are about 0.75.\n%\n%REFERENCES:\n%[1] A. Papoulis and S. U. Pillai, Probability, Random Variables and\n% Stochastic Processes, 4th ed. Boston: McGraw Hill, 2002.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C. \n \n val=p;\nend\n\nfunction val=var(p)\n%%VAR Obtain the variance of the Bernoulli distribution.\n%\n%INPUTS: p The probability of success of a Bernoulli trial.\n%\n%OUTPUTS: val The variance of the Bernoulli distribution.\n%\n%As noted on the page opposite the inside front cover of [1], the mean is\n%just p*(1-p).\n%\n%EXAMPLE:\n%We show that the mean matches the sample mean.\n% p=0.75;\n% varVal=BernoulliD.var(p)\n% numRuns=1e6;\n% varSamp=var(BernoulliD.rand([numRuns,1],p))\n%One will see that both values are about 0.1875.\n%\n%REFERENCES:\n%[1] A. Papoulis and S. U. Pillai, Probability, Random Variables and\n% Stochastic Processes, 4th ed. Boston: McGraw Hill, 2002.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C. \n\n val=p*(1-p); \nend\n\nfunction val=PMF(x,p)\n%%PMF Evaluate the Bernoulli probability mass function (PMF) at given\n% points.\n%\n%INPUTS: x The point(s) at which the Bernoulli PMF is to be evaluated. For\n% nonzero PMF values, x=0 or x=1.\n% p The probability of success of a Bernoulli trial.\n%\n%OUTPUTS: val The value(s) of the Bernoulli PMF.\n%\n%The Bernoulli distribution is given on the page opposite the inside front\n%cover of [1].\n%\n%REFERENCES:\n%[1] A. Papoulis and S. U. Pillai, Probability, Random Variables and\n% Stochastic Processes, 4th ed. Boston: McGraw Hill, 2002.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=zeros(size(x));\n val(x==0)=1-p;\n val(x==1)=p;\nend\n \nfunction val=CDF(x,p)\n%%CDF Evaluate the cumulative distribution function of the Bernoulli\n% distribution at desired points.\n%\n%INPUTS: x The point(s) at which the Bernoulli PMF is to be evaluated. For\n% nonzero PMF values, x=0 or x=1.\n% p The probability of success of a Bernoulli trial.\n%\n%OUTPUTS: val The CDF of the Bernoulli distribution evaluated at the\n% desired point(s).\n%\n%The Bernoulli distribution is given on the page opposite the inside front\n%cover of [1].\n%\n%REFERENCES:\n%[1] A. Papoulis and S. U. Pillai, Probability, Random Variables and\n% Stochastic Processes, 4th ed. Boston: McGraw Hill, 2002.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=zeros(size(x));\n sel=(0<=x|x<1);\n val(sel)=1-p;\n sel=(x>=1);\n val(sel)=p;\nend\n\nfunction x=rand(N,p)\n%%RAND Generate Bernoulli random variables with a given mean.\n%\n%INPUTS: N If N is a scalar, then rand returns an NXN matrix of random\n% variables. If N=[M,N1] is a two-element row vector, then rand\n% returns an MXN1 matrix of random variables.\n% p The probability of success of a Bernoulli trial.\n%\n%OUTPUTS: vals A matrix whose dimensions are determined by N of the\n% generated Bernoulli random variables.\n%\n%The Bernoulli random variables are generated simply using the comparison\n%mentioned in Chapter 4 of [1]. [1].\n%\n%REFERENCES:\n%[1] S. M. Ross, Simulation, 4th ed. Amsterdam: Academic Press, 2006.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n \n if(isscalar(N))\n dims=[N, N];\n else\n dims=N;\n end\n \n x=rand(dims)<=p;\nend\n\nfunction momentVal=momentGenFun(p,numDerivs,t)\n%%MOMENTGENFUN Evaluate the moment generating function (or one of its\n% derivatives) of the Bernoulli distribution. Taking the kth\n% derivative of the moment generating function and evaluating\n% it at t=0 provides the kth noncentral moment of the\n% distribution.\n%\n%INPUTS: p The probability of success of a Bernoulli trial.\n% numDerivs The number of derivatives to take with respect to the\n% argument of the moment generating function. numDerivs>=0.\n% t The matrix of points where the moment generating function\n% should be evaluated. If this parameter is omitted or an\n% empty matrix is passed, the default value of 0 is used.\n%\n%OUTPUTS: momentVal A numPointsX1 vector of the values of the derivatives\n% of the moment generating function given at the points\n% in t or at t=0 if t is omitted.\n%\n%The moment generating function of a random variable is defined to be\n%E(exp(t*x)) where E is the expected value operator, x is the random\n%variable and t is a real parameter. The moment generating function for the\n%Bernoulli distribution is just (1-p)+p*exp(t). Derivatives are\n%straightforward.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n if(nargin<3||isempty(t))\n t=0; \n end\n\n momentVal=exp(t)*p;\n sel=numDerivs==0;\n momentVal(sel)=momentVal(sel)+1-p;\nend\n\nfunction entropyVal=entropy(p)\n%%ENTROPY Obtain the Shannon entropy of the Bernoulli distribution given in\n% nats. The Shannon entropy of a discrete distribution is\n% entropy=-sum_x Pr(x)*log(Pr(x)) where the sum is over all\n% discrete values of x. Units of nats mean that the natural\n% logarithm is used in the definition.\n%\n%INPUTS: p The probability of success of a Bernoulli trial.\n%\n%OUTPUTS: entropyVal The value of the Shannon entropy in nats.\n%\n%Shannon entropy is defined in Chapter 2 of [1].\n%\n%REFERENCES:\n%[1] T. M. Cover and J. A. Thomas, Elements of Information Theory, 2nd ed.\n% Hoboken, NJ: Wiley-Interscience, 2006.\n%\n%April 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n \n if(p==0||p==1)\n entropyVal=0;\n return;\n end\n\n q=1-p;\n\n entropyVal=-q*log(q)-p*log(p);\nend\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/Distributions/BernoulliD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.9099070005411123, "lm_q1q2_score": 0.855233739971689}} {"text": "classdef NegativeBinomialD\n%%NEGATIVEBINOMIALD Functions to handle the negative binomial\n% distribution. The Polya distribution and the Pascal\n% distribution are special cases of this distribution. The\n% negative binomial distribution is the number of sucesses in\n% independent trials before a specified number of failures\n% occurs.\n%Implemented methods are: mean, var, PMF, CDF, rand\n%\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n \nmethods(Static)\n\nfunction val=mean(r,p)\n%%MEAN Obtain the mean of the negative binomial distribution.\n% \n%INPUTS: r This is the integer number of failed trials until sampling stops\n% (defining the distribution).\n% p This is the probability of success for each trial.\n%\n%OUTPUTS: val The mean of the distribution.\n%\n%The negative binomial distribution is discussed in Chapter 4 of [1].\n%\n%EXAMPLE:\n%We verify the computed mean by comparing it to the sample mean.\n% p=0.8;\n% r=4;\n% meanVal=NegativeBinomialD.mean(r,p)\n% numSamp=1e5;\n% sampMeanVal=mean(NegativeBinomialD.rand([1,numSamp],r,p))\n%One will find both values are about 16.\n%\n%REFERENCES:\n%[1] A. Papoulis and S. U. Pillai, Probability, Random Variables and\n% Stochastic Processes, 4th ed. Boston: McGraw Hill, 2002.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=p*r/(1-p);\nend\n\nfunction val=var(r,p)\n%%VAR Obtain the variance of the negative binomial distribution.\n% \n%INPUTS: r This is the integer number of failed trials until sampling stops\n% (defining the distribution).\n% p This is the probability of success for each trial.\n%\n%OUTPUTS: val The variance of the distribution.\n%\n%The negative binomial distribution is discussed in Chapter 4 of [1].\n%\n%EXAMPLE:\n%We verify the computed variance by comparing it to the sample variance.\n% p=0.8;\n% r=4;\n% varVal=NegativeBinomialD.var(r,p)\n% numSamp=1e5;\n% sampVarVal=var(NegativeBinomialD.rand([1,numSamp],r,p))\n%One will find both values are about 80.\n%\n%REFERENCES:\n%[1] A. Papoulis and S. U. Pillai, Probability, Random Variables and\n% Stochastic Processes, 4th ed. Boston: McGraw Hill, 2002.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=p*r/(1-p)^2;\nend\n\nfunction val=PMF(k,r,p)\n%%PMF Evaluate the probability mass function (PMF) of the negative binomial\n% distribution at given points.\n%\n%INPUTS: x The point(s) at which the negative binomial PMF is to be\n% evaluated. x is an integer. For nonzero PMF values, x>=r.\n% r This is the integer number of failed trials until sampling stops\n% (defining the distribution).\n% p This is the probability of success for each trial.\n%\n%OUTPUTS: val The value(s) of the negative binomial PMF.\n%\n%The negative binomial distribution is discussed in Chapter 4 of [1].\n\n%EXAMPLE:\n%Here, we validate the PMF by generating random samples and comparing the\n%PMF plot with a histogram of the random samples.\n% p=0.8;\n% r=4;\n% numSamples=1e5;\n% figure(1)\n% clf\n% histogram(NegativeBinomialD.rand([numSamples,1],r,p),'BinWidth',1,'Normalization','pdf')\n% hold on\n% x=0:80;\n% vals=NegativeBinomialD.PMF(x,r,p);\n% stem(x,vals,'linewidth',2)\n% h1=xlabel('x');\n% h2=ylabel('PDF(x)');\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%One will see that the histogram matches well with the plot.\n%\n%REFERENCES:\n%[1] A. Papoulis and S. U. Pillai, Probability, Random Variables and\n% Stochastic Processes, 4th ed. Boston: McGraw Hill, 2002.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=zeros(size(k));\n numEls=numel(val);\n \n constVal=(1-p)^r;\n for curEl=1:numEls\n if(k(curEl)>=0)\n val(curEl)=binomial(k(curEl)+r-1,k(curEl))*constVal*p^k(curEl);\n end\n end\nend\n\nfunction val=CDF(k,r,p)\n%%CDF Evaluate the cumulative distribution function (CDF) of the negative\n% binomial distribution at given points.\n%\n%INPUTS: x The point(s) at which the negative binomial CDF is to be\n% evaluated. x is an integer. For nonzero CDF values, x>=r.\n% r This is the integer number of failed trials until sampling stops\n% (defining the distribution).\n% p This is the probability of success for each trial.\n%\n%OUTPUTS: val The value(s) of the negative binomial CDF.\n%\n%The negative binomial distribution is discussed in Chapter 4 of [1]. The\n%CDF can be expressed in terms of a regularized incomplete beta function.\n%\n%EXAMPLE:\n%We validate the CDF value by comparing it to a value computed from random\n%samples.\n% p=0.8;\n% r=5;\n% x=16;\n% numSamples=1e5;\n% prob=NegativeBinomialD.CDF(x,r,p)\n% probSamp=mean(NegativeBinomialD.rand([numSamples,1],r,p)<=x)\n%One will find the values ot both be about 0.414.\n%\n%REFERENCES:\n%[1] A. Papoulis and S. U. Pillai, Probability, Random Variables and\n% Stochastic Processes, 4th ed. Boston: McGraw Hill, 2002.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C. \n \n val=1-betainc(p,k+1,r);\nend\n\nfunction vals=rand(N,r,p)\n%%RAND Generate negative binomial random variables.\n%\n%INPUTS: N If N is a scalar, then rand returns an NXN matrix of random\n% variables. If N=[M,N1] is a two-element row vector, then rand\n% returns an MXN1 matrix of random variables.\n% r This is the integer number of failed trials until sampling\n% stops (defining the distribution); r>0.\n% p This is the probability of success for each trial.\n%\n%OUTPUTS: vals A matrix whose dimensions are determined by N of the\n% generated negative binomial random variables.\n%\n%The negative binomial distribution arises from a Poisson distribution\n%whose mean is a random variable having a central gamma distribution. This\n%relationship is briefly mentioned in [1] and can be easily derived. Thus,\n%this function generates gamma random variables and then generates poisson\n%random variables.\n%\n%REFERENCES:\n%[1] M. H. Quenouille, \"A relation between the logarithmic, Poisson, and\n% negative binomial distributions,\" Biometrics, vol. 5, no. 2, pp.\n% 162-164, Jun. 1949.\n%\n%March 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n if(isscalar(N))\n dims=[N, N];\n else\n dims=N;\n end\n\n lambda=GammaD.rand(dims,r,p/(1-p));\n\n numEls=numel(lambda);\n \n vals=zeros(size(lambda));\n for curEl=1:numEls\n vals(curEl)=PoissonD.rand(1,lambda(curEl));\n end\nend\nend\nend", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/Distributions/NegativeBinomialD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846919, "lm_q2_score": 0.9073122182277756, "lm_q1q2_score": 0.855147862440971}} {"text": "function t = tvec_even2 ( nt )\n\n%*****************************************************************************80\n%\n%% TVEC_EVEN2 computes an evenly spaced set of angles between 0 and 2*PI.\n%\n% Discussion:\n%\n% The computation realizes that 0 = 2 * PI. The values are equally\n% spaced in the circle, do not include 0, and are symmetric about 0.\n%\n% Example:\n%\n% NT = 4\n%\n% T = ( PI/4, 3*PI/4, 5*PI/4, 7*PI/4 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 20 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NT, the number of values to compute.\n%\n% Output, real TVEC(NT), the evenly spaced angles, in radians.\n%\n t(1:nt) = ( 1:2:(2*nt-1) ) * pi / nt;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/tvec_even2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.9032942125614059, "lm_q1q2_score": 0.8550552979042889}} {"text": "function J = computeCost(X, y, theta)\n%COMPUTECOST Compute cost for linear regression\n% J = COMPUTECOST(X, y, theta) computes the cost of using theta as the\n% parameter for linear regression to fit the data points in X and y\n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost of a particular choice of theta\n% You should set J to the cost.\n\nJ = 1 / (2 * m) * (X * theta - y)' * (X * theta - y);\n\n\n\n% =========================================================================\n\nend\n", "meta": {"author": "JY-112553", "repo": "machine-learning", "sha": "db9c6e5a5175739821acd97787453472b8f46cac", "save_path": "github-repos/MATLAB/JY-112553-machine-learning", "path": "github-repos/MATLAB/JY-112553-machine-learning/machine-learning-db9c6e5a5175739821acd97787453472b8f46cac/machine-learning-ex1/ex1/computeCost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9585377320263431, "lm_q2_score": 0.8918110396870287, "lm_q1q2_score": 0.8548345313776595}} {"text": "% quantile() - computes the quantiles of the data sample from a distribution X\n%\n% Description:\n% If F is the cumulative distribution function (CDF) of X,\n% the p-th-quantile Qp of distribution X is the value for which holds\n% F(x) < p, for x < Qp, and \n% F(x) >= p, for x >= Qp.\n% for example, for p = 0.5, Qp is the median of X. p must be in [0..1].\n%\n% Usage:\n% >> q = quantile( data, pc );\n%\n% Inputs:\n% data - vector of observations\n% pc - the quantiles will be estimated at the values in pc [0..1]\n% \n% Outputs:\n% q - pc-th-quantiles of the distribution generating the observation\n%\n% Authors: Scott Makeig & Luca Finelli, CNL/Salk Institute-SCCN, August 21, 2002\n%\n% Note: this function overload the function from the statistics toolbox. In\n% case the statistic toolbox is present, the function from the\n% statistics toolbox is being called instead.\n%\n% See also: \n% pop_sample(), eeglab() \n\n% Copyright (C) Scott Makeig & Luca Finelli, CNL/Salk Institute-SCCN, August 21, 2002\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\nfunction q = quantile(data,varargin); \n\n% detect overloaded method in stat toolbox\ncurPath = fileparts(which('quantile'));\nrmpath(curPath);\npath2 = fileparts(which('quantile'));\naddpath(curPath);\nif ~isempty(path2)\n addpath(path2);\n q = quantile(data,varargin{:});\n return;\nelse\n pc = varargin{1};\nend;\n\nif nargin < 2\n\thelp quantile;\n\treturn;\nend;\t\n\n[prows pcols] = size(pc);\nif prows ~= 1 & pcols ~= 1\n error('pc must be a scalar or a vector.');\nend\nif any(pc > 1) | any(pc < 0)\n error('pc must be between 0 and 1');\nend\n[i,j] = size(data);\nsortdata = sort(data);\nif i==1 | j==1 % if data is a vector\n i = max(i,j); j = 1;\n if i == 1,\n fprintf(' quantile() note: input data is a single scalar!\\n')\n q = data*ones(length(pc),1); % if data is scalar, return it\n return;\n end\n sortdata = sortdata(:);\nend\npt = [0 ((1:i)-0.5)./i 1];\nsortdata = [min(data); sortdata; max(data)];\nq = interp1(pt,sortdata,pc);\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/eeglab14_0_0b/functions/sigprocfunc/quantile.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985936, "lm_q2_score": 0.9086179031191509, "lm_q1q2_score": 0.8548184077390293}} {"text": "function L=lebesque(x)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Computes the Lebesgue coefficient for a set of nodes on an interval\n%\n% References:\n%\n% (1) Jean-Paul Berrut & Lloyd N. Trefethen, \"Barycentric Lagrange \n% Interpolation\" \n% http://web.comlab.ox.ac.uk/oucl/work/nick.trefethen/berrut.ps.gz\n% (2) Walter Gaustschi, \"Numerical Analysis, An Introduction\" (1997) p. 76+\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Get number of nodes\nn=length(x);\n\n% use this finer mesh for interpolating between nodes\nN=8*n+1;\n\nx=x(:);\n\nX=repmat(x,1,n);\n\n% Compute the weights\nw=1./prod(X-X'+eye(n),2);\n\n% Fine mesh for interpolating \nxp=linspace(min(x),max(x),N)';\n\nxdiff=repmat(xp.',n,1)-repmat(x,1,N);\n\n% find all the points where the difference is zero\nzerodex=(xdiff==0); \n\n% See eq. 3.1 in Ref (1)\nlfun=prod(xdiff,1);\n\n% kill zeros\nxdiff(zerodex)=eps;\n\n% Compute lebesgue function\nlebfun=sum(abs(diag(w)*repmat(lfun,n,1)./xdiff));\nplot(xp,lebfun);\nL=max(lebfun);\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/4478-barycentric-lagrange-interpolating-polynomials-and-lebesgue-constant/lebesgue.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750453562491, "lm_q2_score": 0.8962513835254865, "lm_q1q2_score": 0.8543740782808591}} {"text": "function D = diffmat(N, varargin)\n%DIFFMAT Spectral differentiation matrix.\n% D = DIFFMAT(N) returns the N x N differentiation matrix associated with the\n% Chebyshev spectral collocation method at second-kind Chebyshev points. \n%\n% D = DIFFMAT(N, P) returns the N x N differentiation matrix of order P.\n%\n% D = DIFFMAT(N, P, DOM) scales the differentiation matrix D to the domain\n% DOM. DOM should be a 1x2 vector.\n%\n% D = DIFFMAT(N, P, DOM, GRID) returns the square differentiation matrix on \n% grid specified by GRID. The specifier GRID can be 'chebkind1' (first-kind \n% Chebyshev grid) or 'chebkind2' (second-kind Chebyshev grid) or 'leg' \n% (Legendre grid).\n%\n% D = DIFFMAT(N, P, DOM, GRID, LBC, RBC) returns the square differentiation \n% matrix on grid GRID with the corresponding row(s) replaced by boundary \n% conditions specified by string specifiers LBC and RBC for the left and right \n% boundary respectively. The specifier LBC and RBC can be any of 'dirichlet', \n% 'neumann', and 'sum' with 'dirichlet' and 'neumann' indicating Dirichlet and\n% Neumann boundary conditions respectively. The string 'sum' indicates a side \n% condition of definite integral i.e., sum(U), where U is the implied solution \n% to the system formed by D. For a differentiation matrix of order higher than\n% 1, if there are multiple boundary conditions at one boundary, the \n% corresponding specifiers need to be grouped in a cell using curly brackets. \n% If there is no boundary condition at a boundary, then it needs to be \n% indicated by either an empty array, i.e. [], or an empty cell, i.e. {}. Note\n% that the number of the boundary conditions given by LBC and RBC must total \n% P, i.e. the order of differentiation, otherwise an error is thrown. Also \n% note that RBC can be omitted if there are only left boundary conditions.\n%\n% Example 1: D = DIFFMAT(N, 1, DOM, GRID, [], 'dirichlet') replaces the last \n% row of an N x N differentiation matrix by a Dirichlet boundary condition.\n%\n% Example 2: D = DIFFMAT(N, 1, DOM, GRID, 'dirichlet') replaces the first \n% row of an N x N differentiation matrix by a Dirichlet boundary condition.\n%\n% Example 3: D = DIFFMAT(N, 2, DOM, GRID, 'dirichlet', 'neumann') replaces\n% the first and last rows of an N x N differentiation matrix by a Dirichlet \n% and a Neumann boundary conditions respectively.\n%\n% Example 4: D = DIFFMAT(N, 3, DOM, GRID, 'dirichlet', {'dirichlet' 'neumann'}) \n% replaces the first row of an N x N differentiation matrix by a Dirichlet\n% boundary condition and the last two rows by Dirichlet and Neumann boundary \n% conditions.\n%\n% D = DIFFMAT(N, 'periodic') returns the N x N first-order Fourier \n% differentiation matrix on the default interval [-1 1]. The tag\n% 'periodic' can be replaced by 'trig'.\n%\n% D = DIFFMAT(N, P, 'periodic') returns the N x N Fourier differentiation \n% matrix of order P on the default interval [-1 1].\n%\n% D = DIFFMAT(N, P, 'periodic', DOM) scales the Pth-order Fourier \n% differetiation matrix to domain DOM.\n%\n% The remaining options concern rectangular spectral differentiation matrices,\n% as introduced in [Driscoll & Hale 2014]. Chebfun uses these to solve ODE\n% boundary value problems in the mode GRID1 = 'chebkind2', GRID2 =\n% 'chebkind1'. See also [Xu & Hale 2014].\n%\n% D = DIFFMAT([M N]) returns the M x N first-order rectangular differentiation \n% matrix which maps from an N-point Chebyshev grid of the second kind to an \n% M-point Chebyshev grid of the same kind.\n% \n% D = DIFFMAT([M N], P) returns an M x N rectangular differentiation matrix of \n% order P which maps from an N-point to an M-point Chebyshev grid, both of\n% second kind.\n%\n% D = DIFFMAT([M N], P, DOM) returns the same D but scaled to the domain DOM.\n%\n% D = DIFFMAT([M N], P, DOM, GRID) returns an M x N first-order rectangular \n% differentiation matrix which maps from an N-point grid of type GRID to an \n% M-point grid of the same type. The specifier GRID can be 'chebkind1', \n% 'chebkind2', or 'leg'.\n%\n% D = DIFFMAT([M N], P, DOM, GRID1, GRID2) returns an M x N first-order \n% rectangular differentiation matrix which maps from an N-point grid of type \n% GRID1 to an M-point grid of type GRID2. The specifier GRID1 and GRID2 can be\n% any of 'chebkind1', 'chebkind2', and 'leg'.\n%\n% D = DIFFMAT(N, P, DOM, GRID1, GRID2, LBC, RBC) returns a square \n% differentiation matrix which is squared up and deflated by appending \n% boundary conditions specified by string specifiers LBC and RBC for the left \n% and the right boundary respectively. \n%\n% Example: D = DIFFMAT([M N], P, DOM, GRID1, GRID2, {}, {'neumann' 'sum'}) \n% appends two rows to an M x N rectangular differentiation matrix to square it \n% up. The first appended row corresponds to a Neumann boundary condition at \n% the right endpoint while the second appended row corresponds to a side \n% condition sum(U) = I for a scalar I, where U is the solution to the \n% resulting system.\n%\n% See also DIFF, CHEBCOLLOC2.DIFFMAT, CUMSUMMAT, DIFFROW, INTMAT, INTROW.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% References for rectangular differentiation matrices:\n%\n% Driscoll, T. and Hale, N., Rectangular spectral collocation, submitted 2014.\n%\n% Xu, K. and Hale, N., Explicit construction of rectangular differentiation\n% matrices, submitted 2014.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% Parse the inputs:\n[m, n, p, dom, bc, nlbc, nrbc, mapFrom, mapTo] = parseInputs(N, varargin{:});\n\n%% Different cases:\nif ( strcmpi(mapFrom, mapTo) && ( m == n ) ) % Square case:\n if ( strcmpi(mapFrom, 'chebkind1') )\n D = chebcolloc1.diffmat(n, p);\n elseif ( strcmpi(mapFrom, 'chebkind2') )\n D = chebcolloc2.diffmat(n, p);\n elseif ( strcmpi(mapFrom, 'periodic') )\n D = trigcolloc.diffmat(n, p);\n else\n [x, ignored, v] = legpts(n); %#ok\n [y, ignored, w] = chebpts(n); %#ok\n z = legpts(n);\n P1 = barymat(y, x, v);\n P2 = barymat(z, y, w);\n D = chebcolloc2.diffmat(n, p);\n D = P2*D*P1;\n \n % Flipping trick for symmetry:\n d = diag(rot90(D));\n d = sign(d).*(abs(d) + abs(flipud(d)))/2;\n D(logical(flipud(eye(N)))) = d;\n DRot = rot90(D, 2);\n idxTo = rot90(~triu(ones(N)));\n D(idxTo) = (-1)^p*DRot(idxTo);\n if ( mod(N, 2) == 1 )\n D((N+1)/2,(N+1)/2) = 0;\n end\n end\n \nelseif ( strcmpi(mapTo, 'chebkind1') )\n \n if ( strcmpi(mapFrom, 'chebkind1') )\n if ( p == 1 )\n D = rectdiff1(m, n);\n else\n D = rectdiff_rec(m, n, p, 1);\n end\n elseif ( strcmpi(mapFrom, 'chebkind2') )\n if ( p == 1 )\n D = rectdiff2(m, n);\n else\n D = rectdiff_rec(m, n, p, 2);\n end\n else\n [x, ignored, v] = legpts(n); %#ok\n [y, ignored, w] = chebpts(n); %#ok\n z = chebpts(m, 1);\n P1 = barymat(y, x, v);\n P2 = barymat(z, y, w);\n D = chebcolloc2.diffmat(n, p);\n D = P2*D*P1;\n end\n \nelseif ( strcmpi(mapTo, 'chebkind2') )\n [z, ignored, ignored, s] = chebpts(m); %#ok\n if ( strcmpi(mapFrom, 'chebkind1') )\n D = chebcolloc1.diffmat(n, p);\n [x, ignored, v, r] = chebpts(n, 1); %#ok\n P = barymat(z, x, v, s, r, 1);\n D = P*D;\n elseif ( strcmpi(mapFrom, 'chebkind2') )\n D = chebcolloc2.diffmat(n, p);\n [x, ignored, v, r] = chebpts(n); %#ok\n P = barymat(z, x, v, s, r, 1);\n D = P*D;\n else\n [x, ignored, v] = legpts(n); %#ok\n [y, ignored, w] = chebpts(n); %#ok\n P1 = barymat(y, x, v);\n P2 = barymat(z, y, w);\n D = chebcolloc2.diffmat(n, p);\n D = P2*D*P1;\n end\n \nelseif ( strcmpi(mapTo, 'leg') )\n z = legpts(m);\n if ( strcmpi(mapFrom, 'chebkind1') )\n D = chebcolloc1.diffmat(n, p);\n [x, ignored, v] = chebpts(n, 1); %#ok\n P = barymat(z, x, v);\n D = P*D;\n elseif ( strcmpi(mapFrom, 'chebkind2') )\n D = chebcolloc2.diffmat(n, p);\n [x, ignored, v] = chebpts(n); %#ok\n P = barymat(z, x, v);\n D = P*D;\n else\n [x, ignored, v] = legpts(n); %#ok\n [y, ignored, w] = chebpts(n); %#ok\n P1 = barymat(y, x, v);\n P2 = barymat(z, y, w);\n D = chebcolloc2.diffmat(n, p);\n D = P2*D*P1;\n end\n \nend\n\n%% Rescaling:\nscl = (2/(dom(end) - dom(1)))^p;\nD = scl*D;\n\n%% Boundary conditions:\nif ( ~isempty(bc) )\n nbc = nlbc + nrbc;\n BC = zeros(nbc, n);\n for j = 1:nbc\n if ( j <= nlbc )\n z = -1;\n r = pi;\n idx = 1;\n else\n z = 1;\n r = 0;\n idx = n;\n end\n \n switch bc{j}\n case 'dirichlet'\n if ( strcmpi(mapFrom, 'chebkind1') )\n [x, ignored, v, t] = chebpts(n, 1); %#ok\n BC(j,:) = barymat(z, x, v, r, t);\n elseif ( strcmpi(mapFrom, 'chebkind2') )\n I = eye(n);\n BC(j,:) = I(idx,:);\n else\n [x, ignored, v] = legpts(n); %#ok\n BC(j,:) = barymat(z, x, v);\n end\n \n case 'neumann'\n \n if ( strcmpi(mapFrom, 'chebkind1') )\n DD = diffmat(n, 1, dom, 'chebkind1');\n [x, ignored, v, t] = chebpts(n, 1); %#ok\n P = barymat(z, x, v, r, t);\n DD = P*DD;\n BC(j,:) = DD;\n elseif ( strcmpi(mapFrom, 'chebkind2') )\n DD = diffmat(n, 1, dom);\n BC(j,:) = DD(idx,:);\n else\n DD = diffmat(n, 1, dom);\n [x, ignored, v] = legpts(n); %#ok\n y = chebpts(n);\n P = barymat(y, x, v);\n DD = DD*P;\n BC(j,:) = DD(idx, :);\n end\n \n case 'sum'\n \n if ( strcmpi(mapFrom, 'chebkind1') )\n [ignored, w] = chebpts(n, dom, 1); %#ok\n elseif ( strcmpi(mapFrom, 'chebkind2') )\n [ignored, w] = chebpts(n, dom); %#ok\n else\n [ignored, w] = legpts(n, dom); %#ok\n end\n \n BC(j,:) = w;\n \n otherwise\n error('CHEBFUN:diffmat:wrongBC', ...\n 'Unknown type of boundary conditions.');\n end\n end\nend\n\n%% Replace or append the boundary conditions:\nif ( ~isempty(bc) && ( m == n ) )\n % Replacement for square case:\n D(1:nlbc, :) = BC(1:nlbc, :);\n D(end-nrbc+1:end,:) = BC(nlbc+1:end,:);\nelseif ( ~isempty(bc) )\n D = [BC(1:nlbc,:); D; BC(nlbc+1:end,:)];\nend\n\nend\n\n\nfunction D = rectdiff1(m, n)\n%RECTDIFF1 Explicit constrcution of 1st-order rectangular differentiation \n%matrix mapping from 1st-kind grid.\n\n% mapping-from grid (angles):\nT = chebtech1.angles(n).';\n\n% difference between dimensions:\nc = n-m;\n\n% mapping-to grid (angles):\nTAU = chebtech1.angles(m);\n\n% Denominator:\ndenom = bsxfun(@(u,v) 2*sin((v+u)/2).*sin((v-u)/2), T, TAU);\n\n% Sign:\nsgn = ones(m, n);\nif ( mod(c, 2) )\n sgn(1:2:end,2:2:end) = -1;\n sgn(2:2:end,1:2:end) = -1;\nelse\n sgn(1:2:end,1:2:end) = -1;\n sgn(2:2:end,2:2:end) = -1;\nend\n\nD = sgn.*((cos(c*TAU)./sin(TAU))*sin(T)-sin(c*TAU)/n*sin(T)./denom)./denom;\n\n% indices for applying negative-sum trick: \n[~, idx] = min(abs(denom), [], 2);\nidx = sub2ind([m n], 1:m, idx.');\nD(idx) = 0;\nD(idx) = -sum(D, 2);\n\nif ( c == 1 )\n % Flipping trick:\n ii = logical(rot90(tril(ones(m, n)), 2));\n rot90D = rot90(D,2);\n D(ii) = -rot90D(ii);\nend\n\nend\n\nfunction D = rectdiff2(m, n)\n%RECTDIFF2 Explicit constrcution of 1st-order rectangular differentiation \n%matrix mapping from a 2nd-kind grid.\n\nnm1 = n - 1; % For convenience.\ncm1 = nm1 - m; % Difference between dimensions:\nt = chebpts(n).'; % Second-kind grid.\ntau = chebpts(m, 1); % First-kind grid.\nT = chebtech2.angles(n).'; % Second-kind grid (angles).\nTAU = chebtech1.angles(m); % First-kind grid (angles).\n\n% Explicit expression:\ndenom = 2*bsxfun( @(u,v) sin((v+u)/2) .* sin((v-u)/2), T, TAU );\nnumer = bsxfun( @times, 1 - tau*t, cos(cm1*TAU)./sin(TAU) );\n\nsgn = (-1)^cm1;\n\nif ( cm1 == 0 )\n D = numer ./ denom.^2 / nm1;\nelse\n D = repmat(sin(cm1*TAU), 1, n)./denom + numer./denom.^2 / nm1;\n D = sgn*D;\nend\nD(:,[1,n]) = .5*D(:,[1,n]); % Scaling for first and last columns.\n\nif ( cm1 == 0 )\n % Flipping trick:\n ii = logical(rot90(tril(ones(m, n)), 2));\n rot90D = rot90(D,2);\n D(ii) = sgn*rot90D(ii);\nend\n\n% Sign:\nD(1:2:end,1:2:end) = -D(1:2:end,1:2:end);\nD(2:2:end,2:2:end) = -D(2:2:end,2:2:end);\n\n% Negative sum trick:\n[~, idx] = min(abs(denom), [], 2); \nidx = sub2ind([m n], 1:m, idx.');\nD(idx) = 0; D(idx) = -sum(D, 2);\n\nif ( cm1 == 0 )\n % Fix corner values:\n D(1) = -.25/(nm1*sin(pi/(2*m))*sin(pi/(4*m))^2); D(end) = -D(1);\n % Negative sum trick for corner entries:\n D(1,2) = -sum(D(1,[1 3:end])); D(end,end-1) = -D(1,2);\nend\n\nend\n \nfunction D = rectdiff_rec(m, n, p, kind)\n%Recursive construction for high-order rectangular differentiation matrices\n\n% Sign and scaling:\nsgn = ones(1, n);\nsgn(1:2:end) = -1;\n\nif ( kind == 1 )\n % mapped-from angles (1st-kind):\n T = chebtech1.angles(n).';\n \n % Compute the first order diff matrix:\n D = rectdiff1(m, n);\n \n % Preparation for higher order (p>1):\n a = [zeros(n,1); 1];\n \n % Signs:\n sgn = (-1)^(n-1)*sgn.*sin(T)/n;\n \nelse\n % mapped-from grid (2nd-kind):\n T = chebtech2.angles(n).';\n \n % Compute the first order diff matrix:\n D = rectdiff2(m, n);\n \n % Preparation for higher order (p>1):\n a = [zeros(n-2,1); -1; 0; 1];\n \n % Signs:\n sgn = (-1)^(n-1)*sgn/(2*(n-1));\n sgn([1 n]) = sgn([1 n])/2;\n \nend\n\n% mapped-to grid (1st-kind):\ntau = chebpts(m, 1);\nTAU = chebtech1.angles(m);\n\na = computeDerCoeffs(a);\n\n% Denominator:\ndenom = bsxfun(@(u,v) 2*sin((v+u)/2).*sin((v-u)/2), T, TAU);\n\n% indices for applying negative-sum trick:\n[~, idx] = min(abs(denom), [], 2);\nidx = sub2ind([m n], 1:m, idx.');\n\n% Recursion for higher-order matrices:\nfor l = 2:p\n \n % Compute coefficients of the derivative of T_n:\n a = computeDerCoeffs(a);\n \n % Evaluating at tau by Clenshaw method:\n Tt = chebtech.clenshaw(tau, a);\n D = (Tt*sgn + l*D)./denom;\n \nend\n\n% negative-sum trick:\nD(idx) = 0;\nD(idx) = -sum(D, 2);\n\nend\n\nfunction cout = computeDerCoeffs(c)\n%COMPUTEDERCOEFFS Recurrence relation for coefficients of derivative.\n% C is the matrix of Chebyshev coefficients of a (possibly array-valued)\n% CHEBTECH object. COUT is the matrix of coefficients for a CHEBTECH object\n% whose columns are the derivatives of those of the original.\n \n [n, m] = size(c);\n cout = zeros(n-1, m); % Initialize vector {c_r}\n w = repmat(2*(1:n-1)', 1, m);\n v = w.*c(2:end,:); % Temporal vector\n cout(n-1:-2:1,:) = cumsum(v(n-1:-2:1,:)); % Compute c_{n-2}, c_{n-4},...\n cout(n-2:-2:1,:) = cumsum(v(n-2:-2:1,:)); % Compute c_{n-3}, c_{n-5},...\n cout(1,:) = .5*cout(1,:); % Adjust the value for c_0\nend\n\nfunction [m, n, p, dom, bc, nlbc, nrbc, mapFrom, mapTo] = parseInputs(N, varargin)\n% Parse the inputs to DIFFMAT.\n\np = 1;\ndom = [-1 1];\nmapFrom = [];\nmapTo = [];\nlbc = {};\nnlbc = 0;\nrbc = {};\nnrbc = 0;\nisLbcGiven = 0;\nisRbcGiven = 0;\n\nif ( isscalar(N) )\n n = N;\n m = n;\nelseif ( N(2) < 0 )\n n = N(1);\n m = n + N(2);\nelse\n m = N(1);\n n = N(2);\nend\n\nfor j = 1:numel(varargin)\n v = varargin{j};\n if ( isnumeric(v) )\n if ( isempty(v) )\n if ( ~isLbcGiven )\n lbc = {};\n isLbcGiven = 1;\n elseif ( ~isRbcGiven )\n rbc = {};\n isRbcGiven = 1;\n end\n elseif ( isscalar(v) )\n p = v;\n else\n dom = v;\n end\n elseif ( ischar(v) )\n switch v\n case 'rect'\n \n if ( strcmpi(mapFrom, 'periodic') )\n error('CHEBFUN:diffmat:wrongInput', ...\n ['Rectangular Fourier differentiation matrices are '...\n 'not supported.']);\n end\n \n if ( isscalar(N) )\n m = n - p;\n end\n \n case {'periodic', 'trig'}\n mapFrom = 'periodic';\n mapTo = 'periodic';\n if ( m ~= n )\n error('CHEBFUN:diffmat:wrongInput', ...\n ['Rectangular Fourier differentiation matrices are '...\n 'not supported.']);\n end\n \n case {'chebkind1', 'chebkind2', 'leg'}\n if ( isempty(mapFrom) )\n mapFrom = v;\n elseif ( isempty(mapTo) )\n mapTo = v;\n else\n error('CHEBFUN:diffmat:unknown', ...\n 'Too many inputs for grid type.');\n end\n \n case {'dirichlet', 'neumann', 'sum', []}\n if ( ~isLbcGiven )\n lbc = {v};\n isLbcGiven = 1;\n elseif ( ~isRbcGiven )\n rbc = {v};\n isRbcGiven = 1;\n else\n error('CHEBFUN:diffmat:unknown', ...\n ['Too many inputs for boundary condition. ' ...\n 'Use curly brackets to group left and right ' ...\n 'boundary conditions, if multiple boundary ' ...\n 'conditions are considered at one boundary.']);\n end\n otherwise\n error('CHEBFUN:diffmat:unknown', ['Unknown input ', v]);\n end\n\n elseif ( iscell(v) )\n if ( ~isLbcGiven )\n lbc = v;\n isLbcGiven = 1;\n elseif ( ~isRbcGiven )\n rbc = v;\n isRbcGiven = 1;\n else\n error('CHEBFUN:diffmat:unknown', ...\n 'Unrecognized boundary condition.');\n end\n else\n error('CHEBFUN:diffmat:unknown', ...\n 'Unknown input of type %s.', class(v));\n end\nend\n\n% If only one grid is given, then let \nif ( ~isempty(mapFrom) && isempty(mapTo) )\n mapTo = mapFrom;\nend\n\nif ( isempty(mapFrom) )\n mapFrom = 'chebkind2';\n mapTo = 'chebkind2';\nend \n\nif ( p < 0 )\n error('CHEBFUN:diffmat:wrongInput', ...\n 'The order of differentiation matrix must be non-negative.');\nend\n\n% No breakpoints allowed:\nif ( numel(dom) > 2 )\n dom = dom([1 end]);\n warning('CHEBFUN:diffmat:noBreaks', ...\n 'DIFFMAT does not support domains with breakpoints.');\nend\n\n% Boundary conditions:\nbc = [lbc rbc];\nif ( ~isempty(bc) )\n if ( isa(mapTo, 'periodic') )\n error('CHEBFUN:diffmat:wrongBC', ...\n ['For periodic functions, there is no need to specify boundary ' ...\n 'conditions.']);\n end\n nlbc = numel(lbc);\n nrbc = numel(rbc);\n nbc = nlbc + nrbc;\n if ( nbc ~= p )\n error('CHEBFUN:diffmat:wrongBC', ...\n ['The number of boundary conditions must match differentiation ' ...\n 'order p.']);\n end\nend\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/diffmat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.9124361622627654, "lm_q1q2_score": 0.8543002941845235}} {"text": "function value = ball_volume_3d ( r )\n\n%*****************************************************************************80\n%\n%% BALL_VOLUME_3D computes the volume of a ball in 3D.\n%\n% Integration region:\n%\n% Points (X,Y,Z) such that\n%\n% X**2 + Y**2 + Z**2 <= R**2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 20 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, the radius of the ball.\n%\n% Output, real BALL_VOLUME_3D, the volume of the ball.\n%\n value = ( 4.0E+00 / 3.0E+00 ) * pi * r * r * r;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/ball_volume_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9546474181553805, "lm_q2_score": 0.894789468908171, "lm_q1q2_score": 0.8542084562858095}} {"text": "function [q,qd,q2d] = fourier_series_traj(t,q0,A,B,w,N)\n% -----------------------------------------------------------------------\n% The function evaluates trancated Fourier series polynomial\n% Inputs:\n% t - time instantes at which the polynomail should be evaluated\n% q0 - initial offset, should be vector (nx1)\n% A - sine coefficients\n% B - cosine coefficients\n% w - fundamental frequency\n% N - number of harmonics\n% Outputs:\n% q - positions i.e. value of polynomial\n% qd - velocities i.e. derivative of polynomail\n% q2d - accelerations i.e. second derivative of polynomial\n% -----------------------------------------------------------------------\nq = q0;\nqd = zeros(size(q0));\nq2d = zeros(size(q0));\nfor k = 1:N\n q = q + A(:,k)/(w*k).*sin(w*k*t) - B(:,k)/(w*k).*cos(w*k*t);\n qd = qd + A(:,k).*cos(w*k*t) + B(:,k)*sin(w*k*t);\n q2d = q2d - A(:,k)*w*k.*sin(w*k*t) + B(:,k)*w*k*cos(w*k*t);\nend\n", "meta": {"author": "shamilmamedov", "repo": "dynamic_calibration", "sha": "11af40e7deb758ec080a175fed8fcdd6c99aca29", "save_path": "github-repos/MATLAB/shamilmamedov-dynamic_calibration", "path": "github-repos/MATLAB/shamilmamedov-dynamic_calibration/dynamic_calibration-11af40e7deb758ec080a175fed8fcdd6c99aca29/trajectory_optmzn/fourier_series_traj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639661317859, "lm_q2_score": 0.8791467627598856, "lm_q1q2_score": 0.8541473156389147}} {"text": "% interp1 举例\nclear; clc;\n\nxi=0:pi/5:2*pi; % 将插值区间分成若干等距小区间\nyi=sin(xi); % 插值节点处的函数值\n\nxh=0:pi/50:2*pi; % 需要插值的点\n\n% 分段线性插值\nsubplot(2,2,1)\nyh=interp1(xi,yi,xh); % 根据插值函数求出的近似值\nplot(xi,yi,'+r', xh,yh,'o-','LineWidth',1.5);\ntitle('分段线性插值','FontSize',18)\n\n% 分段零次插值\nsubplot(2,2,2)\nyh=interp1(xi,yi,xh,'nearst'); % 用邻近的值近似\nplot(xi,yi,'+r', xh,yh,'o-','LineWidth',1.5);\ntitle('分段零次插值','FontSize',18)\n\n% 分段三次 Hermite\nsubplot(2,2,3)\nyh=interp1(xi,yi,xh,'pchip'); \nplot(xi,yi,'+r', xh,yh,'o-','LineWidth',1.5);\ntitle('分段三次Hermite插值','FontSize',18)\n\n% 分段三次样条插值\nsubplot(2,2,4)\nyh=interp1(xi,yi,xh,'spline'); \nplot(xi,yi,'+r', xh,yh,'o-','LineWidth',1.5);\ntitle('分段三次样条插值','FontSize',18)\n\n", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/第二章 插值方法/demo_2_8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951703918909, "lm_q2_score": 0.8887587831798665, "lm_q1q2_score": 0.8540542670695889}} {"text": "function [x, y] = intline(x1, x2, y1, y2)\n%INTLINE Integer-coordinate line drawing algorithm.\n% [X, Y] = INTLINE(X1, X2, Y1, Y2) computes an\n% approximation to the line segment joining (X1, Y1) and\n% (X2, Y2) with integer coordinates. X1, X2, Y1, and Y2\n% should be integers. INTLINE is reversible; that is,\n% INTLINE(X1, X2, Y1, Y2) produces the same results as\n% FLIPUD(INTLINE(X2, X1, Y2, Y1)).\n\n% Copyright 1993-2002 The MathWorks, Inc. Used with permission.\n% $Revision: 1.4 $ $Date: 2003/11/21 14:38:20 $\n\ndx = abs(x2 - x1);\ndy = abs(y2 - y1);\n\n% Check for degenerate case.\nif ((dx == 0) & (dy == 0))\n x = x1;\n y = y1;\n return;\nend\n\nflip = 0;\nif (dx >= dy)\n if (x1 > x2)\n % Always \"draw\" from left to right.\n t = x1; x1 = x2; x2 = t;\n t = y1; y1 = y2; y2 = t;\n flip = 1;\n end\n m = (y2 - y1)/(x2 - x1);\n x = (x1:x2).';\n y = round(y1 + m*(x - x1));\nelse\n if (y1 > y2)\n % Always \"draw\" from bottom to top.\n t = x1; x1 = x2; x2 = t;\n t = y1; y1 = y2; y2 = t;\n flip = 1;\n end\n m = (x2 - x1)/(y2 - y1);\n y = (y1:y2).';\n x = round(x1 + m*(y - y1));\nend\n \nif (flip)\n x = flipud(x);\n y = flipud(y);\nend\n", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/《MATLAB图像处理》源文件/本书源文件/chap11/intline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.9149009555730611, "lm_q1q2_score": 0.8539967460549996}} {"text": "function points=regularNSimplexCoords(numDim,method)\n%%REGULARNSIMPLEXCOORDS Find the coordinates of a regular n-dimensional\n% simplex. That is, a hypertetrahedron in n-dimensions.\n% All sides in the simplex have equal length, the centroid of\n% the simplex is zero, and the distance of all of the points\n% in the simplex from the origin is 1.\n%\n%INPUTS: numDim The number of dimensions of the simplex. numDim>=1.\n% method The simplex is not unique (it can be rotated). If the\n% method parameter is specified, it selects which method of\n% finding a simplex is used. Possible values are\n% 0 (The default if omitted or an empty matrix is passed. Use\n% the method of [1], which utilizes cosines, is used.\n% 1 The method of [1] utilizing square roots instead of\n% cosines is used.\n%\n%OUTPUTS: points numDimXnumPoints set of points that form a\n% numDim-simplex. numPoints is always equal to numDim+1.\n%\n%The two methods given are from Chapter 9 of [1]. The methods do not\n%actually provide points that are a unit distance from the origin, though\n%they are all equidistant from the origin. Thus, this scales the points to\n%be a unit distance form the origin.\n%\n%REFERENCES:\n%[1] A.H. Stroud, Approximate Calculation of Multiple Integrals. Cliffs,\n% NJ: Prentice-Hall, Inc., 1971.\n%\n%December 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(method))\n method=0;\nend\n\nswitch(method)\n case 0%The method in [1] utilizing cosines\n points=zeros(numDim,numDim+1);\n\n r=1:fix(numDim/2);\n\n for k=0:numDim\n points(2*r-1,k+1)=cos(2*r*k*pi/(numDim+1));\n points(2*r,k+1)=sin(2*r*k*pi/(numDim+1));\n %For an odd number of dimensions\n if(mod(numDim,2)~=0)\n points(numDim,k+1)=(-1)^k/sqrt(2);\n end\n end\n points=points/sqrt(numDim/2);\n case 1%The method in [1] utilizing square roots.\n points=zeros(numDim,numDim+1);\n for k=1:(numDim+1)\n i=1:k;\n points(i,k)=-sqrt((numDim+1)./((numDim-i+2).*(numDim-i+1)));\n points(k,k)=sqrt((numDim+1)*(numDim-k+1)/(numDim-k+2));\n %Components for i>k are zero.\n end\n points=points/sqrt(numDim);\n otherwise\n error('Invalid method specified') \nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Geometry/regularNSimplexCoords.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.9111797033789887, "lm_q1q2_score": 0.8539674573061207}} {"text": "classdef BinomialD\n%%BINOMIALD Functions to handle the binomial distribution. The binomial\n% distribution is the distribution of the number of successes in\n% a sequence of n independent trials, each with a probability of\n% success p.\n%Implemented methods are: mean, var, PMF, CDF, rand\n%\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nmethods(Static)\n\nfunction val=mean(n,p)\n%%MEAN Obtain the mean of the binomial distribution for the given number of\n% trials and probability of success.\n%\n%INPUTS: n The number of trials performed.\n% p The probability of success for the underlying Bernoulli trials.\n% 0<=p<=1.\n%\n%OUTPUTS: val The mean number of successes for the binomial distribution.\n%\n%EXAMPLE:\n%We verify the computed mean by comparing it to the sample mean.\n% p=0.75;\n% n=61;\n% meanVal=BinomialD.mean(n,p)\n% numSamp=1e5;\n% sampMeanVal=mean(BinomialD.rand([1,numSamp],n,p))\n%One will find both values are about 45.75.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=n*p;\nend\n\nfunction val=var(n,p)\n%%VAR Obtain the variance of the binomial distribution for the given number\n% of trials and probability of success.\n%\n%INPUTS: n The number of trials performed.\n% p The probability of success for the underlying Bernoulli trials.\n% 0<=p<=1.\n%\n%OUTPUTS: val The variance of the binomial distribution with the given\n% parameters.\n%\n%EXAMPLE:\n%We verify that the computed variance by comparing it to the sample\n%variance.\n% p=0.75;\n% n=61;\n% varVal=BinomialD.var(n,p)\n% numSamp=1e5;\n% sampVarVal=var(BinomialD.rand([1,numSamp],n,p))\n%One will find both values are about 11.4375.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n val=n*p*(1-p);\nend\n\nfunction val=PMF(k,n,p)\n%%PMF Evaluate the binomial probability mass function at a given point with\n% a specified number of trials and success probability per trial.\n%\n%INPUTS: k The nonnegative integer point(s) at which the binomial PMF is to\n% be evaluated (the number of successes in n trials). Note that\n% 0<=k<=n.\n% n The number of trials of which k successes are observed.\n% p The probability of success for the underlying Bernoulli trials.\n% 0<=p<=1.\n%\n%OUTPUT: val The value(s) of the binomial PMF with success probability p.\n%\n%The binomial PMF provides the probability of k successes from n trials,\n%each with a success probability of p.\n%\n%EXAMPLE:\n%Here, we validate the PMF by generating random samples and comparing the\n%PMF plot with a histogram of the random samples.\n% p=0.75;\n% n=61;\n% numSamples=1e5;\n% figure(1)\n% clf\n% histogram(BinomialD.rand([numSamples,1],n,p),'Normalization','pdf')\n% hold on\n% x=0:61;\n% vals=BinomialD.PMF(x,n,p);\n% stem(x,vals,'linewidth',2)\n% h1=xlabel('x');\n% h2=ylabel('PDF(x)');\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%One will see that the histogram matches well with the plot.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n numPoints=length(k);\n val=zeros(size(k));\n for curK=1:numPoints\n if(k(curK)>=0&&k(curK)<=n)\n val(curK)=binomial(n,k(curK))*p^k(curK)*(1-p)^(n-k(curK));\n end\n end\nend\n\nfunction val=CDF(k,n,p)\n%%CDF Evaluate the cumulative distribution function (CDF) of the binomial\n% distribution at a desired point.\n%\n%INPUTS: k The nonnegative integer point(s) at which the binomial CDF is to\n% be evaluated. Note that 0<=k<=n.\n% n The number of trials of which k or fewer successes are observed.\n% p The probability of success for the underlying Bernoulli trials.\n% 0<=p<=1.\n%\n%OUTPUTS: val The CDF of the binomial distribution evaluated at the desired\n% point(s).\n%\n%Rather than summing over the values of the PMF, the equivalency between\n%the binomial distribution and the regularized incomplete beta function,\n%described at [1] is used. Thus, the built-in function betainc can be used\n%for efficient evaluation of the CDF with large values.\n%\n%EXAMPLE:\n%We validate the CDF value by comparing it to a value computed from random\n%samples.\n% p=0.75;\n% n=61;\n% x=45;\n% numSamples=1e5;\n% prob=BinomialD.CDF(x,n,p)\n% probSamp=mean(BinomialD.rand([numSamples,1],n,p)<=x)\n%One will find the values ot both be about 0.460.\n%\n%REFERENCES:\n%[1] Weisstein, Eric W. \"Binomial Distribution.\" From MathWorld--A Wolfram\n% Web Resource. http://mathworld.wolfram.com/BinomialDistribution.html\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n \n val=zeros(size(k));\n sel=k>=0&k<=n;\n \n val(sel)=betainc(1-p,n-k(sel),k(sel)+1);\nend\n\nfunction k=invCDF(probVals,n,p,choice)\n%%INVCDF Evaluate the inverse sumulative distribution function (CDF) of the\n% binomial distirbution for given probabilities.\n%\n%INPUTS: probVals The CDF probability value(s) at which the argument of the\n% binomial CDF is to be determined. Note that 0<=prob<=1.\n% n The number of trials of which k or fewer successes are observed.\n% p The probability of success for the underlying Bernoulli trials.\n% 0<=p<=1.\n% choice An optional parameter indicating what to do when probVals does\n% not exactly equal a CDF value (which will presumably be the case\n% most of the time). Possible values are:\n% 0 Return the k that is the closest value.\n% 1 (The default if omitted or an empty matrix is passed) return\n% the next lower k if it exists, otherwise return 0.\n% 2 Return the next higher k if there is one, otherwise return n.\n%\n%OUTPUTS: k The set of non-negative integer points that are the inverse CDF\n% values (number of trials) corresponding to the values in\n% probVals. This has the same dimensions as probVals.\n%\n%Though one can sum the PMF values until the resulting CDF values exceed\n%prob, this can be slow as n gets large and the recursive computation of\n%costs can be subject to finite precision limitations. These issues can be\n%avoided by expressing the CDF in terms of the regularized incomplete beta\n%function, which is given in [1]. The CDF can be evaluated using betainc\n%without summing all of the terms. The inverse is found using the binSearch\n%function.\n%\n%REFERENCES:\n%[1] Weisstein, Eric W. \"Binomial Distribution.\" From MathWorld--A Wolfram\n% Web Resource. http://mathworld.wolfram.com/BinomialDistribution.html\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n if(nargin<4||isempty(choice))\n choice=1;\n end\n\n f=@(idx)BinomialD.CDF(idx,n,p);\n k=zeros(size(probVals));\n numPts=numel(probVals);\n \n for i=1:numPts\n [~,k(i)]=binSearch(f,probVals(i),choice,[0;n]);\n end\nend\n\nfunction vals=rand(N,n,p)\n%%RAND Generate binomial random variables with a given number of trials and\n% probability of success.\n%\n%INPUTS: N If N is a scalar, then rand returns an NXN matrix of random\n% variables. If N=[M,N1] is a two-element row vector, then rand\n% returns an MXN1 matrix of random variables.\n% n The number of trials performed.\n% p The probability of success for the underlying Bernoulli trials.\n% 0<=p<=1.\n%\n%The algorithm used depends on the value of n*min(p,1-p). If\n%n*min(p,1-p)>=10, then the binomial, triangle, parallelogram, exponential\n%algorithm of [1] is used. If n*min(p,1-p)<10, then a basic inverse\n%transformation method, as described in [1] is used. This assures that the\n%random number generation is fast for a wide variety of values of n and p.\n%\n%REFERENCES:\n%[1] V. Kachitvichyanukul and B. W. Schmeiser, \"Binomial random variate\n% generation,\" Communications of the ACM, vol. 31, no. 2, pp. 216-222,\n% Feb. 1988.\n%\n%August 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n if(isscalar(N))\n dims=[N N];\n else\n dims=N;\n end\n\n vals=zeros(dims);\n numVals=numel(vals);\n\n %Do not use the BTPE algorithm if n*min(p,1-p) is small. Rather, the\n %inverse transformation algorithm from Section 2 is used. However, it\n %has been modified replacing p with pMin=min(p,1-p) as described in the\n %text to reduce the execution time.\n if(n*min(p,1-p)<10)\n pMin=min(p,1-p);\n q=1-pMin;\n s=pMin/q;\n a=(n+1)*s;\n \n for curVal=1:numVals\n u=rand(1);\n r=q^n;\n x=0;\n gotoNextVal=false;\n \n %With n*pMin<10, the mean of the PMF is below 10 and the\n %standard deviation is below sqrt(10). To assure a limited\n %runtime, we thus cap the maximum value of the iterated x at\n %1000, or about 316 standard deviations from the mean.\n while(x<1000)\n if(u<=r)\n %This part deals with using pMin instead of p.\n if(p>1/2)\n x=n-x;\n end\n vals(curVal)=x;\n gotoNextVal=true;\n break;\n end\n u=u-r;\n x=x+1;\n r=((a/x)-s)*r;\n end\n \n if(gotoNextVal)\n continue;\n end\n \n if(p>1/2)\n x=n-x;\n end\n vals(curVal)=x;\n end\n return;\n end\n\n%If we are here, then the BTPE algorithm should be used. Everything below\n%is the BTPE algorithm from Section 3 of [1].\n \n%Step 0: Set up constants as functions of n and p.\n r=min(p,1-p);\n q=1-r;\n fM=n*r+r;\n M=floor(fM);\n p1=floor(2.195*sqrt(n*r*q)-4.6*q)+0.5;\n xM=M+0.5;\n xL=xM-p1;\n xR=xM+p1;\n c=0.134+20.5/(15.3+M);\n a=(fM-xL)/(fM-xL*r);\n lambdaL=a*(1+a/2);\n a=(xR-fM)/(xR*q);\n lambdaR=a*(1+a/2);\n p2=p1*(1+2*c);\n p3=p2+c/lambdaL;\n p4=p3+c/lambdaR;\n \n for curVal=1:numVals\n gotoNextVal=false;\n while(1)\n if(gotoNextVal)\n break;\n end\n \n %Step 1: Generate a random variable for selecting the region. If region\n % 1 is selected, generate a triangularly distributed random variable.\n u=rand(1)*p4;\n v=rand(1);\n if(u1/2)%Step 6\n y=n-y;\n end\n vals(curVal)=y;\n gotoNextVal=true;\n continue;\n elseif(u<=p2)%Step 2: Parallelograms.\n x=xL+(u-p1)/c;\n v=v*c+1-abs(M-x+0.5)/p1;\n if(v<=0||v>1)\n continue;\n end\n\n y=floor(x);\n elseif(u<=p3)%Step 3: Left exponential tail.\n y=floor(xL+log(v)/lambdaL);\n if (y<0)\n continue;\n end\n v=v*(u-p2)*lambdaL;\n else%Step 4: Right exponential tail.\n y=floor(xR-log(v)/lambdaR);\n if(y>n)\n continue;\n end\n v=v*(u-p3)*lambdaR;\n end\n \n %Step 5: Acceptace/ Rejection Comparison.\n\n k=abs(y-M);\n %5.0 Test for appropriate method of evaluating f(y)\n if(k<=20||k>=n*r*q/2-1)\n %5.1 Evaluate f(y) via recursive relationship\n s=r/q;\n a=s*(n+1);\n F=1;\n if(My)\n i=y;\n while(1)\n i=i+1;\n F=F/(a/i-s);\n if(i==M)\n break;\n end\n end\n end\n\n if(v<=F)\n if(p>1/2)%Step 6\n y=n-y;\n end\n vals(curVal)=y;\n gotoNextVal=true;\n continue;\n else\n continue;\n end\n else\n %5.2 Test for squeezing. Check the value of ln(v) against\n %upper and lower bounds of ln(f(y))\n rho=(k/(n*r*q))*((k*(k/3+0.625)+(1/6))/(n*r*q)+0.5);\n t=-k^2/(2.0*n*r*q);\n A=log(v);\n if(A1/2)%Step 6\n y=n-y;\n end\n vals(curVal)=y;\n gotoNextVal=true;\n continue;\n elseif(A>t+rho)\n continue;\n end\n %5.3 Final Acceptance/ Rejection Test\n x1=y+1;\n f1=M+1;\n z=n+1-M;\n w=n-y+1;\n x2=x1^2;\n f2=f1^2;\n z2=z^2;\n w2=w^2;\n\n temp=xM*log(f1/x1)+(n-M+0.5)*log(z/w) ...\n +(y-M)*log(w*r/(x1*q)) ...\n +(13860-(462-(132-(99 ...\n -140/f2)/f2)/f2)/f2)/f1/166320 ...\n +(13860-(462-(132-(99 ...\n -140/z2)/z2)/z2)/z2)/z/166320 ...\n +(13860-(462-(132-(99 ...\n -140/x2)/x2)/x2)/x2)/x1/166320 ...\n +(13860-(462-(132-(99 ...\n -140/w2)/w2)/w2)/w2)/w/166320;\n if(A<=temp)\n if(p>1/2)%Step 6\n y=n-y;\n end\n vals(curVal)=y;\n gotoNextVal=true;\n continue;\n else\n continue;\n end\n end\n end\n end\nend\n\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/Distributions/BinomialD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576266, "lm_q2_score": 0.8902942319436395, "lm_q1q2_score": 0.8539295277088892}} {"text": "function y = construct_harmonic_signal( freq,amp,phase,dc,t )\n% y = construct_harmonic_signal( freq,amp,phase,dc,t )\n% reconstructs a periodical signal from given harmonics\n% Written by Dr. Yoash Levron, April 2013.\n%\n% The input is the individual harmonics of the signal.\n% the function reconstructs the signal y(t).\n%\n% for example, given the input :\n% freq = [50 100 150 200 ...]\n% amp = [3 0 0 0 ...]\n% phase = [0 0 0 0 ...]\n% dc = 2\n% The function will output the signal:\n% y = 2 + 3*cos(2*pi*50*t)\n%\n% Generally, the output signal y is:\n% y = dc + amp(1)*cos(2*pi*freq(1)*t + phase(1)) \n% +amp(2)*cos(2*pi*freq(2)*t + phase(2)) + ...\n%\n% This function is designed compatible to\n% function 'fourier_series_real'. The two functions are inversible:\n% The following code will generate a signal y(t) identical to x(t) :\n% [ freq,amp,phase,dc ] = fourier_series_real( t,x );\n% y = construct_harmonic_signal( freq,amp,phase,dc,t);\n%\n% inputs:\n% freq - [Hz] frequencies of the fourier series, not including zero.\n% amp - amplitudes vector, not including the DC component.\n% phase - [rad/sec] . phases, not including the DC component.\n% dc - the DC value (average of the signal).\n% t - [sec] time vector. \n%\n% outputs:\n% y - output signal. same length as t.\n\ny = dc * t.^0;\nfor ii = 1:length(freq)\n y = y + amp(ii)*cos(2*pi*freq(ii)*t + phase(ii));\nend\n\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/40017-fourier-series-of-real-signals/construct_harmonic_signal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780477, "lm_q2_score": 0.8991213698363247, "lm_q1q2_score": 0.8538680212297763}} {"text": "function sim = gaussianKernel(x1, x2, sigma)\n %% RBFKERNEL returns a radial basis function kernel between x1 and x2\n % sim = gaussianKernel(x1, x2) returns a gaussian kernel between x1 and x2\n % and returns the value in sim\n\n % Ensure that x1 and x2 are column vectors\n x1 = x1(:); x2 = x2(:);\n\n % ====================== YOUR CODE HERE ======================\n % Instructions: Fill in this function to return the similarity between x1\n % and x2 computed using a Gaussian kernel with bandwidth\n % sigma\n value = - sum((x1 - x2) .^ 2) / (2 * sigma ^ 2);\n sim = exp(value);\nend", "meta": {"author": "worldveil", "repo": "coursera-ml", "sha": "94e205b01ec3a47c0d777943194d12fa130f4685", "save_path": "github-repos/MATLAB/worldveil-coursera-ml", "path": "github-repos/MATLAB/worldveil-coursera-ml/coursera-ml-94e205b01ec3a47c0d777943194d12fa130f4685/svm/code/gaussianKernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.8976953010025942, "lm_q1q2_score": 0.853835900229544}} {"text": "function [V,F]=platonic_solid(n,r)\n\n% function [V,F]=platonic_solid(n,r)\n% ------------------------------------------------------------------------\n% PLATONIC_SOLID Creates the PATCH data, the vertices (V) and faces (F) for\n% a given platonic solid (according to \"n\" see below) with radius (r)\n%\n% n=1 -> Tetrahedron\n% n=2 -> Cube\n% n=3 -> Octahedron\n% n=4 -> Icosahedron\n% n=5 -> Dodecahedron\n%\n% %%%Example\n% clear all; close all; clc;\n% \n% r=1;\n% figure;fig=gcf; clf(fig); colordef (fig, 'white'); units=get(fig,'units'); set(fig,'units','normalized','outerposition',[0 0 1 1]); set(fig,'units',units); set(fig,'Color',[1 1 1]);\n% hold on; \n% \n% [V,F]=platonic_solid(1,r);\n% subplot(2,3,1);\n% patch('Faces',F,'Vertices',V,'FaceColor','b','FaceAlpha',0.6,'EdgeColor','k','LineWidth',2); axis equal; grid on; hold on; view(3); axis off;\n% \n% [V,F]=platonic_solid(2,r);\n% subplot(2,3,2);\n% patch('Faces',F,'Vertices',V,'FaceColor','b','FaceAlpha',0.6,'EdgeColor','k','LineWidth',2); axis equal; grid on; hold on; view(3); axis off;\n% \n% [V,F]=platonic_solid(3,r);\n% subplot(2,3,3);\n% patch('Faces',F,'Vertices',V,'FaceColor','b','FaceAlpha',0.6,'EdgeColor','k','LineWidth',2); axis equal; grid on; hold on; view(3); axis off;\n% \n% [V,F]=platonic_solid(4,r);\n% subplot(2,3,4);\n% patch('Faces',F,'Vertices',V,'FaceColor','b','FaceAlpha',0.6,'EdgeColor','k','LineWidth',2); axis equal; grid on; hold on; view(3); axis off;\n% \n% [V,F]=platonic_solid(5,r);\n% subplot(2,3,5);\n% patch('Faces',F,'Vertices',V,'FaceColor','b','FaceAlpha',0.6,'EdgeColor','k','LineWidth',2); axis equal; grid on; hold on; view(3); axis off;\n%\n%\n% Kevin Mattheus Moerman\n% kevinmoerman@hotmail.com\n% 13/11/2009\n% ------------------------------------------------------------------------\n\nphi=(1+sqrt(5))/2;\n\nswitch n\n case 1 % Tetrahedron\n V1=[-0.5;0.5;0;0;];\n V2=[-sqrt(3)/6; -sqrt(3)/6; sqrt(3)/3; 0];\n V3=[-0.25.*sqrt(2/3); -0.25.*sqrt(2/3); -0.25.*sqrt(2/3); 0.75.*sqrt(2/3)];\n F= [1 2 3; 1 2 4; 2 3 4; 1 3 4;];\n\n case 2 % Cube\n V1=[-1; 1; 1; -1; -1; 1; 1; -1;];\n V2=[-1; -1; 1; 1; -1; -1; 1; 1;];\n V3=[-1; -1;-1; -1; 1; 1; 1; 1;];\n F= [1 2 3 4; 1 2 6 5; 2 3 7 6; 3 4 8 7; 4 1 5 8; 5 6 7 8;];\n\n case 3 % Octahedron\n V1=[-1; 1; 1; -1; 0; 0;];\n V2=[-1; -1; 1; 1; 0; 0;];\n V3=[ 0; 0; 0; 0; -1; 1;];\n F= [1 2 5; 2 3 5; 3 4 5; 4 1 5; 1 2 6; 2 3 6; 3 4 6; 4 1 6;];\n\n case 4 % Icosahedron\n V1=[0;0;0;0;-1;-1;1;1;-phi;phi;phi;-phi;];\n V2=[-1;-1;1;1;-phi;phi;phi;-phi;0;0;0;0;];\n V3=[-phi;phi;phi;-phi;0;0;0;0;-1;-1;1;1;];\n F= [1 4 9;1 5 9;1 8 5;1 8 10;1 10 4; 12 2 5; 12 2 3; 12 3 6; 12 6 9; 12 9 5; 11 7 10; 11 10 8; 11 8 2; 11 2 3; 11 3 7; 2 5 8; 10 4 7; 3 6 7; 6 7 4; 6 4 9; ];\n\n case 5 % Dodecahedron\n V1=[1;(1/phi);-phi;phi;-1;0;-phi;1;-1;-1;1;(1/phi);-1;0;0;-(1/phi);phi;-(1/phi);1;0;];\n V2=[1;0;-(1/phi);(1/phi);1;-phi;(1/phi);-1;1;-1;-1;0;-1;-phi;phi;0;-(1/phi);0;1;phi;];\n V3=[[1;phi;0;0;-1;-(1/phi);0;1;1;1;-1;-phi;-1;(1/phi);-(1/phi);phi;0;-phi;-1;(1/phi);]];\n F=[1,2,16,9,20;2,16,10,14,8;16,9,7,3,10;7 9 20 15 5;5,7,3,13,18;3,13,6,14,10;6,13,18,12,11;6,11,17,8,14;11,12,19,4,17;1,2,8,17,4;1,4,19,15,20;12,18,5,15,19];\n\n otherwise\n warning('False input for n')\nend\n\n[THETA,PHI,R]=cart2sph(V1,V2,V3);\nR=r.*ones(size(V1(:,1)));\n[V1,V2,V3]=sph2cart(THETA,PHI,R);\nV=[V1 V2 V3];\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28213-platonicsolid/platonic_solid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.9196425273235999, "lm_q1q2_score": 0.8538042157322837}} {"text": "function value = circle_annulus_area_2d ( radius1, radius2 )\n\n%*****************************************************************************80\n%\n%% CIRCLE_ANNULUS_AREA_2D returns the area of a circular annulus in 2D.\n%\n% Integration region:\n%\n% Points (X,Y) such that\n%\n% RADIUS1**2 <= ( X - XC )**2 + ( Y - YC )**2 <= RADIUS2**2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 20 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real RADIUS1, RADIUS2, the radii of the circles.\n%\n% Output, real CIRCLE_ANNULUS_AREA_2D, the area of the annulus.\n%\n value = pi * ( radius1 + radius2 ) * ( radius2 - radius1 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/circle_annulus_area_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.8962513745192024, "lm_q1q2_score": 0.853745868082664}} {"text": "function varargout = cart2sph2(varargin)\n%CART2SPH2 Convert cartesian coordinates to spherical coordinates.\n%\n% [THETA PHI RHO] = cart2sph2([X Y Z])\n% [THETA PHI RHO] = cart2sph2(X, Y, Z)\n%\n% The following convention is used:\n% THETA is the colatitude, in radians, 0 for north pole, +pi for south\n% pole, pi/2 for points with z=0. \n% PHI is the azimuth, in radians, defined as matlab cart2sph: angle from\n% Ox axis, counted counter-clockwise.\n% RHO is the distance of the point to the origin.\n% Discussion on choice for convention can be found at:\n% http://www.physics.oregonstate.edu/bridge/papers/spherical.pdf\n%\n% Example:\n% cart2sph2([1 0 0]) returns [pi/2 0 1];\n% cart2sph2([1 1 0]) returns [pi/2 pi/4 sqrt(2)];\n% cart2sph2([0 0 1]) returns [0 0 1];\n%\n% See also \n% angles3d, sph2cart2, cart2sph, cart2sph2d\n%\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2005-02-18\n% Copyright 2005-2022 INRA - TPV URPOI - BIA IMASTE\n\n% parse input angles based on input argument number\nif length(varargin) == 1\n xyz = varargin{1};\nelseif length(varargin) == 3\n xyz = [varargin{1} varargin{2} varargin{3}];\nend\n\n% ensure z coordinate is specified\nif size(xyz, 2) == 2\n xyz(:,3) = 1;\nend\n\n% convert to spherical coordinates\n[p, t, r] = cart2sph(xyz(:,1), xyz(:,2), xyz(:,3));\n\n% format output arguments\nif nargout == 1 || nargout == 0\n varargout{1} = [pi/2-t p r];\nelseif nargout==2\n varargout{1} = pi/2-t;\n varargout{2} = p;\nelse\n varargout{1} = pi/2-t;\n varargout{2} = p;\n varargout{3} = r;\nend\n \n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom3d/cart2sph2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.9184802434674242, "lm_q1q2_score": 0.853672650177493}} {"text": "function pdf = triangle_pdf ( x, a, b, c )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_PDF evaluates the Triangle PDF.\n%\n% Discussion:\n%\n% Given points A <= B <= C, the probability is 0 to the left of A,\n% rises linearly to a maximum of 2/(C-A) at B, drops linearly to zero\n% at C, and is zero for all values greater than C.\n%\n% Formula:\n%\n% PDF(A,B,C;X)\n% = 2 * ( X - A ) / ( B - A ) / ( C - A ) for A <= X <= B\n% = 2 * ( C - X ) / ( C - B ) / ( C - A ) for B <= X <= C.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the PDF.\n%\n% Input, real A, B, C, the parameters of the PDF.\n% A <= B <= C and A < C.\n%\n% Output, real PDF, the value of the PDF.\n%\n if ( x <= a )\n\n pdf = 0.0;\n\n elseif ( x <= b )\n\n if ( a == b )\n pdf = 0.0;\n else\n pdf = 2.0 * ( x - a ) / ( b - a ) / ( c - a );\n end\n\n elseif ( x <= c )\n\n if ( b == c )\n pdf = 0.0;\n else\n pdf = 2.0 * ( c - x ) / ( c - b ) / ( c - a );\n end\n\n else\n pdf = 0.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/triangle_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047778, "lm_q2_score": 0.9032942047513692, "lm_q1q2_score": 0.8536082494038287}} {"text": "function [ x, seed ] = sphere_unit_sample_2d ( seed )\n\n%*****************************************************************************80\n%\n%% SPHERE_UNIT_SAMPLE_2D picks a random point on the unit sphere (circle) in 2D.\n%\n% Discussion:\n%\n% The unit sphere in 2D satisfies:\n%\n% X * X + Y * Y = 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real X(2), a random point on the unit circle.\n%\n% Output, integer SEED, a seed for the random number generator.\n%\n dim_num = 2;\n\n [ u, seed ] = r8_uniform_01 ( seed );\n\n x(1) = cos ( 2.0 * pi * u );\n x(2) = sin ( 2.0 * pi * u );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/sphere_unit_sample_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.894789454880027, "lm_q1q2_score": 0.8535988044462104}} {"text": "%PHASECORRELATE Detect translational shifts that occur between two images\n%\n% pshift = cv.phaseCorrelate(src1, src2)\n% [pshift,response] = cv.phaseCorrelate(src1, src2)\n% [...] = cv.phaseCorrelate(..., 'OptionName',optionValue, ...)\n%\n% ## Input\n% * __src1__ First source floating-point array (single-channel `single` or\n% `double`).\n% * __src2__ Second source floating-point array (single-channel `single` or\n% `double`), of same size and type as `src1`.\n%\n% ## Output\n% * __pshift__ detected phase shift (sub-pixel) between the two arrays `[x,y]`\n% * __response__ Signal power within the 5x5 centroid around the peak, between\n% 0 and 1 (optional).\n%\n% ## Options\n% * __Window__ Floating-point array with windowing coefficients to reduce edge\n% effects (optional). Not set by default.\n%\n% The function is used to detect translational shifts that occur between two\n% images.\n%\n% The operation takes advantage of the Fourier shift theorem for detecting the\n% translational shift in the frequency domain. It can be used for fast image\n% registration as well as motion estimation. For more information please see\n% [Phase correlation](https://en.wikipedia.org/wiki/Phase_correlation).\n%\n% Calculates the cross-power spectrum of two supplied source arrays. The\n% arrays are padded if needed with cv.getOptimalDFTSize.\n%\n% The function performs the following equations:\n%\n% * First it applies a\n% [Hanning window](https://en.wikipedia.org/wiki/Hann_function) to each image\n% to remove possible edge effects. This window is cached until the array\n% size changes to speed up processing time.\n%\n% * Next it computes the forward DFTs of each source array:\n%\n% G_a = F{src1}, G_b = F{src2}\n%\n% where `F` is the forward DFT.\n%\n% * It then computes the cross-power spectrum of each frequency domain array:\n%\n% R = G_a * G_b^(*) / |G_a * G_b^(*)|\n%\n% * Next the cross-correlation is converted back into the time domain via the\n% inverse DFT:\n%\n% r = F^(-1){R}\n%\n% * Finally, it computes the peak location and computes a 5x5 weighted\n% centroid around the peak to achieve sub-pixel accuracy.\n%\n% (\\Delta{x}, \\Delta{y}) = weightedCentroid{argmax_(x,y){r}}\n%\n% * If non-zero, the response parameter is computed as the sum of the elements\n% of `r` within the 5x5 centroid around the peak location. It is normalized\n% to a maximum of 1 (meaning there is a single peak) and will be smaller\n% when there are multiple peaks.\n%\n% See also: cv.dft, cv.getOptimalDFTSize, cv.idft, cv.mulSpectrums,\n% cv.createHanningWindow, imregcorr\n%\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/+cv/phaseCorrelate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.9073122163480667, "lm_q1q2_score": 0.8535900264924754}} {"text": "function [ s, t ] = segment_point_coords_2d ( p1, p2, p )\n\n%*****************************************************************************80\n%\n%% SEGMENT_POINT_COORDS_2D: coordinates of a point on a line segment in 2D.\n%\n% Discussion:\n%\n% A line segment is the finite portion of a line that lies between\n% two points P1 and P2.\n%\n% By the coordinates of a point P with respect to a line segment [P1,P2]\n% we mean numbers S and T such that S gives us the distance from the\n% point P to the nearest point PN on the line (not the line segment!),\n% and T gives us the position of PN relative to P1 and P2.\n%\n% If S is zero, then P lies on the line.\n%\n% If 0 <= T <= 1, then PN lies on the line segment.\n%\n% If both conditions hold, then P lies on the line segment.\n%\n% If E is the length of the line segment, then the distance of the\n% point to the line segment is:\n%\n% sqrt ( S**2 + T**2 * E**2 ) if T <= 0;\n% S if 0 <= T <= 1\n% sqrt ( S**2 + (T-1)**2 * E**2 ) if 1 <= T\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real P1(2,1), P2(2,1), the endpoints of the line segment.\n%\n% Input, real P(2,1), the point to be considered.\n%\n% Output, real S, the distance of P to the nearest point PN\n% on the line through P1 and P2. (S will always be nonnegative.)\n%\n% Output, real T, the relative position of the point PN\n% to the points P1 and P2.\n%\n\n%\n% If the line segment is actually a point, then the answer is easy.\n%\n if ( p1(1:2,1) == p2(1:2,1) )\n\n t = 0.0;\n\n else\n\n bot = sum ( ( p2(1:2,1) - p1(1:2,1) ).^2 );\n\n t = ( p(1:2,1) - p1(1:2,1) )' * ( p2(1:2,1) - p1(1:2,1) ) / bot;\n\n end\n\n pn(1:2,1) = p1(1:2,1) + t * ( p2(1:2,1) - p1(1:2,1) );\n\n s = sqrt ( sum ( ( p(1:2,1) - pn(1:2,1) ).^2 ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/segment_point_coords_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222396, "lm_q2_score": 0.9086178944582997, "lm_q1q2_score": 0.8532147509056341}} {"text": "function [ n_data, n, c ] = phi_values ( n_data )\n\n%*****************************************************************************80\n%\n%% PHI_VALUES returns some values of the PHI function.\n%\n% Discussion:\n%\n% PHI(N) is the number of integers between 1 and N which are\n% relatively prime to N. I and J are relatively prime if they\n% have no common factors. The function PHI(N) is known as\n% \"Euler's totient function\".\n%\n% By convention, 1 and N are relatively prime.\n%\n% In Mathematica, the function can be evaluated by:\n%\n% EulerPhi[n]\n%\n% First values:\n%\n% N PHI(N)\n%\n% 1 1\n% 2 1\n% 3 2\n% 4 2\n% 5 4\n% 6 2\n% 7 6\n% 8 4\n% 9 6\n% 10 4\n% 11 10\n% 12 4\n% 13 12\n% 14 6\n% 15 8\n% 16 8\n% 17 16\n% 18 6\n% 19 18\n% 20 8\n%\n% Formula:\n%\n% PHI(U*V) = PHI(U) * PHI(V) if U and V are relatively prime.\n%\n% PHI(P**K) = P**(K-1) * ( P - 1 ) if P is prime.\n%\n% PHI(N) = N * Product ( P divides N ) ( 1 - 1 / P )\n%\n% N = Sum ( D divides N ) PHI(D).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, integer N, the argument of the PHI function.\n%\n% Output, integer C, the value of the PHI function.\n%\n n_max = 20;\n\n c_vec = [ ...\n 1, 1, 2, 2, 4, 2, 6, 4, 6, 4, ...\n 8, 8, 16, 20, 16, 40, 148, 200, 200, 648 ];\n\n n_vec = [ ...\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...\n 20, 30, 40, 50, 60, 100, 149, 500, 750, 999 ];\n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n n = 0;\n c = 0;\n else\n n = n_vec(n_data);\n c = c_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/phi_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522863, "lm_q2_score": 0.9005297761070066, "lm_q1q2_score": 0.8531448418298049}} {"text": "function a_heap = r8vec_heap_a ( n, a )\n\n%*****************************************************************************80\n%\n%% R8VEC_HEAP_A reorders an R8VEC into an ascending heap.\n%\n% Discussion:\n%\n% An ascending heap is an array A with the property that, for every index J,\n% A(J) <= A(2*J) and A(J) <= A(2*J+1), (as long as the indices\n% 2*J and 2*J+1 are legal).\n%\n% Diagram:\n%\n% A(1)\n% / \\\n% A(2) A(3)\n% / \\ / \\\n% A(4) A(5) A(6) A(7)\n% / \\ / \\\n% A(8) A(9) A(10) A(11)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 April 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Albert Nijenhuis, Herbert Wilf,\n% Combinatorial Algorithms,\n% Academic Press, 1978, second edition,\n% ISBN: 0-12-519260-6.\n%\n% Parameters:\n%\n% Input, integer N, the size of the input array.\n%\n% Input, real A(N), an unsorted array.\n%\n% Output, real A_HEAP(N), the values of the array have been \n% reordered into a heap.\n%\n a_heap(1:n) = a(1:n);\n%\n% Only nodes N/2 down to 1 can be \"parent\" nodes.\n%\n for i = floor ( n/2 ) : -1 : 1\n%\n% Copy the value out of the parent node.\n% Position IFREE is now \"open\".\n%\n key = a_heap(i);\n ifree = i;\n\n while ( 1 )\n%\n% Positions 2*IFREE and 2*IFREE + 1 are the descendants of position\n% IFREE. (One or both may not exist because they exceed N.)\n%\n m = 2 * ifree;\n%\n% Does the first position exist?\n%\n if ( n < m )\n break;\n end\n%\n% Does the second position exist?\n%\n if ( m + 1 <= n )\n%\n% If both positions exist, take the smaller of the two values,\n% and update M if necessary.\n%\n if ( a_heap(m+1) < a_heap(m) )\n m = m + 1;\n end\n\n end\n%\n% If the small descendant is smaller than KEY, move it up,\n% and update IFREE, the location of the free position, and\n% consider the descendants of THIS position.\n%\n if ( key <= a_heap(m) )\n break;\n end\n\n a_heap(ifree) = a_heap(m);\n ifree = m;\n\n end\n%\n% Once there is no more shifting to do, KEY moves into the free spot.\n%\n a_heap(ifree) = key;\n\n end\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec_heap_a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.9241418225903234, "lm_q1q2_score": 0.8530191014916068}} {"text": "function bern = bpab ( n, x, a, b )\n\n%*****************************************************************************80\n%\n%% BPAB evaluates at X the Bernstein polynomials based in [A,B].\n%\n% Formula:\n%\n% BERN(N,I)(X) = [N!/(I!*(N-I)!)] * (B-X)^(N-I) * (X-A)^I / (B-A)^N\n%\n% First values:\n%\n% B(0,0)(X) = 1\n%\n% B(1,0)(X) = ( B-X ) / (B-A)\n% B(1,1)(X) = ( X-A ) / (B-A)\n%\n% B(2,0)(X) = ( (B-X)^2 ) / (B-A)^2\n% B(2,1)(X) = ( 2 * (B-X) * (X-A) ) / (B-A)^2\n% B(2,2)(X) = ( (X-A)^2 ) / (B-A)^2\n%\n% B(3,0)(X) = ( (B-X)^3 ) / (B-A)^3\n% B(3,1)(X) = ( 3 * (B-X)^2 * (X-A) ) / (B-A)^3\n% B(3,2)(X) = ( 3 * (B-X) * (X-A)^2 ) / (B-A)^3\n% B(3,3)(X) = ( (X-A)^3 ) / (B-A)^3\n%\n% B(4,0)(X) = ( (B-X)^4 ) / (B-A)^4\n% B(4,1)(X) = ( 4 * (B-X)^3 * (X-A) ) / (B-A)^4\n% B(4,2)(X) = ( 6 * (B-X)^2 * (X-A)^2 ) / (B-A)^4\n% B(4,3)(X) = ( 4 * (B-X) * (X-A)^3 ) / (B-A)^4\n% B(4,4)(X) = ( (X-A)^4 ) / (B-A)^4\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 July 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the degree of the Bernstein polynomials to be used.\n% For any N, there is a set of N+1 Bernstein polynomials, each of\n% degree N, which form a basis for polynomials on [A,B].\n%\n% Input, real X, the point at which the polynomials are to be evaluated.\n%\n% Input, real A, B, the endpoints of the interval on which the\n% polynomials are to be based. A and B should not be equal.\n%\n% Output, real BERN(1:N+1), the values of the N+1 Bernstein polynomials at X.\n%\n if ( b == a )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BPAB - Fatal error!\\n' );\n fprintf ( 1, ' A = B = %f\\n', a );\n error ( 'BPAB - Fatal error!' );\n end\n\n if ( n == 0 )\n \n bern(1) = 1.0;\n \n elseif ( 0 < n )\n \n bern(1) = ( b - x ) / ( b - a );\n bern(2) = ( x - a ) / ( b - a );\n \n for i = 2 : n\n bern(i+1) = ( x - a ) * bern(i) / ( b - a );\n for j = i-1 : -1 : 1\n bern(j+1) = ( ( b - x ) * bern(j+1) + ( x - a ) * bern(j) ) / ( b - a );\n end\n bern(1) = ( b - x ) * bern(1) / ( b - a );\n end\n \n end\n \n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/bpab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013548, "lm_q2_score": 0.894789454880027, "lm_q1q2_score": 0.8529804558094797}} {"text": "% In this example we consider a 127 dimensional space.\n% We choose vectors in this space by removing a row from a 128 x 128 Hadamard matrix.\n% We then construct 2 d-dimensional subspaces by choosing vectors from this set\n% randomly.\n% We then measure the principal angle between such a pair of subspaces.\n% We repeat it for t trials of random d-dimensional subspaces.\n% We vary d from 1 to 64.\n% Finally we plot the variation of principal angle with number of dimensions.\n% We note that as the subspace dimension increases, the principal angle between\n% two randomly chosen subspaces [with basis vectors from the Hadamard matrix]\n% keeps decreasing.\n\nclc; clear all;close all;\n% Construct a Hadamard matrix\nn = 128;\nh = hadamard(n);\n% drop one row\nh2 = h(1:end-1, :);\n% normalize the vectors\nh2 = spx.norm.normalize_l2(h2);\n% compute it's Gram matrix\ng = h2' * h2;\n% verify that absolute value of all the non-zero elements is 1/(n -1).\n\ntrials = 2;\n\nleast_angles = [];\nds = [];\n\n% The size of subspace\nfor d = 1:n/2\n fprintf('Choosing subspace dimension: %d\\n', d);\n for t=1:trials\n % select two independent subspaces\n indices = randperm(n, 2*d);\n A = h2(:, indices(1:d));\n B = h2(:, indices(d+1:end));\n angles = spx.la.spaces.principal_angles_cos(A, B);\n least_angle = angles(1);\n least_angle_deg = rad2deg(acos(least_angle));\n\n fprintf('Trial: %d, smallest principal angle: %.4f, %.2f degrees\\n', t, ...\n least_angle, least_angle_deg);\n end\n ds = [ds d];\n least_angles = [least_angles least_angle_deg];\nend\nplot(ds, least_angles);\nxlabel('D');\nylabel('Angle (degrees)');\ngrid on;\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/examples/linear_algebra/vector_spaces/ex_principal_angle_hadamard.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889438, "lm_q2_score": 0.8902942268497306, "lm_q1q2_score": 0.8528237688743542}} {"text": " function tk = ir_chebyshev_poly(n)\n%function tk = ir_chebyshev_poly(n)\n%|\n%| based on ChebyshevPoly.m by David Terr, Raytheon, 5-10-04\n%|\n%| Given nonnegative integer n, compute the\n%| Chebyshev polynomial T_n. Return the result as a column vector whose mth\n%| element is the coefficient of x^(n+1-m).\n%| polyval(ir_chebyshev_poly(n), x) evaluates T_n(x).\n\nif nargin < 1, ir_usage, end\nif streq(n, 'test'), ir_chebyshev_poly_test, return, end\n\nif n==0\n\ttk = 1;\nelseif n==1\n\ttk = [1 0]';\nelse\n\ttkm2 = zeros(n+1,1);\n\ttkm2(n+1) = 1;\n\ttkm1 = zeros(n+1,1);\n\ttkm1(n) = 1;\n\n\tfor k=2:n\n\t\ttk = zeros(n+1,1);\n\n\t\tfor e=n-k+1:2:n\n\t\t\ttk(e) = 2*tkm1(e+1) - tkm2(e);\n\t\tend\n\n\t\tif mod(k,2)==0\n\t\t\ttk(n+1) = (-1)^(k/2);\n\t\tend\n\n\t\tif k>Simulating 1D Kalman Filter: \\n\\n'); \n%Global parameters\nt=0:pi/100:200;\nF=200.00;\nn=length(t);\n\n% First test\nfprintf('>>1st Signal : f(t)=4*sin(t/10)*exp(-t/200)\\n');\nx1=(4*sin(t./10)).*exp(-inv(F).*t);\nW1=randn(size(x1));\nX1=(x1+W1);\nQ1=1e-4;\nfprintf('>>AWGN1 parameters : m1=%3.f\\tv1=%.3f\\n',mean(W1),var(W1));\n[Y1,K1,P1]=Kalman1D(X1,Q1);\n% Statistical parametrs for the first signal\nMax_x1= max(x1);\nMax_y1= max(Y1);\nMSE1 = 0.00 ;\nfor i=1:n\n MSE1=MSE1+((x1(i)-Y1(i))^2);\nend\nMSE1=MSE1/n;\nPSNR1=20*log10(max(Max_x1,Max_y1)/(MSE1^2));\nfprintf('>>Mean Square Error1 mse1=%3.f\\n',MSE1);\nfprintf('>>Peak Signal to Noise Ratio1 psnr1=%.3f\\tdB\\n\\n',PSNR1);\nf1=figure(1);set(f1,'Name','Testing 1: f(t)=4*sin(t/10)*exp(-t/200)+W, W~N(m,v)');\nsubplot(2,3,1), plot(t,x1,'MarkerSize',1.2), title(' original signal '), grid on ,\nsubplot(2,3,2), plot(t,X1,'g'), title(' noisy signal (awgn)'), grid on,\nsubplot(2,3,3), plot(t,Y1,'r'), title(' Filtered signal,R=1e-2,Q=1e-5'), grid on,\nsubplot(2,3,4), plot(t,x1,'b--','MarkerSize',2), hold on, plot(t,X1,'g+','MarkerSize',1.2), plot(t,Y1,'r--'),...\n title(' Superposition'), legend(' original','noisy','filtered'), grid on,\nsubplot(2,3,5), plot(K1(1:100)), title(strcat(' Kalman Gain',' convergence=',num2str(K1(100)))), grid on,xlabel(' iterations')\nsubplot(2,3,6), plot(P1(1:100)), title(strcat(' variance error',' convergence=',num2str(min(P1)))), grid on,xlabel('iterations')\n\n% Second test\nfprintf('>>2nd Signal : g(t)=0.5*square(pi*t/20);\\n');\nx2=0.5*square(pi*t/20);\nW2=randn(size(x2))/10;\nX2=(x2+W2);\nQ2=1e-4;\nfprintf('>>AWGN2 parameters : m2=%.3f\\tv2=%.3f\\n',mean(W2),var(W2));\n[Y2,K2,P2]=Kalman1D(X2,Q2);\n% Statistical parameters for the second signal\nMax_x2= max(x2);\nMax_y2= max(Y2);\nMSE2 = 0.00 ;\nfor i=1:n\n MSE2=MSE2+((x2(i)-Y2(i))^2);\nend\nMSE2=MSE2/n;\nPSNR2=20*log10(max(Max_x2,Max_y2)/(MSE2^2));\nfprintf('>>Mean Square Error2 mse2=%3.f\\n',MSE2);\nfprintf('>>Peak Signal to Noise Ratio2 psnr2=%.3f\\tdB\\n',PSNR2);\nf2=figure(2);set(f2,'Name','Testing 2: g(t)=1/2 *square(pi*t/20)+W, W~N(m,v)');\nsubplot(2,3,1), plot(t,x2,'MarkerSize',1.2), title(' original signal, Square(pulsetr) '), grid on ,axis([0 200 -1 1])\nsubplot(2,3,2), plot(t,X2,'g'),axis([0 200 -1 1]), title(' noisy signal (awgn)'), grid on,\nsubplot(2,3,3), plot(t,Y2,'r'), title(' Filtered signal,R=1e-2,Q=1e-5'), grid on,\nsubplot(2,3,4), plot(t,x2,'b--','MarkerSize',2), hold on, plot(t,X2,'g+','MarkerSize',1.2), plot(t,Y2,'r--'),...\n title(' Superposition'), legend(' original','noisy','filtered'), grid on,\nsubplot(2,3,5), plot(K2(1:100)), title(strcat(' Kalman Gain',' convergence=',num2str(K2(100)))), grid on,xlabel(' iterations')\nsubplot(2,3,6), plot(P2(1:100)), title(strcat(' variance error',' convergence=',num2str(min(P2)))), grid on,xlabel('iterations')\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/38353-1d-standard-kalman-filter-simulink-model-program/Testing1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.8962513738264114, "lm_q1q2_score": 0.8524625250966796}} {"text": "function a = c8vec_unity ( n )\n\n%*****************************************************************************80\n%\n%% C8VEC_UNITY returns the N roots of unity.\n%\n% Discussion:\n%\n% X(1:N) = exp ( 2 * PI * (0:N-1) / N )\n%\n% X(1:N)**N = ( (1,0), (1,0), ..., (1,0) ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of elements of A.\n%\n% Output, complex A(N), the N roots of unity.\n%\n\n%\n% Yes, I realize that in MATLAB \"i\" already means sqrt(-1).\n% But to me, \"i\" means an array index, and nothing else.\n%\n imaginary = sqrt ( -1.0 );\n\n for i = 1 : n\n theta = 2 * pi * ( i - 1 ) / n;\n a(i) = cos ( theta ) + imaginary * sin ( theta );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/c8vec_unity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.8962513717480382, "lm_q1q2_score": 0.852462520637352}} {"text": "function theta = vector_separation_nd ( dim_num, v1, v2, theta )\n\n%*****************************************************************************80\n%\n%% VECTOR_SEPARATION_ND finds the angular separation between vectors in ND.\n%\n% Discussion:\n%\n% Any two vectors lie in a plane, and are separated by a plane angle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the dimension of the vectors.\n%\n% Input, real V1(DIM_NUM), V2(DIM_NUM), the two vectors.\n%\n% Output, real THETA, the angle between the two vectors.\n%\n v1_norm = sqrt ( sum ( v1(1:dim_num).^2 ) );\n\n v2_norm = sqrt ( sum ( v2(1:dim_num).^2 ) );\n\n cos_theta = ( v1(1:dim_num) * v2(1:dim_num)' ) / ( v1_norm * v2_norm );\n\n theta = r8_acos ( cos_theta );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/vector_separation_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741295151718, "lm_q2_score": 0.894789464699728, "lm_q1q2_score": 0.8523532954356899}} {"text": "function [X,Y,Z] = cov3elli(x,P,ns,NP)\n\n% COV3ELLI 3D ellipsoid from Gaussian mean and covariance.\n% [X,Y,Z] = COV3ELLI(x0,P,ns,NP) gives X, Y and Z coordinates of the\n% points corresponding to the 2 biggest semi-diametres of the ellipsoid\n% defined by the covariances matrix P and centered at x0:\n%\n% (x-x0)'*(P^-1)*(x-x0) = ns^2.\n%\n% The ellipsoid can be plotted in a 3D graphic by just creating a line\n% with line(X,Y,Z).\n%\n% See also COV2ELLI, IDP3ELLI, LINE.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\npersistent spheroid\n\n% Basic shape: 2 circles at 90 degrees, with the pole at the major axis X.\nif isempty(spheroid)\n alpha = 2*pi/NP*(0:NP);\n spheroid = [...\n cos(alpha) cos(alpha)\n sin(alpha) zeros(1,NP+1)\n zeros(1,NP+1) sin(alpha)];\nend\n\n% Rotation R and semi-diameters d, obtained from P by SVD\n[R,D] = svd(P); % rotation matrix R\nd = sqrt(D); % semi-axes\n\n% spheroid -> aligned ellipsoid -> rotated ellipsoid -> ns-ellipsoid\nellip = ns*R*d*spheroid;\n\n% Choleski is not good here: ellipsoid cross not aligned w/ axis\n% C = chol(P)';\n% ellip = ns*C*spheroid;\n\n% output ready for plotting (X, Y and Z line vectors), offset by x\nX = x(1)+ellip(1,:);\nY = x(2)+ellip(2,:);\nZ = x(3)+ellip(3,:);\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/Graphics/cov3elli.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288128, "lm_q2_score": 0.8902942363098473, "lm_q1q2_score": 0.8522589144121706}} {"text": "function J = computeCost(X, y, theta)\n%COMPUTECOST Compute cost for linear regression\n% J = COMPUTECOST(X, y, theta) computes the cost of using theta as the\n% parameter for linear regression to fit the data points in X and y\n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly\nJ = 0;\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost of a particular choice of theta\n% You should set J to the cost.\n\n## for i = 1:m,\n## J = J + ((X(i, :) * theta) - y(i)) ^ 2;\n## end;\n\nJ = sum(((X * theta) - y) .^ 2);\n\nJ = 1 / (2 * m) * J;\n\n\n% =========================================================================\n\nend\n", "meta": {"author": "fewtime", "repo": "ML", "sha": "fd9679e9d6648d01e36047e97434f38c8d2d6168", "save_path": "github-repos/MATLAB/fewtime-ML", "path": "github-repos/MATLAB/fewtime-ML/ML-fd9679e9d6648d01e36047e97434f38c8d2d6168/coursera-machine-learning/machine-learning-ex1/ex1/computeCost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9572777975782054, "lm_q2_score": 0.8902942355821459, "lm_q1q2_score": 0.8522589050346486}} {"text": "function [ x, w ] = ncoh_rule ( n )\n\n%*****************************************************************************80\n%\n%% NCOH_RULE: Newton Cotes Open Half quadrature rule.\n%\n% Discussion:\n%\n% Newton Cotes Open Half rule on [-1,+1];\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 February 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the rule.\n%\n% Output, real X(N), W(N), the points and weights.\n%\n x = ( 1 : 2 : 2*n-1 )';\n x = x / ( 2 * n );\n%\n% Linear transformation from [0,1] to [-1,+1].\n%\n x = 2.0 * x - 1.0;\n%\n% Compute the weights.\n%\n x_min = -1.0;\n x_max = 1.0;\n\n w = nc_compute ( n, x_min, x_max, x );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_total_poly/ncoh_rule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475730993028, "lm_q2_score": 0.9032941962904956, "lm_q1q2_score": 0.8521203878653243}} {"text": "function [mu sigma2] = estimateGaussian(X)\n%ESTIMATEGAUSSIAN This function estimates the parameters of a \n%Gaussian distribution using the data in X\n% [mu sigma2] = estimateGaussian(X), \n% The input X is the dataset with each n-dimensional data point in one row\n% The output is an n-dimensional vector mu, the mean of the data set\n% and the variances sigma^2, an n x 1 vector\n% \n\n% Useful variables\n[m, n] = size(X);\n\n% You should return these values correctly\nmu = zeros(n, 1);\nsigma2 = zeros(n, 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the mean of the data and the variances\n% In particular, mu(i) should contain the mean of\n% the data for the i-th feature and sigma2(i)\n% should contain variance of the i-th feature.\n%\n\nmu = (1 / m) * sum(X);\nsigma2 = (1 / m) * sum((X - mu) .^ 2);\n\n% =============================================================\n\n\nend\n", "meta": {"author": "JY-112553", "repo": "machine-learning", "sha": "db9c6e5a5175739821acd97787453472b8f46cac", "save_path": "github-repos/MATLAB/JY-112553-machine-learning", "path": "github-repos/MATLAB/JY-112553-machine-learning/machine-learning-db9c6e5a5175739821acd97787453472b8f46cac/machine-learning-ex8/ex8/estimateGaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.8887588038050467, "lm_q1q2_score": 0.8519088439070156}} {"text": "function c = catalan ( n )\n\n%*****************************************************************************80\n%\n%% CATALAN computes the Catalan numbers, from C(0) to C(N).\n%\n% First values:\n%\n% C(0) 1\n% C(1) 1\n% C(2) 2\n% C(3) 5\n% C(4) 14\n% C(5) 42\n% C(6) 132\n% C(7) 429\n% C(8) 1430\n% C(9) 4862\n% C(10) 16796\n%\n% Formula:\n%\n% C(N) = (2*N)! / ( (N+1) * (N!) * (N!) )\n% = 1 / (N+1) * COMB ( 2N, N )\n% = 1 / (2N+1) * COMB ( 2N+1, N+1).\n%\n% Recursion:\n%\n% C(N) = 2 * (2*N-1) * C(N-1) / (N+1)\n% C(N) = sum ( 1 <= I <= N-1 ) C(I) * C(N-I)\n%\n% Discussion:\n%\n% The Catalan number C(N) counts:\n%\n% 1) the number of binary trees on N vertices;\n% 2) the number of ordered trees on N+1 vertices;\n% 3) the number of full binary trees on 2N+1 vertices;\n% 4) the number of well formed sequences of 2N parentheses;\n% 5) number of ways 2N ballots can be counted, in order,\n% with N positive and N negative, so that the running sum\n% is never negative;\n% 6) the number of standard tableaus in a 2 by N rectangular Ferrers diagram;\n% 7) the number of monotone functions from [1..N} to [1..N} which\n% satisfy f(i) <= i for all i;\n% 8) the number of ways to triangulate a polygon with N+2 vertices.\n%\n% Example:\n%\n% N = 3\n%\n% ()()()\n% ()(())\n% (()())\n% (())()\n% ((()))\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 June 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Dennis Stanton and Dennis White,\n% Constructive Combinatorics,\n% Springer Verlag, New York, 1986.\n%\n% Parameters:\n%\n% Input, integer N, the number of Catalan numbers desired.\n%\n% Output, integer C(1:N+1), the Catalan numbers from C(0) to C(N).\n%\n if ( n < 0 )\n c = [];\n return;\n end\n\n c(1) = 1;\n%\n% The extra parentheses ensure that the integer division is\n% done AFTER the integer multiplication.\n%\n for i = 1 : n\n c(i+1) = ( c(i) * 2 * ( 2 * i - 1 ) ) / ( i + 1 );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/catalan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257064, "lm_q2_score": 0.9046505351008904, "lm_q1q2_score": 0.8518679406518854}} {"text": "function [ a, b, c ] = sphere_triangle_vertices_to_angles ( r, v1, v2, v3 )\n\n%*****************************************************************************80\n%\n%% SPHERE_TRIANGLE_VERTICES_TO_ANGLES computes the angles of a spherical triangle.\n%\n% Discussion:\n%\n% A sphere centered at 0 in 3D satisfies the equation:\n%\n% X * X + Y * Y + Z * Z = R * R\n%\n% A spherical triangle is specified by three points on the surface\n% of the sphere.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 August 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, the radius of the sphere.\n%\n% Input, real V1(3), V2(3), V3(3), the vertices of the triangle.\n%\n% Output, real A, B, C, the angles of the spherical triangle.\n%\n\n%\n% Compute the lengths of the sides of the spherical triangle.\n%\n [ as, bs, cs ] = sphere_triangle_vertices_to_sides ( r, v1, v2, v3 );\n%\n% Get the spherical angles.\n%\n [ a, b, c ] = sphere_triangle_sides_to_angles ( r, as, bs, cs );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/sphere_triangle_vertices_to_angles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214138, "lm_q2_score": 0.8976952880018481, "lm_q1q2_score": 0.8518385609245661}} {"text": "% Derive -- Equations of Motion - 2D (planar) quad-rotor\n%\n% Model:\n% We will assume that the quadrotor is modeled by two point-masses that\n% are connected by a rigid mass-less bar. There are two motors, each of\n% which apply a force orthogonal to the connecting bar. Assume that air\n% drag is negligable.\n%\n\nclc; clear;\n\n%%%% Create symbolic variables:\nsyms x y q 'real' % horizontal and vertical position, angle (+i axis = 0)\nsyms dx dy dq 'real' % rates\nsyms ddx ddy ddq 'real' % accelerations\nsyms u1 u2 'real' % force applied by rotors\nsyms d m g 'real' % distance from center to rotor, rotor mass, gravity\n\n\n%%%% Unit vectors:\n\n% Inertial reference frame:\ni = sym([1;0;0]);\nj = sym([0;1;0]);\nk = sym([0;0;1]);\n\n% Body reference frame:\ne = cos(q)*i + sin(q)*j; % Unit vector from center to rotor 2\nn = -sin(q)*i + cos(q)*j; % Unit vector orthogonal to e\n\n\n%%%% Position vectors:\nPc = x*i + y*j; % Position of the center of the quad rotor\nP1 = Pc - d*e; % Position of rotor 1\nP2 = Pc + d*e; % Position of rotor 2\n\n\n%%%% Define the state vector and its derivative\nz = [x;y;q;dx;dy;dq]; %State\ndz = [dx;dy;dq;ddx;ddy;ddq]; %Derivative of state\n\n\n%%%% Kinematics:\n\n% Define the derivative operator. CHAIN RULE. \nderivative = @(f)( jacobian(f,z)*dz );\n\n% Velocities\ndPc = derivative(Pc);\ndP1 = derivative(P1);\ndP2 = derivative(P2);\n\n% Accelerations\nddPc = derivative(dPc);\nddP1 = derivative(dP1);\nddP2 = derivative(dP2);\n\n\n%%%% Define all force vectors:\nFg1 = -m*g*j; %Force of gravity on mass 1\nFg2 = -m*g*j; %Force of gravity on mass 2\nFu1 = u1*n; %Force due to rotor 1\nFu2 = u2*n; %Force due to rotor 1\n\n\n%%%% Force Balance:\nsumForces = Fg1 + Fg2 + Fu1 + Fu2;\nmassAccel = m*ddPc;\neqn1 = dot(sumForces-massAccel,i);\neqn2 = dot(sumForces-massAccel,j);\n\n\n%%%% Angular Momentum Balance: (about center of quad rotor)\nsumTorques = ...\n cross(P1-Pc, Fg1) + ...\n cross(P2-Pc, Fg2) + ... \n cross(P1-Pc, Fu1) + ...\n cross(P2-Pc, Fu2);\nangMomentum = ...\n cross(P1-Pc, m*ddP1) + ...\n cross(P2-Pc, m*ddP2);\neqn3 = simplify(dot(sumTorques-angMomentum, k));\n\n\n%%%% Collect and solve equations:\nvars = [ddx;ddy;ddq]; %This is what we want to find (the accelerations)\neqns = [eqn1;eqn2;eqn3]; %These are the dynamics equations\n[M,f] = equationsToMatrix(eqns, vars); % EoM are linear in acceleration\n\n% In this problem, the equations of motion are simple, so we can solve them\n% analytically using the \"\\\" command. For more complicated systems, it is\n% typically much faster to do this solve numerically at run-time.\nsoln = simplify(M\\f); \nddxSoln = soln(1);\nddySoln = soln(2);\nddqSoln = soln(3);\n\n\n%%%% Automatically write out dynamics function:\n% This will automatically optimize the function to minimize computation\n% time. Not too important here, but makes a big difference for complicated\n% functions. It also prevents copy-paste errors.\nmatlabFunction(...\n ddxSoln, ddySoln, ddqSoln,...\n 'file','autoGen_dynamics.m',...\n 'vars',{q,u1,u2,m,g,d},...\n 'outputs',{'ddx','ddy','ddq'});\n\n\n%%%% Display the solution to the user:\ndisp(['ddx = ' ddxSoln]);\ndisp(['ddy = ' ddySoln]);\ndisp(['ddq = ' ddqSoln]);\n\n\n\n\n", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/demo/quadRotor2d/Derive_EoM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.8962513738264114, "lm_q1q2_score": 0.8518071463679805}} {"text": "function v=polyValNewton(z,a,c)\n%POLYVALNEWTON Evaluate a set of polynomial given in Newton's form at a\n% desired set of points. This is useful when given a set of\n% Hermite interpolating polynomials for interpolating a\n% vector.\n%\n%INPUTS: z A numPointsX1 or 1XnumPoints vector of scalar points where the\n% values of the numDim polynomials are desired.\n% a A numDimXn matrix of polynomial coefficients for numDim\n% polynomials, as described below.\n% c A numDim X(n-1) matrix of the control points associated with\n% each of the numDim polynomial in Newton's form, which might be\n% the control points used in the HermiteInterpPoly function.\n%\n%OUTPUTS: v The numDimXnumPoints matrix of values of the polynomials\n% evaluated at the points in z.\n%\n%A polynomial function in Newton's form evaluated at point z has the form\n%y(z)=a(1)+sum_{k=1}^{n-1}a(k+1)(z-c(1))*(z-c(2))*...*(z-c(k))\n%This function just evaluates multiple scalar polynomials.\n%\n%The algorithm is based on VALUE from Chapter 19 of [1] to handle vector\n%values; a loop is used here.\n%\n%Newton's polynomial form arises when dealing with Hermite interpolating\n%polynomials as is discussed in Section 2.1.3 of [2] and in Chapters 3.3\n%and 3.4 of [3].\n%\n%REFERENCES:\n%[1] A. Nijenhuis and H. S. Wilf, Combinatorial Algorithms for Computers\n% and Calculators, 2nd ed. New York: Academic press, 1978.\n%[2] J. Stoer and R. Bulirsch, Introduction to Numerical Analysis, 3rd ed.\n% New York: Springer, 2002.\n%[3] R. L. Burden and J. D. Faires, Numerical Analysis, 9th ed. Boston, MA:\n% Brooks/Cole, 2011.\n%\n%March 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumDim=size(a,1);\nnumPoints=length(z);\n\nv=zeros(numDim,numPoints);\nfor curDim=1:numDim\n v(curDim,:)=polyValNewtonScalar(z,a(curDim,:),c(curDim,:));\nend\nend\n\nfunction v=polyValNewtonScalar(z,a,c)\n%Below is VALUE from Chapter 19 of [1]\n%\n%REFERENCES:\n%A. Nijenhuis and H. S. Wilf, Combinatorial Algorithms for Computers\n%and Calculators, 2nd ed. New York: Academic press, 1978.\n\nn=length(a);\n\nv=ones(size(z))*a(n);\nfor k=(n-1):-1:1\n v=(z-c(k)).*v+a(k);\nend\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Polynomials/polyValNewton.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317102, "lm_q2_score": 0.9184802429095672, "lm_q1q2_score": 0.851764861363309}} {"text": "function y = mnorm_pdf(x,mu,S)\n%MNORM_PDF Multivariate-Normal probability density function (pdf).\n%\n% Description\n% Y = MNORM_PDF(X,MU,SIGMA) Returns the multivariate-normal\n% pdf with mean, MU, and covariance matrix, SIGMA, at the values in X.\n%\n% Default values for MU and SIGMA are 0 and 1 respectively.\n%\n% Copyright (c) 1998-2005 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\nif nargin < 3, \n S = 1;\nend\n\nif nargin < 2;\n mu = 0;\nend\n\nif nargin < 1, \n error('Requires at least one input argument.');\nend\n\n[n,m]=size(x);\nxmu=x-repmat(mu,n,1); \nif ~issparse(S)\n % Use Cholesky decomposition, since it is faster and\n % numerically more stable.\n L=chol(S,'lower');\n y=zeros(n,1);\n for i1=1:n\n b=L\\xmu(i1,:)';\n y(i1)=-b'*b;\n end\n y=exp(.5*y-sum(log(diag(L)))-.5*m*log(2*pi));\nelse\n LD = ldlchol(S);\n y=zeros(n,1);\n for i1=1:n\n xmui1=xmu(i1,:)';\n y(i1)=-xmui1'*ldlsolve(LD,xmui1);\n end\n y=exp(0.5*(y-sum(log(diag(LD)))-m*log(2*pi)));\nend\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/dist/mnorm_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877684006775, "lm_q2_score": 0.8774767874818408, "lm_q1q2_score": 0.8517559846641436}} {"text": "function [J, grad] = costFunction(theta, X, y)\n%COSTFUNCTION Compute cost and gradient for logistic regression\n% J = COSTFUNCTION(theta, X, y) computes the cost of using theta as the\n% parameter for logistic regression and the gradient of the cost\n% w.r.t. to the parameters.\n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost of a particular choice of theta.\n% You should set J to the cost.\n% Compute the partial derivatives and set grad to the partial\n% derivatives of the cost w.r.t. each parameter in theta\n%\n% Note: grad should have the same dimensions as theta\n%\n\n% X.shape = [m, n], y.shape = [m, 1], theta.shape = [n, 1]\n% y_pred = sigmoid(X*theta), y_pred.shape = [m, 1]\ny_pred = sigmoid(X*theta);\nJ = -1.0 / m * sum( y.*log(y_pred) + (1-y).*log(1-y_pred) );\ngrad = 1.0 / m .* (X' * (y_pred - y));\n\n\n\n\n\n% =============================================================\n\nend\n", "meta": {"author": "imLogM", "repo": "Machine_Learning_AndrewNg", "sha": "1d499e8e2738032dc85e869ba55c32eb24da288d", "save_path": "github-repos/MATLAB/imLogM-Machine_Learning_AndrewNg", "path": "github-repos/MATLAB/imLogM-Machine_Learning_AndrewNg/Machine_Learning_AndrewNg-1d499e8e2738032dc85e869ba55c32eb24da288d/machine-learning-ex2/ex2/costFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360931, "lm_q2_score": 0.8902942290328345, "lm_q1q2_score": 0.851685908655929}} {"text": "function [U, S] = pca(X)\n%PCA Run principal component analysis on the dataset X\n% [U, S, X] = pca(X) computes eigenvectors of the covariance matrix of X\n% Returns the eigenvectors U, the eigenvalues (on diagonal) in S\n%\n\n% Useful values\n[m, n] = size(X);\n\n% You need to return the following variables correctly.\nU = zeros(n);\nS = zeros(n);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: You should first compute the covariance matrix. Then, you\n% should use the \"svd\" function to compute the eigenvectors\n% and eigenvalues of the covariance matrix. \n%\n% Note: When computing the covariance matrix, remember to divide by m (the\n% number of examples).\n%\n\nSigma = (1/m) * (X'*X);\n[U, S, V] = svd(Sigma);\n\n% =========================================================================\n\nend\n", "meta": {"author": "zlotus", "repo": "Coursera_Machine_Learning_Exercises", "sha": "3000f402e8e495b7c49e80c0ce4a58d42bf6b430", "save_path": "github-repos/MATLAB/zlotus-Coursera_Machine_Learning_Exercises", "path": "github-repos/MATLAB/zlotus-Coursera_Machine_Learning_Exercises/Coursera_Machine_Learning_Exercises-3000f402e8e495b7c49e80c0ce4a58d42bf6b430/ex7/pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.9059898216525933, "lm_q1q2_score": 0.8515519251279573}} {"text": "function [ mD ] = CreateGradientOperator( numRows, numCols )\n% ----------------------------------------------------------------------------------------------- %\n% [ mD ] = CreateGradientOperator( numRows, numCols )\n% Generates a Convolution Matrix for the 2D Gradient of the form [-1, 1].\n% Input:\n% - numRows - Number of Rows.\n% Number of rows of the image to be convolved.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: {1, 2, 3, ...}.\n% - numCols - Number of Columns.\n% Number of columns of the image to be convolved.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: {1, 2, 3, ...}.\n% Output:\n% - mD - Convolution Matrix.\n% The output convolution matrix. The product of\n% the matrix 'mD' and and image 'mI' in its\n% column stack form ('mD * mI(:)') is equivalent\n% to the convolution of 'mI' with the kernel\n% using the valid convolution shape\n% ('conv2(mI, mH, 'valid')').\n% Structure: Matrix (Sparse).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% References:\n% 1. See my notes - 'Matrix Form of Image Gradient.md'.\n% Remarks:\n% 1. The function basically calculates the Convolution Matrix for the\n% kernel [-1, 1] with operation mode of Valid Convolution. See\n% 'CreateGradientOperatorUnitTest()' for the exact operation.\n% 2. The matrix 'mT' is the template for creating Vertical / Horizontal\n% derivative operator.\n% TODO:\n% 1. \n% Release Notes:\n% - 1.0.000 25/03/2020 Royi Avital\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\n% Vertical Operator - T(numRows)\nmT = spdiags([ones(numRows - 1, 1), -ones(numRows - 1, 1)], [0, 1], numRows - 1, numRows);\nmDv = kron(eye(numCols), mT);\n\n% Vertical Operator - T(numCols)\nmT = spdiags([ones(numCols, 1), -ones(numCols, 1)], [0, 1], numCols - 1, numCols);\nmDh = kron(mT, eye(numRows));\n\nmD = [mDv; mDh];\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/Mathematics/Q3164164/CreateGradientOperator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620550745211, "lm_q2_score": 0.8872045907347108, "lm_q1q2_score": 0.8515053012750954}} {"text": "function [U, S] = pca(X)\n%PCA Run principal component analysis on the dataset X\n% [U, S, X] = pca(X) computes eigenvectors of the covariance matrix of X\n% Returns the eigenvectors U, the eigenvalues (on diagonal) in S\n%\n\n% Useful values\n[m, n] = size(X);\n\n% You need to return the following variables correctly.\nU = zeros(n);\nS = zeros(n);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: You should first compute the covariance matrix. Then, you\n% should use the \"svd\" function to compute the eigenvectors\n% and eigenvalues of the covariance matrix. \n%\n% Note: When computing the covariance matrix, remember to divide by m (the\n% number of examples).\n%\n\nSigma = 1 / m * X' * X;\n[U, S, V] = svd(Sigma);\n\n% =========================================================================\n\nend\n", "meta": {"author": "merwan", "repo": "ml-class", "sha": "0b06b73d4aac0b8d7c726325200c3781b5c9d3b0", "save_path": "github-repos/MATLAB/merwan-ml-class", "path": "github-repos/MATLAB/merwan-ml-class/ml-class-0b06b73d4aac0b8d7c726325200c3781b5c9d3b0/mlclass-ex7/pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240142763572, "lm_q2_score": 0.907312229506029, "lm_q1q2_score": 0.8511713909462274}} {"text": "function [theta] = normalEqn(X, y)\n%NORMALEQN Computes the closed-form solution to linear regression \n% NORMALEQN(X,y) computes the closed-form solution to linear \n% regression using the normal equations.\n\ntheta = zeros(size(X, 2), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the code to compute the closed form solution\n% to linear regression and put the result in theta.\n%\n\n% ---------------------- Sample Solution ----------------------\n\n\ntheta = pinv((X'*X))*X'*y;\n\n% -------------------------------------------------------------\n\n\n% ============================================================\n\nend\n", "meta": {"author": "Ayatans", "repo": "Machine-Learning-homework", "sha": "4550cfc0426c9da8072dff165130fff40d138c10", "save_path": "github-repos/MATLAB/Ayatans-Machine-Learning-homework", "path": "github-repos/MATLAB/Ayatans-Machine-Learning-homework/Machine-Learning-homework-4550cfc0426c9da8072dff165130fff40d138c10/machine-learning-ex1/ex1/normalEqn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9559813551535005, "lm_q2_score": 0.8902942297605357, "lm_q1q2_score": 0.8511046842518188}} {"text": "%% Factorial\nfunction [f] = find_factorial(n)\n% calculate the factorial of a positive integer n\n% factorial(n)can be used directly as a default function of Matlab\n\nintegerTest= ~mod(n,1); %it returns 0 if value is not an integer.\nif integerTest== 0 || n < 0; % checking n to be positive & integer \n disp('Error! your number muss be positive and integer');\nelse\n f = 1;\n for i = 1:n\n f = f*i;\n end\n disp(['factorial of ',num2str(n),' is: ',num2str(f)]);\nend\nend\n\n", "meta": {"author": "TheAlgorithms", "repo": "MATLAB-Octave", "sha": "e150b77ad256de46c1ce3815c3d7945ac4fc28dc", "save_path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave", "path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave/MATLAB-Octave-e150b77ad256de46c1ce3815c3d7945ac4fc28dc/algorithms/maths/find_factorial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9591542840900507, "lm_q2_score": 0.8872045877523147, "lm_q1q2_score": 0.8509660812069799}} {"text": "% ------------------------GOLDEN SECTION METHOD----------------------------\n% -------------------------------------------------------------------------\n% Copyright (c) 2009, Katarzyna Zarnowiec, all rights reserved \n% mailto: katarzyna.zarnowiec@gmail.com\n% -------------------------------------------------------------------------\n\nfigure; hold on;\n\na=0; % start of interval\nb=2; % end of interval\nepsilon=0.000001; % accuracy value\niter= 50; % maximum number of iterations\ntau=double((sqrt(5)-1)/2); % golden proportion coefficient, around 0.618\nk=0; % number of iterations\n\n\nx1=a+(1-tau)*(b-a); % computing x values\nx2=a+tau*(b-a);\n\nf_x1=f(x1); % computing values in x points\nf_x2=f(x2);\n\nplot(x1,f_x1,'rx') % plotting x\nplot(x2,f_x2,'rx')\n\nwhile ((abs(b-a)>epsilon) && (k