{"text": "function [km3] = l2km3(l)\n% Convert volume from liters to cubic kilometers. \n% Chad Greene 2012\nkm3 = l*1e-12;", "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/35258-unit-converters/unit_converters/l2km3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297807787536, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6999816689372349}} {"text": "% predicting numerical values using Linear Regression\nclear all;\nformat long\ndisp('===== Linear Regression ====');\ndisp('Reading featur vector');\n\n\n\nIndices = crossvalind('Kfold', 26548, 10);\nfigure;\n\nsubplot(3,2,1);\n\nfor feat = 1:3\n MSEarray =[];\n elapsedarray =[];\n for crossvalidateIter = 1:10\n (fprintf('%d',crossvalidateIter));\n featurs = csvread('data\\forWeka_featuresonly.csv');\n num_data = size(featurs,1); %5000;\n %disp(sprintf('Number of datapoints %d',num_data))\n \n possiblefeaturizations = {'bernouli', 'tfidf','multinomial'};\n %featurization = 'bernouli'%'tfidf'%'tfidf'%'multinomial'%'tfidf' %'multinomial'; % 'bernouli', 'tfidf'\n featurization = possiblefeaturizations{feat};\n \n \n featurs = featurs(:,2:size(featurs,2));\n if strcmp(featurization,'multinomial')\n %just pass\n elseif strcmp(featurization,'bernouli')\n featurs = bernoulli(featurs);\n elseif strcmp(featurization,'tfidf')\n featurs = tfidf(featurs);\n end\n \n size_training = floor(.9*num_data);\n \n \n trainingset = featurs(Indices~=crossvalidateIter,:);\n testset = featurs(Indices==crossvalidateIter,:);\n \n \n %disp('Splitting up data into training/test sets');\n [num,txt,raw] = xlsread('data\\final104.xls');\n \n % reading the description of each shoe\n descriptions = raw(2:size(raw,1),2);\n style_ratings = num(1:size(num,1),1);\n comfort_ratings = num(1:size(num,1),4);\n overal_ratings = num(1:size(num,1),5);\n \n % only take m data points\n m=num_data;\n descriptions = descriptions(1:m);\n style_ratings = style_ratings(1:m);\n comfort_ratings = comfort_ratings(1:m);\n overal_ratings = overal_ratings(1:m);\n \n responsevals = [style_ratings, comfort_ratings, overal_ratings];\n \n \n responsevals_training = responsevals(Indices~=crossvalidateIter,:);\n responsevals_test = responsevals(Indices==crossvalidateIter,:);\n \n %disp('Linear Regression');\n % \n \n tic;\n \n predictions = [];\n actual = [];\n for i =1:3\n a = responsevals_training(:,i);\n b = responsevals_test(:,i)';\n regresscoeff = regress(a, trainingset);\n C2 = (regresscoeff'*(testset'));\n predictions = [predictions, C2'];\n actual = [actual, b'];\n end\n \n \n MSE = mean(sum(((predictions-actual).^2)'))\n elapsed = toc;\n MSEarray = [MSEarray MSE];\n elapsedarray = [elapsedarray elapsed];\n \n end\n featurization = possiblefeaturizations{feat}\n fprintf('Avergae MSE for Linear Regression is %0.10f\\n', mean(MSEarray));\n subplot(3,2,feat*2-1)\n plot(MSEarray,'-o');\n title(strcat('MSE for Linear Regression (',featurization,') ', sprintf(' avergae MSE = %0.10f\\n', mean(MSEarray))));\n xlabel('10 fold cross-validation (iteration no)')\n ylabel('MSE')\n subplot(3,2,feat*2)\n plot(elapsedarray,'-o');\n title(strcat('Elapsed time for Linear Regression (',featurization, ') ' , sprintf(' avergae elapsed time = %0.10f\\n', mean(elapsedarray))));\n xlabel('10 fold cross-validation (iteration no)')\n ylabel('Elapsed Time')\n drawnow;\nend\n\n\n\n", "meta": {"author": "faridani", "repo": "MatlabNLP", "sha": "e18e8bc44ecbc8bb6aa57312c1ee22930f805a6f", "save_path": "github-repos/MATLAB/faridani-MatlabNLP", "path": "github-repos/MATLAB/faridani-MatlabNLP/MatlabNLP-e18e8bc44ecbc8bb6aa57312c1ee22930f805a6f/sandboxes/siamak sandbox/multivariate6D/linearRegression_generalized_crossvalidation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6999709139366403}} {"text": "function [ H_output ] = homography_linearization( H, point, anchor_points )\nvega = 5;\n\n% Obtain kernel: Student\u2019s t-weighting \nalpha = (1 + pdist2(point,anchor_points)./vega).^(-(vega+1)/2);\nalpha = alpha./sum(alpha);\n\n% Linearization using Taylor series\nH_output = zeros(3,3);\n\nfor i = 1:size(anchor_points,1) \n A = taylor_series( H, anchor_points(i,:));\n \n H_output = H_output + alpha(i).*A;\nend\n\nend\n\nfunction [ A ] = taylor_series( H, p)\n% The first two terms of Taylor series provide the best linearization of H\n% H:3*3 p:1*2 \n\nh1 = H(1,1); h2 = H(1,2); h3 = H(1,3);\nh4 = H(2,1); h5 = H(2,2); h6 = H(2,3);\nh7 = H(3,1); h8 = H(3,2); h9 = H(3,3);\nx1 = p(1,1);x2 = p(1,2);\n\ndy1dx1 = h1/(h9 + h7*x1 + h8*x2) - (h7*(h3 + h1*x1 + h2*x2))/(h9 + h7*x1 + h8*x2)^2;\ndy1dx2 = h2/(h9 + h7*x1 + h8*x2) - (h8*(h3 + h1*x1 + h2*x2))/(h9 + h7*x1 + h8*x2)^2;\ndy2dx1 = h4/(h9 + h7*x1 + h8*x2) - (h7*(h6 + h4*x1 + h5*x2))/(h9 + h7*x1 + h8*x2)^2;\ndy2dx2 = h5/(h9 + h7*x1 + h8*x2) - (h8*(h6 + h4*x1 + h5*x2))/(h9 + h7*x1 + h8*x2)^2;\n\ny1 = (h3 + h1*x1 + h2*x2)/(h9 + h7*x1 + h8*x2);\ny2 = (h6 + h4*x1 + h5*x2)/(h9 + h7*x1 + h8*x2);\n\nA = [dy1dx1 dy1dx2 (y1 - x1*dy1dx1 - x2*dy1dx2);\n dy2dx1 dy2dx2 (y2 - x1*dy2dx1 - x2*dy2dx2);\n 0 0 1];\nend\n", "meta": {"author": "YaqiLYU", "repo": "AANAP", "sha": "59c2f4614293e83166fd7f34ec6c47386e054482", "save_path": "github-repos/MATLAB/YaqiLYU-AANAP", "path": "github-repos/MATLAB/YaqiLYU-AANAP/AANAP-59c2f4614293e83166fd7f34ec6c47386e054482/homography_linearization.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565738, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6999708968912737}} {"text": "function M = grassmannfactory(n, p, k)\n% Returns a manifold struct to optimize over the space of vector subspaces.\n%\n% function M = grassmannfactory(n, p)\n% function M = grassmannfactory(n, p, k)\n%\n% Grassmann manifold: each point on this manifold is a collection of k\n% vector subspaces of dimension p embedded in R^n.\n%\n% The metric is obtained by making the Grassmannian a Riemannian quotient\n% manifold of the Stiefel manifold, i.e., the manifold of orthonormal\n% matrices, itself endowed with a metric by making it a Riemannian\n% submanifold of the Euclidean space, endowed with the usual inner product.\n% In short: it is the usual metric used in most cases.\n% \n% This structure deals with matrices X of size n x p x k (or n x p if\n% k = 1, which is the default) such that each n x p matrix is orthonormal,\n% i.e., X'*X = eye(p) if k = 1, or X(:, :, i)' * X(:, :, i) = eye(p) for\n% i = 1 : k if k > 1. Each n x p matrix is a numerical representation of\n% the vector subspace its columns span.\n%\n% By default, k = 1.\n%\n% See also: stiefelfactory\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Dec. 30, 2012.\n% Contributors: \n% Change log: \n% March 22, 2013 (NB) : Implemented geodesic distance.\n% April 17, 2013 (NB) : Retraction changed to the polar decomposition, so\n% that the vector transport is now correct, in the\n% sense that it is compatible with the retraction,\n% i.e., transporting a tangent vector G from U to V\n% where V = Retr(U, H) will give Z, and\n% transporting GQ from UQ to VQ will give ZQ: there\n% is no dependence on the representation, which is\n% as it should be. Notice that the polar\n% factorization requires an SVD whereas the qfactor\n% retraction requires a QR decomposition, which is\n% cheaper. Hence, if the retraction happens to be a\n% bottleneck in your application and you are not\n% using vector transports, you may want to replace\n% the retraction with a qfactor.\n% July 4, 2013 (NB) : Added support for the logarithmic map 'log'.\n% July 5, 2013 (NB) : Added support for ehess2rhess.\n% June 24, 2014 (NB) : Small bug fix in the retraction, and added final\n% re-orthonormalization at the end of the\n% exponential map. This follows discussions on the\n% forum where it appeared there is a significant\n% loss in orthonormality without that extra step.\n% Also changed the randvec function so that it now\n% returns a globally normalized vector, not a\n% vector where each component is normalized (this\n% only matters if k>1).\n\n assert(n >= p, ...\n ['The dimension n of the ambient space must be larger ' ...\n\t 'than the dimension p of the subspaces.']);\n \n if ~exist('k', 'var') || isempty(k)\n k = 1;\n end\n \n if k == 1\n M.name = @() sprintf('Grassmann manifold Gr(%d, %d)', n, p);\n elseif k > 1\n M.name = @() sprintf('Multi Grassmann manifold Gr(%d, %d)^%d', ...\n n, p, k);\n else\n error('k must be an integer no less than 1.');\n end\n \n M.dim = @() k*p*(n-p);\n \n M.inner = @(x, d1, d2) d1(:).'*d2(:);\n \n M.norm = @(x, d) norm(d(:));\n \n M.dist = @distance;\n function d = distance(x, y)\n square_d = 0;\n XtY = multiprod(multitransp(x), y);\n for i = 1 : k\n cos_princ_angle = svd(XtY(:, :, i));\n % Two next instructions not necessary: the imaginary parts that\n % would appear if the cosines are not between -1 and 1 when\n % passed to the acos function would be very small, and would\n % thus vanish when the norm is taken.\n % cos_princ_angle = min(cos_princ_angle, 1);\n % cos_princ_angle = max(cos_princ_angle, -1);\n square_d = square_d + norm(acos(cos_princ_angle))^2;\n end\n d = sqrt(square_d);\n end\n \n M.typicaldist = @() sqrt(p*k);\n \n % Orthogonal projection of an ambient vector U to the horizontal space\n % at X.\n M.proj = @projection;\n function Up = projection(X, U)\n \n XtU = multiprod(multitransp(X), U);\n Up = U - multiprod(X, XtU);\n\n end\n \n M.tangent = M.proj;\n \n\tM.egrad2rgrad = M.proj;\n \n M.ehess2rhess = @ehess2rhess;\n function rhess = ehess2rhess(X, egrad, ehess, H)\n PXehess = projection(X, ehess);\n XtG = multiprod(multitransp(X), egrad);\n HXtG = multiprod(H, XtG);\n rhess = PXehess - HXtG;\n end\n \n M.retr = @retraction;\n function Y = retraction(X, U, t)\n if nargin < 3\n t = 1.0;\n end\n Y = X + t*U;\n for i = 1 : k\n % We do not need to worry about flipping signs of columns here,\n % since only the column space is important, not the actual\n % columns. Compare this with the Stiefel manifold.\n % [Q, unused] = qr(Y(:, :, i), 0); %#ok\n % Y(:, :, i) = Q;\n \n % Compute the polar factorization of Y = X+tU\n [u, s, v] = svd(Y(:, :, i), 'econ'); %#ok\n Y(:, :, i) = u*v';\n end\n end\n \n M.exp = @exponential;\n function Y = exponential(X, U, t)\n if nargin == 3\n tU = t*U;\n else\n tU = U;\n end\n Y = zeros(size(X));\n for i = 1 : k\n [u s v] = svd(tU(:, :, i), 0);\n cos_s = diag(cos(diag(s)));\n sin_s = diag(sin(diag(s)));\n Y(:, :, i) = X(:, :, i)*v*cos_s*v' + u*sin_s*v';\n % From numerical experiments, it seems necessary to\n % re-orthonormalize. This is overall quite expensive.\n [q, unused] = qr(Y(:, :, i), 0); %#ok\n Y(:, :, i) = q;\n end\n end\n\n % Test code for the logarithm:\n % Gr = grassmannfactory(5, 2, 3);\n % x = Gr.rand()\n % y = Gr.rand()\n % u = Gr.log(x, y)\n % Gr.dist(x, y) % These two numbers should\n % Gr.norm(x, u) % be the same.\n % z = Gr.exp(x, u) % z needs not be the same matrix as y, but it should\n % v = Gr.log(x, z) % be the same point as y on Grassmann: dist almost 0.\n M.log = @logarithm;\n function U = logarithm(X, Y)\n U = zeros(n, p, k);\n for i = 1 : k\n x = X(:, :, i);\n y = Y(:, :, i);\n ytx = y.'*x;\n At = y.'-ytx*x.';\n Bt = ytx\\At;\n [u, s, v] = svd(Bt.', 'econ');\n\n u = u(:, 1:p);\n s = diag(s);\n s = s(1:p);\n v = v(:, 1:p);\n\n U(:, :, i) = u*diag(atan(s))*v.';\n end\n end\n\n M.hash = @(X) ['z' hashmd5(X(:))];\n \n M.rand = @random;\n function X = random()\n X = zeros(n, p, k);\n for i = 1 : k\n [Q, unused] = qr(randn(n, p), 0); %#ok\n X(:, :, i) = Q;\n end\n end\n \n M.randvec = @randomvec;\n function U = randomvec(X)\n U = projection(X, randn(n, p, k));\n U = U / norm(U(:));\n end\n \n M.lincomb = @lincomb;\n \n M.zerovec = @(x) zeros(n, p, k);\n \n % This transport is compatible with the polar retraction.\n M.transp = @(x1, x2, d) projection(x2, d);\n \n M.vec = @(x, u_mat) u_mat(:);\n M.mat = @(x, u_vec) reshape(u_vec, [n, p, k]);\n M.vecmatareisometries = @() true;\n\nend\n\n% Linear combination of tangent vectors\nfunction d = lincomb(x, a1, d1, a2, d2) %#ok\n\n if nargin == 3\n d = a1*d1;\n elseif nargin == 5\n d = a1*d1 + a2*d2;\n else\n error('Bad use of grassmann.lincomb.');\n end\n\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/manopt/manopt/manifolds/grassmann/grassmannfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.6999548154592152}} {"text": "function [ r, info ] = r8po_fa ( n, a )\n\n%*****************************************************************************80\n%\n%% R8PO_FA factors a R8PO matrix.\n%\n% Discussion:\n%\n% The R8PO storage format is appropriate for a symmetric positive definite \n% matrix and its inverse. (The Cholesky factor of a R8PO matrix is an\n% upper triangular matrix, so it will be in R8GE storage format.)\n%\n% Only the diagonal and upper triangle of the square array are used.\n% This same storage scheme is used when the matrix is factored by\n% R8PO_FA, or inverted by R8PO_INVERSE. For clarity, the lower triangle\n% is set to zero.\n%\n% The positive definite symmetric matrix A has a Cholesky factorization\n% of the form:\n%\n% A = R' * R\n%\n% where R is an upper triangular matrix with positive elements on\n% its diagonal. This routine overwrites the matrix A with its\n% factor R.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 February 2004\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Dongarra, Bunch, Moler, Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real A(N,N), the matrix in R8PO storage.\n%\n% Output, real R(N,N), the Cholesky factor R in R8GE storage.\n%\n% Output, integer INFO, error flag.\n% 0, normal return.\n% K, error condition. The principal minor of order K is not\n% positive definite, and the factorization was not completed.\n%\n r(1:n,1:n) = a(1:n,1:n);\n\n for j = 1 : n\n\n for k = 1 : j - 1\n t = 0.0;\n for i = 1 : k-1\n t = t + r(i,k) * r(i,j);\n end\n r(k,j) = ( r(k,j) - t ) / r(k,k);\n end\n\n t = 0.0;\n for i = 1 : j - 1\n t = t + r(i,j)^2;\n end\n\n s = r(j,j) - t;\n\n if ( s <= 0.0 )\n info = j;\n return;\n end\n\n r(j,j) = sqrt ( s );\n\n end\n\n info = 0;\n%\n% Since the Cholesky factor is stored in R8GE format, be sure to\n% zero out the lower triangle.\n%\n for i = 1 : n\n for j = 1 : i-1\n r(i,j) = 0.0;\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/linplus/r8po_fa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.6998666613685619}} {"text": "function c = cond_2x2(A)\n%COND Condition number with respect to inversion.\n% COND2d(X) returns the 2-norm condition number (the ratio of the\n% largest singular value of X to the smallest). Large condition\n% numbers indicate a nearly singular matrix.\n%\n% COND(X,P) returns the condition number of X in 2-norm:\n%\n% NORM(X,2) * NORM(INV(X),2). \n%\n% Class support for input X:\n% float: double, single\n%\n% See also RCOND, CONDEST, CONDEIG, NORM, NORMEST.\n\n% Copied from MATLAB's cond function. \n\nassert(~issparse(A));\n[d1,d2,n] = size(A);\nassert(d1==2 && d2==2);\nA = reshape(A,[4,n]);\n\n% A2 = A'*A \ntmp = A(1,:).*A(3,:) + A(2,:).*A(4,:);\nA2 = cat(1,A(1,:).^2 + A(2,:).^2,...\n tmp,tmp,...\n A(3,:).^2 + A(4,:).^2);\n\ns = sqrt(eigs_2x2(A2));\nc = zeros([1,n],class(A));\n\nissing = any(s==0,1);\nc(issing) = inf;\nc(~issing) = max(s(:,~issing),[],1)./min(s(:,~issing),[],1);\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/misc/cond_2x2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.699866655567751}} {"text": "%\n% run an example of ordfilt3 on a noisy sphere. The example is the same as\n% that written by Olivier Salvado.\n\nclear\nrandn('seed',0)\n\n[x,y,z] = meshgrid(1:100,1:100,1:100);\nsphere = 20 + 200*( ( sqrt((x-50).^2+(y-50).^2+(z-50).^2) ) < 40 );\nclear x y z\nsphere = uint8(1*sphere + 50*randn(size(sphere)));\n\n% -- median filter\ntic\n[Vr] = ordfilt3(sphere,'med',5);\ntoc\nclf\n% -- compare to box filter\nsubplot(221)\np1 = patch(isosurface(sphere,100), ...\n 'FaceColor','blue','EdgeColor','none');\np2 = patch(isocaps(sphere,100), ...\n 'FaceColor','interp','EdgeColor','none');\nisonormals(sphere,p1)\nview(3); axis vis3d square\ncamlight; lighting phong\n\nsubplot(222)\np1 = patch(isosurface(Vr,100), ...\n 'FaceColor','blue','EdgeColor','none');\np2 = patch(isocaps(Vr,100), ...\n 'FaceColor','interp','EdgeColor','none');\nisonormals(Vr,p1)\nview(3); axis vis3d square\ncamlight; lighting phong\n\n%%\n% show some slice\nfor k=1:20,\n subplot(223)\n imagesc( sphere(:,:,k) ,[0 255]),axis image\n title('original')\n \n subplot(224)\n imagesc( Vr(:,:,k) ,[0 255]),axis image\n title('Filtered with a 3D median filter')\n\n drawnow\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/22044-ordfilt3/ordfilt3_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.699858803753171}} {"text": "function yi = finterp1(x,y,xi,outOfRangeVal)\n%\"finterp1\"\n% Fast 1-D linear interpolation of regularly spaced vector, to regularly\n% spaced vector/point.\n%\n% This function does the following\n% transformation:\tt = (xi-x(1))/(x(end)-x(1))\n% yi = y(1) + t ( y(end) - y(1) )\n%\n% x & y must be a monotonically increasing vector/array;\n%\n% Written DK 09-27-06\n%\n% Usage:\n% yi = finterp1(x,y,xi,outOfRangeVal);\n%\n% See also FINTERP2, FINTERP3, FINTERP3NOMESH ,INTERP1, INTERP2, INTERP3\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR 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% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\n\nif ~exist('outOfRangeVal')\n outOfRangeVal = NaN;\nend\n\nn = length(x);\n% check if all the parameters passed are of the same class\nsuperiorfloat(x,y,xi);\n\ntry\n h = diff(x);\n [ignore,k] = histc(xi,x);\n k(xi=x(n)) = n-1;\n t = (xi - x(k))./h(k);\ncatch % if the vector is monotonically decreasing\n t = (xi-x(1))/(x(end)-x(1));\n k = y(1) + t*(y(end) - y(1));\n k = round(k);\n k(xi=x(n)) = n-1;\nend\n\nyi = y(k)+t.*(y(k+1) - y(k));\n\n% APA Check\n% x = x(:);\n% xi = xi(:);\n% y = y(:);\n% dxV = [diff(x); 1]; %DUMMY 1\n% if all(dxV(1:end-1)<0)\n% x = flipud(x);\n% y = flipud(y);\n% dxV = [diff(x); 1];\n% end \n% dyV = [diff(y); 1]; %DUMMY 1\n% indNaN = xi < min(x) | xi> max(x);\n% xi(indNaN) = x(1); %assign DUMMY value\n% [jnk,binIndex] = histc(xi,x);\n% slopeV = dyV./dxV;\n% slopeV(binIndex==length(x)) = 0;\n% yi = y(binIndex) + slopeV(binIndex).*(xi-x(binIndex));\n% yi(indNaN) = outOfRangeVal;\n% \n% return;\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/finterp1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.699858795711846}} {"text": "function [C,t,err] = cubic_vertex_removal(C1,C2,varargin)\n % CUBIC_VERTEX_REMOVAL Given a G\u00b9 continuous sequence of cubic B\u00e9zier curves,\n % optimize the positions of a new single curve to minimize its integrated\n % squared distance to those curves. This requires both estimating the\n % parameterization mapping between the inputs and output (non-linear problem)\n % and then computing the optimal positions as a linear least squares problem.\n % \n % C = cubic_vertex_removal(C1,C2)\n % [C,t,err] = cubic_vertex_removal(C1,C2,'ParameterName',ParameterValue,\u2026)\n %\n % Inputs:\n % C1 4 by dim list of first curves control point positions\n % C2 4 by dim list of second curves control point positions, it's assumed\n % that C1(4,:) == C2(1,:) and C1(4,:) - C1(3,:) = s * (C2(2,:) - C2(1,:))\n % for some s>= 0.\n % Optional:\n % 'Method' followed by one of the following:\n % {'perfect'} use root finding. This is fastest when you only care about\n % finding a perfect fit. It may lead to a very poor approximate when\n % a perfect fit is not possible. A perfect fit is when \n % `[C1,C2] = cubic_split(C,t)`. If this is the case, then the\n % returned `err` for this method should be very close to zero. (Note\n % that \"perfect fit\" \u2192 err=0 but err=0 does not necessarily imply\n % \"perfect fit\". \n % 'iterative' use iterative method. This is slower but more accurate\n % when a perfect fit is not possible.\n % 'MaxIter' followed by maximum number of iterations for iterative\n % method {100}\n % 't0' followed by initial guess of t for iterative method {relative\n % approximate arc lengths}\n % 'AlreadyGenerated' followed by whether the automatically generated helper\n % functions cubic_vertex_removal_polyfun and cubic_vertex_removal_g\n % have already been generated. On some machines checking `exist()` can\n % be really slow. So, you could call\n % `cubic_vertex_removal(\u2026,'AlreadyGenerated',false)` onces to\n % generate the files and the call\n % `cubic_vertex_removal(\u2026,'AlreadyGenerated',true) for subsequent\n % calls {false}.\n % Outputs:\n % C 4 by dim list of output coordinates. By default:\n % C(1,:) = C1(1,:),\n % C(4,:) = C2(4,:), (C\u2080 continuity)\n % and\n % C(2,:) - C(1,:) = s1*(C1(2,:) - C1(1,:)) with s1>=0\n % C(4,:) - C(3,:) = s2*(C2(4,:) - C2(3,:)) with s2>=0 (G\u2081 continutity)\n % t scalar value between [0,1] defining the piecewise-linear\n % parameterization mapping between the inputs and output. C1 is mapped to\n % [0,t] and C2 is mapped to [t1,1].\n % err Integrated squared distance between the output and input curves (see\n % cubic_cubic_integrated_distance).\n %\n % Example:\n % C = [0 0;1 1;2 -1;3 0];\n % tgt = 0.1;\n % [C1,C2] = cubic_split(C,tgt);\n % [C,t,err] = cubic_vertex_removal(C1,C2,'Method','perfect');\n % clf;\n % hold on;\n % plot_cubic(C1,[],[],'Color',orange);\n % plot_cubic(C2,[],[],'Color',orange);\n % plot_cubic(C,[],[],'Color',blue);\n % hold off;\n % axis equal;\n % set(gca,'YDir','reverse')\n % title(sprintf('err: %g',err),'FontSize',30);\n % \n\n method = 'perfect';\n max_iter = 100;\n t0 = [];\n promise_already_built = false;\n E_tol = 1e-15;\n grad_tol = 1e-8;\n\n % Map of parameter names to variable names\n params_to_variables = containers.Map( ...\n {'Method','MaxIter','t0','AlreadyGenerated','Tol','GradientTol',}, ...\n {'method','max_iter','t0','promise_already_built','E_tol','grad_tol'});\n v = 1;\n while v <= numel(varargin)\n param_name = varargin{v};\n if isKey(params_to_variables,param_name)\n assert(v+1<=numel(varargin));\n v = v+1;\n % Trick: use feval on anonymous function to use assignin to this workspace\n feval(@()assignin('caller',params_to_variables(param_name),varargin{v}));\n else\n error('Unsupported parameter: %s',varargin{v});\n end\n v=v+1;\n end\n\n if strcmp(method,'cubic-polish')\n [C,t,err] = cubic_vertex_removal(C1,C2,varargin{:},'Method','cubic');\n % Slip in 'MaxIter',1 before user parameters so it gets over-written if\n % provided. \n [C,t,err] = cubic_vertex_removal(C1,C2,'MaxIter',1,varargin{:},'t0',t,'Method','iterative');\n return;\n end\n\n\n switch method\n case {'perfect','cubic'}\n % _If_ t is perfect, then C is a simple function of t.\n C_from_t = @(C1,C2,t) ...\n [C1(1,:); ...\n (1./t)*(C1(2,:)-C1(1,:)) + C1(1,:); ...\n (1./(1-t))*(C2(end-1,:)-C2(end,:)) + C2(end,:); ...\n C2(end,:)];\n switch method\n case 'perfect'\n % Build a root finder for the 1D problem\n if ~promise_already_built && ~exist('cubic_vertex_removal_polyfun','file');\n warning('assuming L2 not l2 error');\n dim = 1;\n % Matlab is (sometimes?) confused that this is a static workspace and\n % refuses to let syms create variables.\n %syms('iC1',[4 dim],'real');\n %syms('iC2',[4 dim],'real');\n %% complains if I mark st as 'real'\n %syms('st',[1 1]);\n iC1 = [\n sym('iC11','real')\n sym('iC12','real')\n sym('iC13','real')\n sym('iC14','real')];\n iC2 = [\n sym('iC21','real')\n sym('iC22','real')\n sym('iC23','real')\n sym('iC24','real')];\n st = sym('st');\n\n sC = C_from_t(iC1,iC2,st);\n [oC1,oC2] = cubic_split(sC,st);\n % L2 style.\n sg = sum( [oC1-iC1;oC2-iC2].^2, 'all');\n sres = solve(diff(sg,st) == 0,st);\n %sdgdt = simplify(diff(sg,st)); \n %vroots = @(C1,C2) double(vpasolve(subs(subs(sdgdt,iC1,C1),iC2,C2)==0,st,[0 1]));\n sres_children = children(sres(1));\n % Should cache these two:\n %polyfun = matlabFunction(flip(coeffs(sres_children(1),sres_children(2))),'Vars',{iC1,iC2});\n % Matlab2023a seems to use slightly different cell arrays for sres_children. \n polyfun = matlabFunction( ...\n flip(coeffs(sres_children{1},sres_children{2})), ...\n 'Vars',{iC1,iC2}, ...\n 'File','cubic_vertex_removal_polyfun');\n g = matlabFunction(sg,'Vars',{iC1,iC2,st},'File','cubic_vertex_removal_g');\n else\n polyfun = @cubic_vertex_removal_polyfun;\n g = @cubic_vertex_removal_g;\n end\n keepreal = @(C) C(imag(C)==0 & real(C)>=0 & real(C)<=1);\n % Using numerical roots is faster than vroots\n nroots = @(K1,K2) keepreal(roots(polyfun(K1,K2)));\n keepmin = @(ts,Es) ts(find(Es==min(Es),1));\n % We'll determine t based on the 1D g function. But we'll compute the\n % returned energy below using the full dim-D problem.\n keepmin = @(K1,K2,ts) keepmin(ts,arrayfun(@(t) g(K1,K2,t),ts));\n find_t = @(K1,K2) keepmin(K1,K2,nroots(K1,K2));\n % Decide which coordinate to use (pick a non-degenerate one).\n % Based on max-extent.\n [~,i] = max(max([C1(1,:);C2(end,:)])-min([C1(1,:);C2(end,:)]));\n t = find_t(C1(:,i),C2(:,i));\n assert(~isempty(t));\n case 'cubic'\n D1 = -6.*C1(1,:) + 18.*C1(2,:) - 18.*C1(3,:) + 6.*C1(4,:);\n D2 = -6.*C2(1,:) + 18.*C2(2,:) - 18.*C2(3,:) + 6.*C2(4,:);\n D2_sqr_len = sum(D2.*D2,2);\n D1_sqr_len = sum(D1.*D1,2);\n D2_D1 = sum(D2.*D1,2);\n r = D2_D1/D1_sqr_len;\n t = (1 + (r.^(1/3))).^-1;\n end\n C = C_from_t(C1,C2,t);\n case 'iterative'\n % use arc-length to guess t\u2081\n if isempty(t0)\n tol = 1e-5;\n ts = matrixnormalize(cumsum([0;spline_arc_lengths([C1;C2],[1 2 3 4;5 6 7 8],tol)]));\n t0 = ts(2);\n end\n t1 = t0;\n % Build null space matrices. so that C(:) = S*V + B(:) satisfies C\u2080 and G\u2081\n % constraints for any V\n B = [C1(1,:);C1(1,:);C2(4,:);C2(4,:)];\n B1 = [0 0;(C1(2,:) - C1(1,:));0 0;0 0];\n B2 = [0 0;0 0;(C2(3,:) - C2(4,:));0 0];\n S = [B1(:) B2(:)];\n\n f = @(t1) objective_t1(C1,C2,t1,B,S);\n [E,C] = f(t1);\n for iter = 1:max_iter\n %dfdt1 = (f(t1+1e-5)-f(t1-1e-5))/(2*1e-5);\n % Complex step is bit faster and more accurate/stable. For 1D input, I\n % believe this should be as good as autodiff and probably as good as we\n % can get without a lot of hand derivativation/compiling code.\n dfdt1 = imag(f(complex(t1,1e-100)))/1e-100;\n \n if norm(dfdt1,inf) < grad_tol\n break;\n end\n dt1 = 0.5*sign(-dfdt1);\n [alpha,t1] = backtracking_line_search(f,t1,dfdt1,dt1,0.3,0.5);\n if alpha == 0\n %warning('line search failed');\n break;\n end\n [E,C] = f(t1);\n if E < E_tol\n break;\n end\n end\n\n t = t1;\n otherwise\n error(['unknown method :' method]);\n end\n\n\n if nargout>2\n % L2 not l2\n [E1] = cubic_cubic_integrated_distance( ...\n 0,t, ...\n 1/t,0, ...\n C1, ...\n 1,0, ...\n C);\n [E2] = cubic_cubic_integrated_distance( ...\n t,1, ...\n 1/(1-t),-t/(1-t), ...\n C2, ...\n 1,0, ...\n C);\n err = E1+E2;\n end\n\n\n % Helper functions for iterative method\n function [E,C] = objective_t1(C1,C2,t1,B,S)\n if isfloat(t1) && (t1>1 || t1<0)\n E = inf;\n return;\n end\n C = nan(4,2);\n [~,H,F,c] = objective(C1,C2,C,t1);\n % Enforce constraints via subspace\n % C = [\n % C1(1,:)\n % C1(1,:) + v1 * (C1(2,:) - C1(1,:))\n % C2(4,:) + v2 * (C2(3,:) - C2(4,:))\n % C2(4,:)\n % ];\n HH = repdiag(H,2);\n V = ((S.'*HH*S)\\(-S.'*F(:)-S.'*HH*B(:)));\n V = max(V,0);\n C = reshape( B(:) + S*V , size(C));\n [E] = objective(C1,C2,C,t1);\n end\n function [E,H,F,c] = objective(C1,C2,C,t1)\n if isfloat(t1) && (t1>1 || t1<0)\n E = inf;\n return;\n end\n % WARNING\n w1 = 1;\n w2 = 1;\n %w1 = t1; \n %w2 = 1-t1;\n if nargout == 4\n % Given t1 update C\n [H1,F1,c1,E1] = cubic_cubic_integrated_distance( ...\n 0,t1, ...\n 1/t1,0, ...\n C1, ...\n 1,0, ...\n C);\n [H2,F2,c2,E2] = cubic_cubic_integrated_distance( ...\n t1,1, ...\n 1/(1-t1),-t1/(1-t1), ...\n C2, ...\n 1,0, ...\n C);\n % Equal weighting (\"L2\")\n H = w1*H1 + w2*H2;\n F = w1*F1 + w2*F2;\n c = w1*c1 + w2*c2;\n else \n % Given t1 update C\n [E1] = cubic_cubic_integrated_distance( ...\n 0,t1, ...\n 1/t1,0, ...\n C1, ...\n 1,0, ...\n C);\n [E2] = cubic_cubic_integrated_distance( ...\n t1,1, ...\n 1/(1-t1),-t1/(1-t1), ...\n C2, ...\n 1,0, ...\n C);\n end\n E = w1*E1 + w2*E2;\n end\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/cubic_vertex_removal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.6998587837452045}} {"text": "function pass = test_sign(pref)\n\nif ( nargin == 0 )\n pref = chebfunpref();\nend\n\n% Initialise random vector:\nseedRNG(6178);\nx = 2 * rand(100, 1) - 1;\nhvsde = @(x) .5*(sign(x) + 1);\n\n%% Simple tests\npref.splitting = 0;\nf = chebfun('x.^2', pref); \ntol = eps*get(f, 'hscale');\nf1 = sign(f);\npass(1,1) = all(feval(f1, x) == 1);\n\n% Test if pointValues are dealt with correctly: \nf = chebfun(@(x) cos(pi*x) + 2, sort(x)', pref);\nf.pointValues = -pi*ones(length(f.ends), 1);\nf1 = sign(f);\npass(1,2) = all(f1.pointValues == -1);\n\n% Test also on longer intervals:\nf = chebfun(@(x) x, [-1, 100], pref);\nf1 = sign(f);\nh = chebfun({-1, 1}, [-1, 0, 100]);\npass(1,3) = normest(h - f1) < tol;\n\n% Test functions with breakpoints:\nf = chebfun(@(x) x, [-1, 1e-10, 1], pref);\nf1 = sign(f);\nh = restrict(h,[-1, 1]);\npass(1,4) = normest(f1 - h) < tol;\n\n% Real, imaginary and complex CHEBFUN objects:\nf = chebfun({-1, 1, -1, 1, -1, 1}, -3:3);\n\n%% Real CHEBFUN\ngHandle1 = @(x) sin(pi*x);\ng = chebfun(@(x) gHandle1(x), -3:3, pref);\ng1 = sign(g);\npass(2,1) = length(g1.funs) == 6;\npass(2,2) = normest(f - g1) < tol;\npref.splitting = 1;\nh1 = chebfun(@(x) sign(gHandle1(x)), -3:3, pref);\npass(2,3) = length(h1.funs) == 6;\npass(2,4) = normest(f - h1) < 100*tol;\n\n%% Array-valued CHEBFUN\nf1 = chebfun(@(x) feval(f, [x, x]) , -3:3, pref);\ngHandle2 = @(x) cos(pi*(x-.5));\ng = chebfun(@(x) [gHandle1(x), gHandle2(x)] , -3:3, pref);\ng4 = sign(g);\npass(3,1) = length(g4.funs) == 6;\npass(3,2) = normest(f1 - g4) < 1e1*tol;\n\nh4 = chebfun(@(x) sign([gHandle1(x), gHandle2(x)]), -3:3, pref);\npass(3,3) = length(h4.funs) == 6;\npass(3,4) = normest(f1 - h4) < tol;\n\n%% A more complicated function:\nf = chebfun(@(x) sin(1i*x).*(1i*x + exp(5i*x)));\ng = chebfun(@(x) sign(sin(1i*x).*(1i*x + exp(5i*x))),[-1 0 1], ...\n 'extrapolate', 'on');\nh = sign(f);\npass(4,:) = normest(g - h) < 1e4*eps*length(h);\n\n\n%% Test sign() for a complex-valued CHEBFUN.\nf = chebfun(@(x) exp(2*pi*1i*x)./(1 + (x - 0.1).^2), [-1 1]);\nh = sign(f);\nh_exact = @(x) exp(2*pi*1i*x);\npass(5,:) = norm(feval(h, x) - h_exact(x), inf) < 1e2*vscale(h)*eps;\n\n%% Test on singular function: a real case\n\n% Set a domain:\ndom = [-2 7];\n\n% Generate a few random points to use as test values:\nx = diff(dom) * rand(100, 1) + dom(1);\n\npow = -0.5;\nop = @(x) (dom(2)-x).^pow.*( sin(10*x).^2 );\nf = chebfun(op, dom, 'exps', [0 pow], 'splitting', 'on');\ns = sign(f);\npass(6,:) = ( norm(feval(s-1, x), inf) < eps );\n\n%% Test on singular function: a complex case\n\n% Set a domain:\ndom = [-1 1];\n\n% Generate a few random points to use as test values:\nx = diff(dom) * rand(100, 1) + dom(1);\n\npow = -0.5;\nop = @(x) (dom(2)-x).^pow.*exp(2*pi*1i*x);\nf = chebfun(op, dom, 'exps', [0 pow], 'splitting', 'on');\ns = sign(f);\ns_exact = @(x) exp(2*pi*1i*x);\nvals_s = feval(s, x);\nvals_exact = feval(s_exact, x);\nerr = vals_s - vals_exact;\npass(7,:) = ( norm(err, inf) < 1e1*eps*get(s, 'vscale') );\n\n%% Functions on [-inf inf]:\n\n% Set the domain:\ndom = [-Inf Inf];\ndomCheck = [-1e2 1e2];\n\n% Generate a few random points to use as test values:\nx = diff(domCheck) * rand(100, 1) + domCheck(1);\n\nop = @(x) (1-exp(-x.^2))./x;\nf = chebfun(op, dom);\ns = sign(f);\nsVals = feval(s, x);\nop = @(x) 2*hvsde(x) - 1;\nsExact = op(x);\nerr = sVals - sExact;\npass(8,:) = all( ~norm(err, inf) );\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/tests/chebfun/test_sign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427857178614, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.6998587828613646}} {"text": "clc, clear\nx1=[6.683, 6.681, 6.676, 6.678, 6.679, 6.672];\nx2=[6.661, 6.661, 6.667, 6.667, 6.664];\n[h,p,ci,st]=ttest2(x1,x2,'Alpha',0.1)\n", "meta": {"author": "Eurus-Holmes", "repo": "Mathematical_Modeling", "sha": "cb9dd53af84ffbd455ec62ab89886351e0ec98d9", "save_path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling", "path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling/Mathematical_Modeling-cb9dd53af84ffbd455ec62ab89886351e0ec98d9/Mathematical_Modeling_Algorithms_and_Applications_Second_Edition_Procedures_and_Data/07\u7b2c7\u7ae0/ex7_4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6998587760938377}} {"text": "function [ pivot, lu, info ] = r8mat_to_r8plu ( n, a )\n\n%*****************************************************************************80\n%\n%% R8MAT_TO_R8PLU factors a general matrix.\n%\n% Discussion:\n%\n% This routine is a simplified version of the LINPACK routine DGEFA.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979,\n% ISBN13: 978-0-898711-72-1.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be positive.\n%\n% Input, real A(N,N), the matrix to be factored.\n%\n% Output, integer PIVOT(N), a vector of pivot indices.\n%\n% Output, real LU(N,N), an upper triangular matrix U and\n% the multipliers L which were used to obtain it. The factorization\n% can be written A = L * U, where L is a product of permutation and\n% unit lower triangular matrices and U is upper triangular.\n%\n% Output, integer INFO, singularity flag.\n% 0, no singularity detected.\n% nonzero, the factorization failed on the INFO-th step.\n%\n lu(1:n,1:n) = a(1:n,1:n);\n\n info = 0;\n\n for k = 1 : n-1\n%\n% Find L, the index of the pivot row.\n%\n l = k;\n for i = k+1 : n\n if ( abs ( lu(l,k) ) < abs ( lu(i,k) ) )\n l = i;\n end\n end\n\n pivot(k) = l;\n%\n% If the pivot index is zero, the algorithm has failed.\n%\n if ( lu(l,k) == 0.0 )\n info = k;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_TO_R8PLU - Fatal error!\\n' );\n fprintf ( 1, ' Zero pivot on step %d\\n', info );\n return\n end\n%\n% Interchange rows L and K if necessary.\n%\n if ( l ~= k )\n temp = lu(l,k);\n lu(l,k) = lu(k,k);\n lu(k,k) = temp;\n end\n%\n% Normalize the values that lie below the pivot entry A(K,K).\n%\n lu(k+1:n,k) = -lu(k+1:n,k) / lu(k,k);\n%\n% Row elimination with column indexing.\n%\n for j = k+1 : n\n\n if ( l ~= k )\n temp = lu(l,j);\n lu(l,j) = lu(k,j);\n lu(k,j) = temp;\n end\n\n lu(k+1:n,j) = lu(k+1:n,j) + lu(k+1:n,k) * lu(k,j);\n\n end\n\n end\n\n pivot(n) = n;\n\n if ( lu(n,n) == 0.0 )\n info = n;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_TO_R8PLU - Fatal error!\\n' );\n fprintf ( 1, ' Zero pivot on step %d\\n', info );\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/r8lib/r8mat_to_r8plu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.6998176710208494}} {"text": "% Haar transform on Healpix\n% Y = HealpixHaarTransform(X)\n\nfunction Y = HealpixHaarTransform(X)\n\n% nest depth\nn = length(X);\nm = log2(n / 12) / 2; % = log4(n / 12)\n\n% Haar wavelet basis\nA = [ 1 1 1 1;\n 1 1 -1 -1;\n 1 -1 1 -1;\n 1 -1 -1 1 ] / sqrt(4);\n%A = [ 1 1 1 1;\n% 1 1 -1 -1;\n% sqrt(2) -sqrt(2) 0 0;\n% 0 0 sqrt(2) -sqrt(2) ] / sqrt(4);\n\nY = HealpixNestedLinearTrans(X, A, m);\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/extern/HealpixLib/HealpixHaarTransform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541659378681, "lm_q2_score": 0.7431679972357831, "lm_q1q2_score": 0.6998072405887772}} {"text": "I = imread('bh.png'); \n%I = imread('C:\\Users\\Mostwanted\\Desktop\\Wuhan_China.jpg'); \nsubplot(1,2,1); \nimshow(I); \n\n\nI=double(I); \nf=I(:,:,1); \nff=I(:,:,2); \nfff=I(:,:,3); \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \nk1=4; \nk2=5; \nr=161; \nalf=1458; \nnn=floor((r+1)/2); \nfor i=1:r \n for j=1:r \n b(i,j) =exp(-((i-nn)^2+(j-nn)^2)/(k1*alf))/(k2*pi*alf*10000); % Gaussian 1 \n end \nend \n\nk1=8; \nk2=8; \nr=161; \nalf=1458; \nnn=floor((r+1)/2); \nfor i=1:r \n for j=1:r \n bb(i,j) =exp(-((i-nn)^2+(j-nn)^2)/(k1*alf))/(k2*pi*alf*10000); % Gaussian 2 \n end \nend \n\nk1=0.5; \nk2=0.5; \nr=161; \nalf=1458; \nnn=floor((r+1)/2); \nfor i=1:r \n for j=1:r \n bbb(i,j) =exp(-((i-nn)^2+(j-nn)^2)/(k1*alf))/(k2*pi*alf*10000); % Gaussian 2 3 \n end \n end \n%%%%%%%%%%% R component of treatment %%%%%%%%%%%%% \nImg = double(f); \n[m,n]=size(f); \n\naa=125; \n\nfor i=1:m \n for j=1:n \n C(i,j)=log(1+aa*(Img(i,j)/I(i,j))); \n end \nend \n\nK=imfilter(Img,b); \nKK=imfilter(Img,bb); \nKKK=imfilter(Img,bbb); \n\nfor i=1:m \n for j=1:n \n G(i,j)=1/3*(log(Img(i,j)+1)-log(K(i,j)+1)); \n G(i,j)=1/3*(log(Img(i,j)+1)-log(KK(i,j)+1))+G(i,j); \n G(i,j)=C(i,j)*(1/3*(log(Img(i,j)+1)-log(KKK(i,j)+1))+G(i,j)); \n end \nend \n\nmi=min(min(G)); \nma=max(max(G)); \n L=(G-mi)*255/(ma-mi); \n%%%%%%%%%%%%%% G Processing Components %%%%%%%%%%%%%%%%%%%%%%%%%%%%% \nImg = double(ff); \n[m,n]=size(ff); \n\naa=125; \nfor i=1:m \n for j=1:n \n CC(i,j)=log(1+aa*(Img(i,j)/I(i,j))); \n end \nend \n\nK=imfilter(Img,b); \nKK=imfilter(Img,bb); \nKKK=imfilter(Img,bbb); \nfor i=1:m \n for j=1:n \n G(i,j)=1/3*(log(Img(i,j)+1)-log(K(i,j)+1)); \n G(i,j)=1/3*(log(Img(i,j)+1)-log(KK(i,j)+1))+G(i,j); \n G(i,j)=CC(i,j)*(1/3*(log(Img(i,j)+1)-log(KKK(i,j)+1))+G(i,j)); \n end \nend \n\nmi=min(min(G)); \nma=max(max(G)); \n LL=(G-mi)*255/(ma-mi); \n%%%%%%%%%%%%% With the B component of the Department %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \nImg = double(fff); \n[m,n]=size(fff); \n\naa=125; \nfor i=1:m \n for j=1:n \n CCC(i,j)=log(1+aa*(Img(i,j)/I(i,j))); \n end \nend \n\nK=imfilter(Img,b); \nKK=imfilter(Img,bb); \nKKK=imfilter(Img,bbb); \n\nfor i=1:m \n for j=1:n \n G(i,j)=1/3*(log(Img(i,j)+1)-log(K(i,j)+1)); \n G(i,j)=1/3*(log(Img(i,j)+1)-log(KK(i,j)+1))+G(i,j); \n G(i,j)=CCC(i,j)*(1/3*(log(Img(i,j)+1)-log(KKK(i,j)+1))+G(i,j)); \n end \nend \n\nmi=min(min(G)); \nma=max(max(G)); \n\n LLL=(G-mi)*255/(ma-mi); \n%%%%%%%%%%%% Department of Integrated color image of science %%%%%%%%%%%%%%% \nmsrcr=cat(3,L,LL,LLL); \nsubplot(1,2,2); \nimshow(uint8(msrcr)); \n%imwrite(uint8(msrcr),'C:\\Users\\Mostwanted\\Desktop\\Wuhan_China_outcr1.jpg'); \n%imwrite(uint8(msrcr),'C:\\Users\\Mostwanted\\Desktop\\Washington_DC_outcr1.jpg'); ", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u589e\u5f3a\u7b97\u6cd5/image-contrast-enhancement-master/scr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541593883189, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6998072357213617}} {"text": "function [Ri, RiFull] = syntheticCamera(F, type)\n\nif nargin < 2\n type = 'continuous';\nend\n\nRi = cell(F, 1);\nRiFull = cell(F, 1);\n\nswitch type \n case 'random'\n for i = 1:F\n R = orth(randn(3));\n Ri{i} = R(2:3, :);\n RiFull{i} = R;\n end\n \n case 'continuous'\n Ux = @(u) [ 0, -u(3), u(2); ... \n u(3), 0, -u(1); ...\n -u(2), u(1), 0];\n theta = randn(1); % create an angle randomly\n u = randn(3, 1); \n u = u/norm(u); % create a unit axis randomly\n for i = 1:F\n theta = theta + 1;\n % create a rotation matrix\n orthR = cos(theta)*eye(3) + sin(theta)*Ux(u) + (1-cos(theta))*kron(u,u');\n Ri{i} = orthR(2:3, :);\n RiFull{i} = orthR(1:3, :);\n end\n \n case 'vertical'\n Ux = @(u) [ 0, -u(3), u(2); ... \n u(3), 0, -u(1); ...\n -u(2), u(1), 0];\n %theta = randn(1);\n theta = 360/F;\n u = [0.2;0;1]; % z-axis rotation \n for i = 1:F\n % in degrees\n orthR = cosd(theta*i)*eye(3) + sind(theta*i)*Ux(u) + (1-cosd(theta*i))*kron(u,u');\n \n Ri{i} = orthR(2:3, :);\n RiFull{i} = orthR(1:3, :);\n end\n \n case 'real'\n Ux = @(u) [ 0, -u(3), u(2); ...\n u(3), 0, -u(1); ...\n -u(2), u(1), 0];\n %theta = randn(1);\n theta = 2;\n totalRotDeg = 120;\n u = [0;0;1]; % z-axis rotation\n for i = 1:F\n \n orthR = cosd(theta)*eye(3) + sind(theta)*Ux(u) + (1-cosd(theta))*kron(u,u');\n \n if i >= round(F/2) && i <= round((3*F)/4) \n camActNum = round(F/2) - round((3*F)/4);\n degrees = totalRotDeg / camActNum;\n \n % in degrees\n theta = theta + degrees;\n orthR = cosd(theta)*eye(3) + sind(theta)*Ux(u) + (1-cosd(theta))*kron(u,u');\n \n Ri{i} = orthR(2:3, :);\n RiFull{i} = orthR(1:3, :);\n else\n Ri{i} = orthR(2:3, :);\n RiFull{i} = orthR(1:3, :);\n end\n end\n \n case '360'\n Ux = @(u) [ 0, -u(3), u(2); ... \n u(3), 0, -u(1); ...\n -u(2), u(1), 0];\n %theta = randn(1);\n theta = 360/F;\n u = [0;0;1]; % z-axis rotation \n for i = 1:F \n % in degrees\n orthR = cosd(theta*i)*eye(3) + sind(theta*i)*Ux(u) + (1-cosd(theta*i))*kron(u,u'); \n Ri{i} = orthR(2:3, :);\n RiFull{i} = orthR(1:3, :);\n end\n \n otherwise\n error('%s is a wrong camera type!', type);\nend\n", "meta": {"author": "jhonykaesemodel", "repo": "image2mesh", "sha": "839fdadf64187a3d2d3e4a84a5fa92226fccd668", "save_path": "github-repos/MATLAB/jhonykaesemodel-image2mesh", "path": "github-repos/MATLAB/jhonykaesemodel-image2mesh/image2mesh-839fdadf64187a3d2d3e4a84a5fa92226fccd668/matlab/utils/synthetic_camera.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6997914996739114}} {"text": "function degrees = degrees(radians)\n\n% DEGREES (RADIANS)\n%\n% Conversion function from Radians to Degrees.\n% Richard Medlock 12-03-2002\n%\n% Last Updated: 18-09-2009\n% - Calculation simplified to make it more efficient\n% based on a suggestion by Joel Parker.\n\n% Original calculation\n% radians = radians/((2*pi)/360);\n\n\n\ndegrees = radians/(pi/180);", "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/3263-degrees-and-radians/degrees.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6997914969741321}} {"text": "% Rank aware thresholding needs much more measurements than MUSIC to work\n% properly.\n\nclose all;\nclear all;\nclc;\nrng('default');\npng_export = true;\npdf_export = false;\n% Create the directory for storing images\n[status_code,message,message_id] = mkdir('bin');\n\nmf = spx.graphics.Figures();\n\n% Signal space \nN = 256;\n% Sparsity level\nK = 6;\n% Number of measurements\nM = 32;\n% Number of signals\nS = 4;\n% Construct the signal generator.\ngen = spx.data.synthetic.SparseSignalGenerator(N, K, S);\n% Generate bi-uniform signals\nX = gen.biUniform(1, 2);\n% Sensing matrix\nPhi = spx.dict.simple.gaussian_dict(M, N);\n% Measurement vectors\nY = Phi.apply(X);\n% Rank Aware Thresholding solver instance\nsolver = spx.pursuit.joint.RankAwareThresholding(Phi, K);\n% Solve the sparse recovery problem\nresult = solver.solve(Y);\n% Solution vector\nZ = result.Z;\n% Comparison\ncs = spx.commons.SparseSignalsComparison(X, Z, K);\ncs.summarize();\n\nfor s=1:S\n mf.new_figure(sprintf('MMV signal: %d', s));\n subplot(411);\n stem(X(:, s), '.');\n title('Sparse vector');\n subplot(412);\n stem(Z(:, s), '.');\n title('Recovered sparse vector');\n subplot(413);\n stem(abs(X(:, s) - Z(:, s)), '.');\n title('Recovery error');\n subplot(414);\n stem(Y(:, s), '.');\n title('Measurement vector');\nend\n\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/pursuit/joint_recovery/rank_aware_thresholding/ex_rank_aware_thresholding.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6997914959160586}} {"text": "function pass = test_laplacian( pref ) \n\n% Grab some preferences\nif ( nargin == 0 )\n pref = chebfunpref();\nend\ntol = 1e7*pref.techPrefs.chebfuneps;\n\n% Test with different parity of m,p\n% Example 1:\nf = ballfun(@(x,y,z)x.^2+y.^2+z.^2);\nV = ballfunv(f,2*f,-f);\ng = laplacian(V);\nexact = ballfunv(ballfun(@(x,y,z)6),ballfun(@(x,y,z)12),ballfun(@(x,y,z)-6));\npass(1) = norm( g - exact ) < tol;\n\n% Example 2:\nf1 = ballfun(@(x,y,z)cos(x.*y));\nf2 = ballfun(@(x,y,z)sin(y.*z));\nf3 = ballfun(@(x,y,z)z.^3);\nv = ballfunv(f1,f2,f3);\ng = laplacian(v);\nexact = grad(div(v))-curl(curl(v));\npass(2) = norm( g - exact ) < tol;\n\nif (nargout > 0)\n pass = all(pass(:));\nend\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/ballfunv/test_laplacian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6997914911001318}} {"text": "function [Z, Wsep, Wmix, m, U, S, V] = zca(X, portion)\n\nif nargin < 2\n portion = 1;\nend\n\nrndidx = randperm(size(X, 1));\nX_orig = X;\nX = X(rndidx(1:round(size(X,1) * portion)), :);\n\nm = mean(X, 1);\nXc = bsxfun(@minus, X, m);\n\nsigma = Xc' * Xc / size(Xc, 1);\n\n[U, S, V] = svd(sigma, 0);\n\nWsep = V / sqrt(S+1e-12);\nWmix = V';\nZ = bsxfun(@minus, X_orig, m) * Wsep * Wmix;\n\n\n\n\n\n", "meta": {"author": "kyunghyuncho", "repo": "deepmat", "sha": "6fd133406b5d78e1b87e2f736e27cfb2024807af", "save_path": "github-repos/MATLAB/kyunghyuncho-deepmat", "path": "github-repos/MATLAB/kyunghyuncho-deepmat/deepmat-6fd133406b5d78e1b87e2f736e27cfb2024807af/zca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.7690802264851918, "lm_q1q2_score": 0.6997914825263518}} {"text": "function gdif = p00_gdif ( problem, n, x )\n\n%*****************************************************************************80\n%\n%% P00_GDIF approximates the gradient via finite differences.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 October 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer PROBLEM, the problem number.\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the point where the gradient\n% is to be approximated.\n%\n% Output, real GDIF(N), the approximated gradient vector.\n%\n tol = eps^0.33;\n\n for i = 1 : n\n\n if ( 0.0 <= x(i) )\n dx = eps * ( x(i) + 1.0 );\n else\n dx = eps * ( x(i) - 1.0 );\n end\n\n xi = x(i);\n x(i) = xi + dx;\n fplus = p00_f ( problem, n, x );\n\n x(i) = xi - dx;\n fminus = p00_f ( problem, n, x );\n\n gdif(i) = ( fplus - fminus ) / ( 2.0 * dx );\n\n x(i) = xi;\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/test_opt/p00_gdif.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.6997709806788337}} {"text": "function variance = cardioid_variance ( x, a, b )\n\n%*****************************************************************************80\n%\n%% CARDIOID_VARIANCE returns the variance of the Cardioid PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 July 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, the parameters of the PDF.\n% 0.0 <= B <= 0.5.\n%\n% Output, real VARIANCE, the variance of the PDF.\n%\n variance = a;\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_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.6997607012022571}} {"text": "function img = discreteSphereEighth(varargin)\n%DISCRETESPHEREEIGHTH Discretize a 3D sphere eighth\n%\n% IMG = discreteSphereEighth(LX, LY, LZ, SPHEIGHTH)\n% Creates a 3D image of a eighth of a sphere.\n%\n% Example\n% img = discreteSphereEighth(1:100, 1:100, 1:100, [50 50 50 30 10 60 45]);\n% img = discreteSphereEighth([1 1 100;1 1 100;1 1 100], [50 50 50], 30, 10);\n% img = discreteSphereEighth([1 1 100;1 1 100;1 1 100], [50 50 50 30 10]);\n%\n% See Also\n% imShapes, discreteBall, discreteCube\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2015-03-31\n% Copyright 2015 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).\n\n% HISTORY\n\n% compute coordinate of image voxels\n[lx, ly, lz, varargin] = parseGridArgs3d(varargin{:});\n[x, y, z] = meshgrid(lx, ly, lz);\n\n% default parameters\ncenter = [lx(ceil(end/2)) ly(ceil(end/2)) lz(ceil(end/2))];\nside = center;\ntheta = 0; phi = 0; psi=0;\n\n% process input parameters\nif length(varargin)==1\n var = varargin{1};\n center = var(:,1:3);\n if size(var, 2)>3\n side = var(:,4);\n end\n if size(var, 2)>4\n theta = var(:,5);\n end\n if size(var, 2)>5\n phi = var(:,6);\n end\n if size(var, 2)>6\n psi = var(:,7);\n end\n \nelseif ~isempty(varargin)\n center = varargin{1};\n if length(varargin)>1\n side = varargin{2};\n end\n if length(varargin)>2\n theta = varargin{3};\n end\n if length(varargin)>3\n phi = varargin{4};\n end\n if length(varargin)>4\n psi = varargin{5};\n end\nend\n\nif length(side) == 1\n side = [side side side];\nend\n\n% compute coordinate of image voxels in cube reference system\ntrans = composeTransforms3d(...\n createTranslation3d(-center),...\n createRotationOz(-deg2rad(phi)),...\n createRotationOy(-deg2rad(theta)), ...\n createRotationOz(-deg2rad(psi)),...\n createScaling3d(1 ./ side));\n[x, y, z] = transformPoint3d(x, y, z, trans);\n\n% create image: simple threshold over 3 dimensions, and over radius\nimg = sqrt(x.^2 + y.^2 + z.^2) <= 1 & x >= 0 & x <= 1 & y >=0 & y <= 1 & z >= 0 & z <= 1;\n\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imShapes/discreteSphereEighth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.6997220629976387}} {"text": "function d = spline_pchip_set ( n, x, f )\n\n%*****************************************************************************80\n%\n%% SPLINE_PCHIP_SET sets derivatives for a piecewise cubic Hermite interpolant.\n%\n% Discussion:\n%\n% This routine computes what would normally be called a Hermite\n% interpolant. However, the user is only required to supply function\n% values, not derivative values as well. This routine computes\n% \"suitable\" derivative values, so that the resulting Hermite interpolant\n% has desirable shape and monotonicity properties.\n%\n% The interpolant will have an extremum at each point where\n% monotonicity switches direction.\n%\n% The resulting piecewise cubic Hermite function may be evaluated\n% by SPLINE_PCHIP_VAL.\n%\n% This routine was originally called \"PCHIM\".\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 August 2005\n%\n% Author:\n%\n% Original FORTRAN77 version by Fred Fritsch.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Fred Fritsch, Ralph Carlson,\n% Monotone Piecewise Cubic Interpolation,\n% SIAM Journal on Numerical Analysis,\n% Volume 17, Number 2, April 1980, pages 238-246.\n%\n% Fred Fritsch, J Butland,\n% A Method for Constructing Local Monotone Piecewise Cubic Interpolants,\n% LLNL Preprint UCRL-87559, April 1982.\n%\n% Parameters:\n%\n% Input, integer N, the number of data points. N must be at least 2.\n%\n% Input, real X(N), the strictly increasing independent\n% variable values.\n%\n% Input, real F(N), dependent variable values to be interpolated. This\n% routine is designed for monotonic data, but it will work for any F-array.\n% It will force extrema at points where monotonicity switches direction.\n%\n% Output, real D(N), the derivative values at the\n% data points. If the data are monotonic, these values will determine\n% a monotone cubic Hermite function.\n%\n\n%\n% Check the arguments.\n%\n if ( n < 2 )\n ierr = -1;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPLINE_PCHIP_SET - Fatal error!\\n' );\n fprintf ( 1, ' Number of data points less than 2.\\n' );\n error ( 'SPLINE_PCHIP_SET - Fatal error!' );\n end\n\n for i = 2 : n\n if ( x(i) <= x(i-1) )\n ierr = -3;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPLINE_PCHIP_SET - Fatal error!\\n' );\n fprintf ( 1, ' X array not strictly increasing.\\n' );\n error ( 'SPLINE_PCHIP_SET - Fatal error!' );\n end\n end\n\n ierr = 0;\n nless1 = n - 1;\n h1 = x(2) - x(1);\n del1 = ( f(2) - f(1) ) / h1;\n dsave = del1;\n%\n% Special case N=2, use linear interpolation.\n%\n if ( n == 2 )\n d(1) = del1;\n d(n) = del1;\n return\n end\n%\n% Normal case, 3 <= N.\n%\n h2 = x(3) - x(2);\n del2 = ( f(3) - f(2) ) / h2;\n%\n% Set D(1) via non-centered three point formula, adjusted to be\n% shape preserving.\n%\n hsum = h1 + h2;\n w1 = ( h1 + hsum ) / hsum;\n w2 = -h1 / hsum;\n d(1) = w1 * del1 + w2 * del2;\n\n if ( pchst ( d(1), del1 ) <= 0.0 )\n\n d(1) = 0.0\n%\n% Need do this check only if monotonicity switches.\n%\n elseif ( pchst ( del1, del2 ) < 0.0 )\n\n dmax = 3.0 * del1;\n\n if ( abs ( dmax ) < abs ( d(1) ) )\n d(1) = dmax;\n end\n\n end\n%\n% Loop through interior points.\n%\n for i = 2 : nless1\n\n if ( 2 < i )\n h1 = h2;\n h2 = x(i+1) - x(i);\n hsum = h1 + h2;\n del1 = del2;\n del2 = ( f(i+1) - f(i) ) / h2;\n end\n%\n% Set D(I)=0 unless data are strictly monotonic.\n%\n d(i) = 0.0;\n\n temp = pchst ( del1, del2 );\n\n if ( temp < 0.0 )\n\n ierr = ierr + 1;\n dsave = del2;\n%\n% Count number of changes in direction of monotonicity.\n%\n elseif ( temp == 0.0 )\n\n if ( del2 ~= 0.0D+00 )\n if ( pchst ( dsave, del2 ) < 0.0 )\n ierr = ierr + 1;\n end\n dsave = del2;\n end\n%\n% Use Brodlie modification of Butland formula.\n%\n else\n\n hsumt3 = 3.0 * hsum;\n w1 = ( hsum + h1 ) / hsumt3;\n w2 = ( hsum + h2 ) / hsumt3;\n dmax = max ( abs ( del1 ), abs ( del2 ) );\n dmin = min ( abs ( del1 ), abs ( del2 ) );\n drat1 = del1 / dmax;\n drat2 = del2 / dmax;\n d(i) = dmin / ( w1 * drat1 + w2 * drat2 );\n\n end\n\n end\n%\n% Set D(N) via non-centered three point formula, adjusted to be\n% shape preserving.\n%\n w1 = -h2 / hsum;\n w2 = ( h2 + hsum ) / hsum;\n d(n) = w1 * del1 + w2 * del2;\n\n if ( pchst ( d(n), del2 ) <= 0.0 )\n d(n) = 0.0;\n elseif ( pchst ( del1, del2 ) < 0.0 )\n%\n% Need do this check only if monotonicity switches.\n%\n dmax = 3.0 * del2;\n\n if ( abs ( dmax ) < abs ( d(n) ) )\n d(n) = dmax;\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/spline/spline_pchip_set.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.6997220577838644}} {"text": "function n = poisson_fixed_time ( lambda, time )\n\n%*****************************************************************************80\n%\n%% POISSON_FIXED_TIME counts the Poisson events in a fied time.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 September 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real LAMBDA, the average number of events per unit time.\n%\n% Input, real TIME, the amount of time to observe.\n%\n% Output, integer N, the number of Poisson events observed.\n%\n n = 0;\n t = 0.0;\n\n while ( t < time )\n dt = - log ( rand ( 1, 1 ) ) / lambda;\n n = n + 1;\n t = t + dt;\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/poisson_simulation/poisson_fixed_time.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.6997220550835772}} {"text": "function lambda = circulant2_eigenvalues ( n, x )\n\n%*****************************************************************************80\n%\n%% CIRCULANT2_EIGENVALUES returns the eigenvalues of the CIRCULANT2 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of rows and columns of A.\n%\n% Output, complex LAMBDA(N,1), the eigenvalues.\n%\n lambda = zeros ( n, 1 );\n\n x = zeros ( n, 1 );\n for i = 1 : n\n x(i,1) = i;\n end\n\n w(1:n,1) = c8vec_unity ( n );\n\n lambda(1:n,1) = x(n,1);\n for i = n-1 : -1 : 1\n lambda(1:n,1) = lambda(1:n,1) .* w(1:n,1) + x(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/test_mat/circulant2_eigenvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.699722052875788}} {"text": "function triangle_ncc_rule_test05 ( )\n\n%*****************************************************************************80\n%\n%% TEST05 demonstrates REFERENCE_TO_PHYSICAL_T3.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 January 2007\n%\n% Author:\n%\n% John Burkardt\n%\n dim_num = 2;\n node_num = 3;\n\n node_xy = [ ...\n 0.0, 0.0; ...\n 1.0, 0.0; ...\n 0.0, 1.0 ]';\n node_xy2 = [ ...\n 1.0, 2.0; ...\n 1.0, 1.0; ...\n 3.0, 2.0 ]';\n point_show = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST05\\n' );\n fprintf ( 1, ' REFERENCE_TO_PHYSICAL_T3 transforms a rule\\n' );\n fprintf ( 1, ' on the unit (reference) triangle to a rule on\\n' );\n fprintf ( 1, ' an arbitrary (physical) triangle.\\n' );\n\n rule = 3;\n\n order_num = triangle_ncc_order_num ( rule );\n\n [ xy, w ] = triangle_ncc_rule ( rule, order_num );\n%\n% Here is the reference triangle, and its rule.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The reference triangle:\\n', rule );\n fprintf ( 1, '\\n' );\n\n for node = 1 : 3\n fprintf ( 1, ' %8d %14f %14f\\n', node, node_xy(1:2,node) );\n end\n\n area = triangle_area ( node_xy );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Rule %d for reference triangle\\n', rule );\n fprintf ( 1, ' with area = %f\\n', area );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X Y W\\n' );\n fprintf ( 1, '\\n' );\n\n for order = 1 : order_num\n fprintf ( 1, ' %8d %14f %14f %14f\\n', order, xy(1:2,order), w(order) );\n end\n%\n% Transform the rule.\n%\n xy2 = reference_to_physical_t3 ( node_xy2, order_num, xy );\n%\n% Here is the physical triangle, and its transformed rule.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The physical triangle:\\n' );\n fprintf ( 1, '\\n' );\n\n for node = 1 : 3\n fprintf ( 1, ' %8d %14f %14f\\n', node, node_xy2(1:2,node) );\n end\n\n area2 = triangle_area ( node_xy2 );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Rule %d for physical triangle', rule );\n fprintf ( 1, ' with area = %f\\n', area2 );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X Y W\\n' );\n fprintf ( 1, '\\n' );\n\n for order = 1 : order_num\n fprintf ( 1, ' %8d %14f %14f %14f\\n', order, xy2(1:2,order), w(order) );\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/triangle_ncc_rule/triangle_ncc_rule_test05.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.6997220460656208}} {"text": "function varargout = EarthGradient(f,varargin)\n%GRADIENT Approximate gradient.\n% [FX,FY] = GRADIENT(F) returns the numerical gradient of the\n% matrix F. FX corresponds to dF/dx, the differences in x (horizontal) \n% direction. FY corresponds to dF/dy, the differences in y (vertical) \n% direction. The spacing between points in each direction is assumed to \n% be one. When F is a vector, DF = GRADIENT(F) is the 1-D gradient.\n%\n% [FX,FY] = GRADIENT(F,H), where H is a scalar, uses H as the\n% spacing between points in each direction.\n%\n% [FX,FY] = GRADIENT(F,HX,HY), when F is 2-D, uses the spacing\n% specified by HX and HY. HX and HY can either be scalars to specify\n% the spacing between coordinates or vectors to specify the\n% coordinates of the points. If HX and HY are vectors, their length\n% must match the corresponding dimension of F.\n%\n% [FX,FY,FZ] = GRADIENT(F), when F is a 3-D array, returns the\n% numerical gradient of F. FZ corresponds to dF/dz, the differences\n% in the z direction. GRADIENT(F,H), where H is a scalar, \n% uses H as the spacing between points in each direction.\n%\n% [FX,FY,FZ] = GRADIENT(F,HX,HY,HZ) uses the spacing given by\n% HX, HY, HZ. \n%\n% [FX,FY,FZ,...] = GRADIENT(F,...) extends similarly when F is N-D\n% and must be invoked with N outputs and either 2 or N+1 inputs.\n%\n% Note: The first output FX is always the gradient along the 2nd\n% dimension of F, going across columns. The second output FY is always\n% the gradient along the 1st dimension of F, going across rows. For the\n% third output FZ and the outputs that follow, the Nth output is the\n% gradient along the Nth dimension of F.\n%\n% Examples:\n% [x,y] = meshgrid(-2:.2:2, -2:.2:2);\n% z = x .* exp(-x.^2 - y.^2);\n% [px,py] = gradient(z,.2,.2);\n% contour(z), hold on, quiver(px,py), hold off\n%\n% Class support for input F:\n% float: double, single\n%\n% See also DIFF, DEL2.\n\n% Copyright 1984-2015 The MathWorks, Inc.\n\n[f,ndim,loc,rflag] = parse_inputs(f,varargin);\nnargoutchk(0,ndim);\n\n% Loop over each dimension. \n\nvarargout = cell(1,ndim);\nsiz = size(f);\n% first dimension \ng = zeros(size(f),class(f)); % case of singleton dimension\nh = loc{1}; \nn = siz(1);\n% Take forward differences on left and right edges\nif n > 1\n g(1,:) = (f(2,:) - f(1,:))./h;\n g(n,:) = (f(n,:) - f(n-1,:))./h;\nend\n\n% Take centered differences on interior points\nif n > 2\n h = 2*h;\n for nn = 2:n-1\n g(nn,:) = (f(nn+1,:)-f(nn-1,:)) ./ h;\n end\nend\n\nvarargout{1} = g;\n\n% second dimensions and beyond\nif ndim == 2\n % special case 2-D matrices to support sparse matrices,\n % which lack support for N-D operations including reshape\n % and indexing\n n = siz(2);\n h = loc{2};\n g = zeros(size(f),class(f));\n \n % Take forward differences on left and right edges\n if n > 1\n g(:,1) = (f(:,2) - f(:,1))./h;\n g(:,n) = (f(:,n) - f(:,n-1))./h;\n end\n \n % Take centered differences on interior points\n if n > 2\n h = 2*h;\n g(:,2:n-1) = (f(:,3:n) - f(:,1:n-2)) ./ h;\n end\n varargout{2} = g;\n \nelseif ndim > 2\n % N-D case\n for k = 2:ndim\n n = siz(k);\n newsiz = [prod(siz(1:k-1)) siz(k) prod(siz(k+1:end))];\n nf = reshape(f,newsiz);\n h = reshape(loc{k},1,[]);\n g = zeros(size(nf),class(nf)); % case of singleton dimension\n \n % Take forward differences on left and right edges\n if n > 1\n g(:,1,:) = (nf(:,2,:) - nf(:,1,:))/(h(2)-h(1));\n g(:,n,:) = (nf(:,n,:) - nf(:,n-1,:))/(h(end)-h(end-1));\n end\n \n % Take centered differences on interior points\n if n > 2\n h = h(3:n) - h(1:n-2);\n g(:,2:n-1,:) = (nf(:,3:n,:) - nf(:,1:n-2,:)) ./ h;\n end\n \n varargout{k} = reshape(g,siz);\n end\nend\n\n% Swap 1 and 2 since x is the second dimension and y is the first.\nif ndim > 1\n varargout(2:-1:1) = varargout(1:2);\nelseif rflag\n varargout{1} = varargout{1}.';\nend\n\n\n%-------------------------------------------------------\nfunction [f,ndim,loc,rflag] = parse_inputs(f,v)\n%PARSE_INPUTS\n% [ERR,F,LOC,RFLAG] = PARSE_INPUTS(F,V) returns the spacing\n% LOC along the x,y,z,... directions and a row vector\n% flag RFLAG. \n\nloc = {};\n\n% Flag vector case and row vector case.\nndim = ndims(f);\nvflag = false;\nrflag = false;\nif isvector(f)\n ndim = 1;\n vflag = true;\n if isrow(f) % Treat row vector as a column vector\n rflag = true;\n f = f.';\n end\nend\n\nindx = size(f);\n\n% Default step sizes: hx = hy = hz = 1\nif isempty(v)\n % gradient(f)\n loc = cell(1, ndims(f));\n for k = 1:ndims(f)\n loc(k) = {1:indx(k)};\n end\nelseif isscalar(v) % gradient(f,h)\n % Expand scalar step size\n if isscalar(v{1})\n loc = cell(1, ndims(f));\n for k = 1:ndims(f)\n h = v{1};\n loc(k) = {h*(1:indx(k))};\n end\n % Check for vector case\n elseif vflag\n loc(1) = v(1);\n else\n error(message('MATLAB:gradient:InvalidInputs'));\n end\nelseif ndims(f) == numel(v) % gradient(f,hx,hy,hz,...)\n % Swap 1 and 2 since x is the second dimension and y is the first.\n loc = v;\n if ndim > 1\n loc(2:-1:1) = loc(1:2);\n end\nelse\n error(message('MATLAB:gradient:InvalidInputs'));\nend\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/@msh/private/EarthGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.6997220395611515}} {"text": "function [H_x] = H_xfn(kMinus1State, imuMeasurement, deltaT )\n%H_XFN Compute the 6x6 matrix H_x_k \n\npsiVec = imuMeasurement.omega*deltaT;\npsiMag = norm(psiVec);\nd = imuMeasurement.v*deltaT;\n\nPsi = cos(psiMag)*eye(3) + (1 - cos(psiMag))*(psiVec/psiMag)*(psiVec/psiMag)' - sin(psiMag)*crossMat(psiVec/psiMag);\n\n%Construct the H_x matrix\nH_x = zeros(6,6);\nH_x(1:3, 1:3) = eye(3);\nH_x(4:6, 4:6) = Psi;\nH_x(1:3, 4:6) = -kMinus1State.C_vi'*crossMat(d);\n\n\nend\n\n", "meta": {"author": "utiasSTARS", "repo": "msckf-swf-comparison", "sha": "ad9566ef35c3e4792a89b04623e1fa2f99238435", "save_path": "github-repos/MATLAB/utiasSTARS-msckf-swf-comparison", "path": "github-repos/MATLAB/utiasSTARS-msckf-swf-comparison/msckf-swf-comparison-ad9566ef35c3e4792a89b04623e1fa2f99238435/swf/utils/H_xfn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6997163126615473}} {"text": "clear; close all;\n\nd = 100;\nbeta = 1e-1;\nX = rand(1,d);\nw = randn;\nb = randn;\nt = w'*X+b+beta*randn(1,d);\nx = linspace(min(X),max(X),d); % test data\n\n[model,llh] = linRegVb(X,t);\n% [model,llh] = rvmRegVb(X,t);\nplot(llh);\n[y, sigma] = linRegPred(model,x,t);\nfigure\nplotCurveBar(x,y,sigma);\nhold on;\nplot(X,t,'o');\nhold off", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/demo/ch10/rvmRegVb_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6997163060400573}} {"text": "function orientation = FlyOrient(subset_frame, threshold)\n\n%FLYORIENT\n% Usage:\n% orientation = FlyOrient(subset_frame, threshold)\n%\n% This function takes in a subset frame around the fly (calculated by\n% FindFly) and discards the 3D data by placing points where the pixel intensity\n% is larger than the user chosen threshold. Then, Principal Components\n% Analysis (by way fot the pca1 function) is performed on the resulting \n% scatter plot to find the direction of maximum variance --- this direction\n% is taken to be the fly's (ambiguous) orientation. \n% orientation is a vector consisting of two angles (complements) that comprise \n% the body axis. The first element is an angle in the upper half plane; the\n% second element is an angle in the lower half plane.\n\n% Written by Dan Valente\n% 11 October 2006\n\n%Normalize frame data by pixel of maximum intensity\nsubset_frame = subset_frame/max(max(subset_frame));\n\n% Put dots where fly is and do PCA on reduced data set\n[rows, cols] = find(subset_frame >= threshold);\nrows = length(subset_frame(:,1))-rows+1;\nx = [cols';rows'];\n[xnew, PC, V, data] = pca1(x);\n\n% Find orientation vectors (two, mirrored across diagonal), and group into\n% upper half and lower half planes.\na1 = PC(1,1);\nb1 = PC(2,1);\na2 = -PC(1,1);\nb2 = -PC(2,1);\nif (b1 >= 0 );\n orientUHP = atan2(b1,a1);\n orientLHP = atan2(b2,a2);\nelseif (b2 >=0);\n orientUHP = atan2(b2,a2);\n orientLHP = atan2(b1,a1);\nelse\nend\n\n% The vector we will return\norientation = [orientUHP orientLHP];\n\nreturn;\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/fly_track/FTrack/functions/FlyOrient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806522, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6997163016895595}} {"text": "function polygon_properties_test02 ( )\n\n%*****************************************************************************80\n%\n%% POLYGON_PROPERTIES_TEST02 tests POLYGON_AREA.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 07 May 2014\n%\n% Author:\n%\n% John Burkardt\n%\n test_num = 2;\n area_exact_test = [ 2.0, 6.0 ];\n n_test = [ 4, 8 ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POLYGON_PROPERTIES_TEST02\\n' );\n fprintf ( 1, ' For a polygon:\\n' );\n fprintf ( 1, ' POLYGON_AREA computes the area.\\n' );\n\n for test = 1 : test_num\n\n n = n_test(test);\n area_exact = area_exact_test(test);\n\n if ( test == 1 )\n\n v = [ ...\n 1.0, 0.0; ...\n 2.0, 1.0; ...\n 1.0, 2.0; ...\n 0.0, 1.0 ]';\n\n elseif ( test == 2 )\n\n v = [ ...\n 0.0, 0.0; ...\n 3.0, 0.0; ...\n 3.0, 3.0; ...\n 2.0, 3.0; ...\n 2.0, 1.0; ...\n 1.0, 1.0; ...\n 1.0, 2.0; ...\n 0.0, 2.0 ]';\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of polygonal vertices = %d\\n', n );\n\n r8mat_transpose_print ( 2, n, v, ' The polygon vertices:' );\n\n area = polygon_area ( n, v );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Exact area is %g\\n', area_exact );\n fprintf ( 1, ' The computed area is %g\\n', area );\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/polygon_properties/polygon_properties_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.6996775466568723}} {"text": "%\n% Written by M. Harper Langston - 5/10/00\n% harper@cims.nyu.edu\n%\n% For this sparse LU solver of Ax = b, A has band s.\n% For example, the following matrix has band s = 1\n%\n% x x 0 0 0 0\n% x x x 0 0 0\n% 0 x x x 0 0\n% 0 0 x x x 0\n% 0 0 0 x x x\n% 0 0 0 0 x x\n%\n%\nfunction [x] = Band_Solve(A,b)\n% Here, s is the band number\n[m,n] = size(A);\nif m~=n\n error('Matrix not sqaure') % Want square matrix for simplicity\nend\n% Find the band of A\nfor l = 1:n\n if A(m,l)~=0\n s = n-l;\n break;\n end\nend\n% Do the sparse LU decomposition for a matrix of band s\nfor j = 1:m\n if j >= m-s\n L(j:m,j) = A(j:m,j)./A(j,j);\n\t\tU(j,j:m) = A(j,j:m);\n \tA(j:m,j:m) = A(j:m,j:m) - L(j:m,j)*U(j,j:m);\n else\n \tL(j:j+s,j) = A(j:j+s,j)./A(j,j);\n \tU(j,j:j+s) = A(j,j:j+s);\n \tA(j:j+s,j:j+s) = A(j:j+s,j:j+s) - L(j:j+s,j)*U(j,j:j+s);\n end\nend\nL = sparse(L);\nU = sparse(U);\n% Call backsolve routine, which I wrote to pay heed to sparsity.\n[y] = Back_Solve(L,b);\n[x] = Back_Solve(U,y);\n%\n% Written by M. Harper Langston - 5/10/00\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/21472-2d-fast-poisson-solver/Band_Solve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6996766922586612}} {"text": "function c=ref_rdftiii_1(f)\n%REF_RDFTIII_1 Reference RDFT by FFT\n% Usage: c=ref_rdftiii_1(f);\n%\n% Compute RDFTII by doing a DFTIII and returning half the coefficients.\n% Only works for real functions.\n%\n% The transform is orthonormal\n\n\nL=size(f,1);\nLhalf=floor(L/2);\nLend=Lhalf*2;\n\ncc=ref_dftiii(f);\n\nc=zeros(size(f));\n\n% Copy the cosine-part of the coefficients.\nc(1:2:Lend,:)=sqrt(2)*real(cc(1:Lhalf,:));\n\n% Copy the sine-part of the coefficients.\nc(2:2:Lend,:)=-sqrt(2)*imag(cc(1:Lhalf,:));\n\n% If f has an odd length, we must also copy the Niquest-wave\n% (it is real)\nif mod(L,2)==1\n c(end,:)=real(cc((L+1)/2,:));\nend;\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/reference/ref_rdftiii_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942093072239, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.699676685541768}} {"text": "%TR2RPY\tConvert a homogeneous transform matrix to roll/pitch/yaw angles\n%\n%\t[A B C] = TR2RPY(TR) returns a vector of Euler angles \n%\tcorresponding to the rotational part of the homogeneous transform TR.\n%\n%\tSee also RPY2TR, TR2EUL\n\n%\tCopright (C) Peter Corke 1993\nfunction rpy = tr2rpy(m)\n\t\n\trpy = zeros(1,3);\n\n\tif abs(m(1,1)) < eps & abs(m(2,1)) < eps,\n\t\trpy(1) = 0;\n\t\trpy(2) = atan2(-m(3,1), m(1,1));\n\t\trpy(3) = atan2(-m(2,3), m(2,2));\n\telse,\n\t\trpy(1) = atan2(m(2,1), m(1,1));\n\t\tsp = sin(rpy(1));\n\t\tcp = cos(rpy(1));\n\t\trpy(2) = atan2(-m(3,1), cp * m(1,1) + sp * m(2,1));\n\t\trpy(3) = atan2(sp * m(1,3) - cp * m(2,3), cp*m(2,2) - sp*m(1,2));\n\tend\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/EKF_monoSLAM_1pRANSAC/matlab_code/tr2rpy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.699676680841383}} {"text": "function btv_test04 ( )\n\n%*****************************************************************************80\n%\n%% BTV_TEST04 tests BURGERS_TIME_VISCOUS with the shock initial condition.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 April 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BTV_TEST04\\n' );\n fprintf ( 1, ' Test BURGERS_TIME_VISCOUS with the shock initial condition.\\n' );\n fprintf ( 1, ' Use periodic boundaries.\\n' );\n\n nx = 81;\n nt = 300;\n t_max = 3.0;\n nu = 0.01;\n bc = 4;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Initial condition: shock\\n' );\n fprintf ( 1, ' Number of space nodes = %d\\n', nx );\n fprintf ( 1, ' Number of time steps = %d\\n', nt );\n fprintf ( 1, ' Final time T_MAX = %g\\n', t_max );\n fprintf ( 1, ' Viscosity = %g\\n', nu );\n fprintf ( 1, ' Boundary condition = %d\\n', bc );\n\n U = burgers_time_viscous ( @ic_shock, nx, nt, t_max, nu, bc );\n\n x = linspace ( -1.0, +1.0, nx );\n\n figure ( 4 )\n\n plot ( x, U(1:50:(nt+1),:), 'Linewidth', 3 )\n grid on\n xlabel ( '<-- X -->' )\n ylabel ( '<-- U(X,T) -->' )\n title ( 'Burgers equation solutions over time, initial condition shock' )\n\n filename = 'btv_test04.png';\n print ( '-dpng', filename )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Saved plot as \"%s\"\\n', filename );\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/burgers_time_viscous/btv_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.6995373880220409}} {"text": "% polyvalm2 - Evaluate polynomial with matrix argument.\n%*************************************************************************************\n% \n% MATLAB (R) is a trademark of The Mathworks (R) Corporation\n% \n% Function: polyvalm2\n% Filename: polyvalm2.m\n% Programmer: James Tursa\n% Version: 1.1\n% Date: November 11, 2009\n% Copyright: (c) 2009 by James Tursa, All Rights Reserved\n%\n% This code uses the BSD License:\n%\n% Redistribution and use in source and binary forms, with or without \n% modification, are permitted provided that the following conditions are \n% met:\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% \n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE \n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n% POSSIBILITY OF SUCH DAMAGE.\n% \n% polyvalm2 evaluates a polynomial with a square matrix argument faster\n% than the MATLAB built-in functions polyvalm or mpower.\n%\n% Y = polyvalm2(P,X), when P is a vector of length N+1 whose\n% elements are the coefficients of a polynomial, is the value\n% of the polynomial evaluated with matrix argument X. X must\n% be a square matrix. \n%\n% Y = P(1)*X^N + P(2)*X^(N-1) + ... + P(N)*X + P(N+1)*I\n%\n% Class support for inputs P, X:\n% float: double, single\n%\n% The polyvalm2 speed improvements come from the following:\n%\n% 1) The MATLAB built-in function polyvalm uses Horner's method.\n% polyvalm2 uses a binary decomposition of the matrix powers\n% to do the calculation more efficiently, reducing the total\n% number of matrix multiplies used to calculate the answer.\n%\n% 2) polyvalm calculates the product of a scalar times a matrix\n% as the product of diag(scalar*ones(etc))*matrix ... i.e. it\n% does a matrix multiply. polyvalm2 will calculate this more\n% efficiently as the simple product scalar*matrix.\n%\n% 3) polyvalm does all of the calculations shown above, even if\n% the coefficient P(i) is zero. polyvalm2 does not do\n% calculations for P(i) coefficients that are zero.\n%\n% 4) polyvalm converts sparse matrix inputs into full matrices to\n% do the calculations, whereas polyvalm2 keeps the intermediate\n% calculations and the answer sparse.\n%\n% An extreme case of speed difference can be found with a sparse\n% matrix example:\n%\n% >> A = sprand(2500,2500,.01);\n% >> p = [1 2 3 4];\n% >> tic;polyvalm(p,A);toc\n% Elapsed time is 43.669362 seconds.\n% >> tic;polyvalm2(p,A);toc\n% Elapsed time is 4.240375 seconds.\n%\n% The trade-off is that polyvalm2 uses more memory for intermediate\n% variables than polyvalm, so for very large matrices polyvalm2 can\n% run out of memory. In these cases polyvalm2 will abandon the\n% efficient calculation method and just call the built-in polyvalm.\n% For sparse matrix inputs, however, polyvalm2 will typically be more\n% memory efficient than the MATLAB polyvalm function.\n%\n% Caution: Since polyvalm2 uses different calculations to form the matrix\n% powers, the end result may not match polyvalm exactly. Also, for the\n% case where only the leading coefficient is non-zero, polyvalm2 may not\n% match mpower exactly. But the answer will be just as accurate. And if\n% there are inf's or NaN's involved, then the end result will not, in\n% general, match polyvalm or mpower results. This should not be a great\n% drawback to using polyvalm2, however, since even the MATLAB built-in\n% functions polyvalm and mpower will not match each other in these cases.\n% (By reordering the calculations, the NaN's propagate differently)\n% \n% Change Log:\n% Nov 11, 2009: Updated for sparse matrix input --> sparse result\n%\n%**************************************************************************\n\nfunction Y = polyvalm2(p,X)\n%\\\n% Check the arguments\n%/\nif( nargin ~= 2 )\n error('MATLAB:polyvalm2:InvalidNumberOfArgs','Need two input arguments.');\nend\nif( nargout > 1 )\n error('MATLAB:polyvalm2:TooManyOutputArgs','Too many output arguments.');\nend\nclassname = superiorfloat(p,X);\nif( ~(isvector(p) || isempty(p)) )\n error('MATLAB:polyvalm2:InvalidP','P must be a vector.');\nend\nz = size(X);\nif( length(z) > 2 || z(1) ~= z(2) )\n error('MATLAB:polyvalm2:NonSquareMatrix','Matrix must be square.');\nend\nif( isempty(X) )\n if( issparse(X) )\n Y = sparse(z(1),z(2));\n else\n Y = zeros(z,classname);\n end\n return\nend\n%\\\n% Clear out any leading zeros and reverse the coefficients\n%/\ntry\n f = find(p,1,'first');\n if( isempty(f) )\n if( issparse(X) )\n Y = sparse(z(1),z(2));\n else\n Y = zeros(z,classname);\n end\n return\n end\n p2 = p(end:-1:f);\n%\\\n% Initialize return value with the constant term, and then set the\n% constant term coefficient to 0 so we don't process it anymore.\n%/\n if( issparse(X) )\n Y = diag(p2(1) * sparse(ones(z(1),1)));\n else\n Y = diag(p2(1) * ones(z(1),1,classname));\n end\n p2(1) = 0;\n%\\\n% Special small cases use custom code for quick return\n%/\n np = length(p2);\n if( np == 1 )\n return\n elseif( np == 2 )\n if( p2(2) == 1 )\n Y = Y + X;\n else\n Y = Y + p2(2) * X;\n end\n return\n end\n%\\\n% Initialize the cell array that will hold the X powers\n%/\n cp{np} = [];\n%\\\n% Get the binary decomposition of the powers as rows of binary characters,\n% each row representing a different power, and arranged from 0 at the top\n% to the highest power at the bottom.\n%/\n bp = dec2bin(0:(np-1));\n%\\\n% Loop through the bit positions from least significant to most significant\n%/\n P = X;\n zz = size(bp,2);\n for n=zz:-1:1\n%\\\n% Only process those rows with non-zero coefficients. If the bit position\n% for this row is 1, then we need to apply the current power of X to the\n% cell for this row. Each cell is building up the appropriate power of X.\n% cp{1} is for X^0 (not used or needed actually because we have that piece\n% already calculated from above), cp{2} is for X^1, cp{3} is for X^2, etc.\n% P is the current power of X, i.e. P = X^(2^(zz-n))\n%/\n check = (p2 ~= 0);\n for m=1:np\n if( check(m) && bp(m,n) == '1' )\n if( isempty(cp{m}) )\n cp{m} = P;\n else\n cp{m} = cp{m} * P;\n end\n%\\\n% Look at all the downstream bit patterns. If any match the current one for\n% the bits processed so far, then just copy the current cell into the\n% downstream cells (no need to repeat the calculation downstream because we\n% already know the answer). Then reset the check flag for that downstream\n% row so we don't process it for this particular loop index.\n%/\n for k=m+1:np\n if( check(k) && isequal(bp(m,n:zz),bp(k,n:zz)) )\n cp{k} = cp{m};\n check(k) = 0;\n end\n end\n%\\\n% If the remaining leftmost bits of the current row are 0, then we are done\n% with this power of X. Apply the coefficient and add it to the result,\n% then free up the memory for this cell position. Also, reset the\n% coefficient for this row to 0 so we know not to process this row anymore.\n%/\n if( all(bp(m,1:(n-1))=='0') )\n Y = Y + p2(m) * cp{m};\n p2(m) = 0;\n cp{m} = [];\n end\n end\n end\n%\\\n% Square the current power of X, but not if it is the last index in the\n% loop because in that case it won't be used or needed. For some reason,\n% P * P is a lot faster than P^2.\n%/\n if( n ~= 1 )\n P = P * P;\n end\n end\n%\\\n% The binary decomposition scheme used too much memory, so clear all of the\n% local large variables and just call the built in polyvalm function\n% instead. This is slower and computationally less efficient, but it is\n% more memory efficient so it might work.\n%/\ncatch\n warning('MATLAB:polyvalm2:OutOfMemory','Out Of Memory ... Resorting to built-in polyvalm');\n clear cp P bp p2 check;\n Y = polyvalm(p,X);\nend\nreturn\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/25780-polyvalm2-a-faster-matrix-polynomial-evaluator/polyvalm2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.6995373858589136}} {"text": "function M = mult(A, f, lambda)\n%MULT Multiplication operator for the ultraspherical spectral method. \n% M = MULT(A, F, lambda) returns the multiplication operator that represents \n% u(x) -> F(x)u(x), in the C^{(lambda)} ultraspherical polynomial basis. \n% \n% If lambda = 0, then the operator is Toeplitz-plus-Hankel-plus-rank-1 and\n% represents multiplication in Chebyshev T coefficients.\n%\n% If lambda = 1, then the operator is Toeplitz-plus-Hankel and represents\n% multiplication in Chebyshev U or C^{(1)} coefficients. \n% \n% If lambda > 1, then the operator does not have any Toeplitz/Hankel structure\n% and is constructed using a three-term recurrence.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Obtaining some useful information:\nn = A.dimension;\nd = A.domain;\nf = restrict(f, d);\nnumIntervals = length(d) - 1;\n\n% Find the diagonal blocks;\nblocks = cell(numIntervals);\nfor k = 1:numIntervals\n blocks{k} = ultraS.multmat(n(k), f.funs{k}, lambda);\nend\n\n% Assemble:\nM = blkdiag(blocks{:});\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/@ultraS/mult.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6995266999105297}} {"text": "%% Band-Pass filter visualization\n\n[b, a] = butter(4, [0.5 50] / 100, 'bandpass');\ny = filter(b, a, cnt.x);\ncnt.x=cnt.x(:,1:34);\ncnt.clab=cnt.clab(:,1:34);\n\nf_sz=ceil(length(cnt.x)/2);\nf=100*linspace(0,1,f_sz);\nf_X=fft(cnt.x);\nf_y=fft(y);\nsubplot(2,1,1)\nstem(f,abs(f_X(1:f_sz)));\ntitle('Original signal');\nxlabel('frequency');\nxlim([0 50]);\nylabel('power');\nsubplot(2,1,2)\nstem(f,abs(f_y(1:f_sz)));\nxlim([0 50]);\n\ntitle('Application of the beta (13-30Hz) bandpass filter')\nxlabel('frequency');\nylabel('power');", "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_NeuroDriving/BandPass_filter_visualization.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6995266932813566}} {"text": "function [sigma,u,eqn,info] = elasticitymfemP1P0(node,elem,pde,bdFlag,option)\n\n\nif ~exist('option','var'), option = []; end\n\ntime = cputime; % record assembling time\n\nd = 2; % two dimensions\nN = size(node,1);\nNT = size(elem,1);\nNsigma = 3*N;\nNu = 2*NT;\nNdof = Nsigma + Nu;\n\n%% Assemble matrix\n[Dphi,area] = gradbasis(node,elem);\n\n%% Mass matrix of linear (P1) element\nM = sparse(N,N);\nfor i = 1:3\n for j = i:3\n ii = double(elem(:,i));\n jj = double(elem(:,j));\n if (j==i)\n M = M + sparse(ii,jj,area/6,N,N);\n else\n M = M + sparse([ii;jj],[jj;ii],[area/12; area/12],N,N); \n end \n end\nend\n\n%% Compliance tensor\nlambda = pde.lambda;\nmu = pde.mu;\nC1 = 1/(2*mu);\nC2 = lambda/(2*mu + d*lambda);\n% E = mu*(3*lambda+2*mu)/(lambda+mu);\n% nu = lambda/(2*(lambda+mu));\nA = sparse(C1*(eye(3,3) - C2*([1 1 0]'*[1 1 0])));\n\n%% Matrix for (Asigma,tau)\nAm = kron(A,M);\n\n%% Div operator\nelem2dofsigma = zeros(NT,3,3);\nelem2dofsigma(:,:,1) = double(elem);\nfor k = 2:3\n elem2dofsigma(:,:,k) = elem2dofsigma(:,:,k-1)+N;\nend\nelemIdx = (1:NT)';\nelem2dofu = [elemIdx elemIdx+NT];\nDx = squeeze(Dphi(:,1,:)).*repmat(area,1,3);\nDy = squeeze(Dphi(:,2,:)).*repmat(area,1,3);\nclear Dphi\n% u1: dx sigma(1) + dy sigma(3)\n% u2: dx sigma(3) + dy sigma(2)\nB = sparse(repmat(elem2dofu(:,1),1,3),elem2dofsigma(:,:,1),Dx,Nu,Nsigma) ...\n + sparse(repmat(elem2dofu(:,1),1,3),elem2dofsigma(:,:,3),Dy,Nu,Nsigma) ... \n + sparse(repmat(elem2dofu(:,2),1,3),elem2dofsigma(:,:,3),Dx,Nu,Nsigma) ...\n + sparse(repmat(elem2dofu(:,2),1,3),elem2dofsigma(:,:,2),Dy,Nu,Nsigma);\n\n%% Stabilization\nT = auxstructure(elem);\nedge2elem = T.edge2elem;\nelem2edge = T.elem2edge;\n[normal,edgeLength,unitNormal] = edgenormal(node,T.edge);\nclear T;\nharea = edgeLength.^2;\n% elementwise part: [u_in_k']:[u_jn_k']=n_k(i)n_k(j);\n% Use Dphi as a scaled outwards normal vector to compute - int_F h[u n'][v n']\nC = sparse(Nu,Nu);\nfor i = 1:2\n for j = i:2\n ii = elem2dofu(:,i);\n jj = elem2dofu(:,j);\n Cij = zeros(NT,1);\n for k = 1:3 % sum of all four faces\n fk = elem2edge(:,k);\n Cij = Cij + harea(fk).*((i==j) + unitNormal(fk,i).*unitNormal(fk,j));\n end\n if (j==i) \n C = C + sparse(ii,jj,-Cij,Nu,Nu);\n else\n C = C + sparse([ii;jj],[jj;ii],repmat(-Cij,1,2),Nu,Nu); \n end \n end\nend\n% cross face part\nfor i = 1:2\n for j = 1:2\n ii = elem2dofu(edge2elem(:,1),i);\n jj = elem2dofu(edge2elem(:,2),j);\n Cij = harea.*((i==j) + unitNormal(:,i).*unitNormal(:,j));\n C = C + sparse([ii;jj],[jj;ii],repmat(-Cij,1,2),Nu,Nu); \n end\nend\n\n%% Assemble the right hand side\nF = zeros(Ndof,1);\nfu = zeros(NT,2);\nif ~isfield(pde,'f') || (isreal(pde.f) && (pde.f==0))\n pde.f = [];\nend\nif ~isfield(option,'fquadorder')\n option.fquadorder = 2; % default order\nend\nif ~isempty(pde.f)\n\t[lambda,weight] = quadpts3(option.fquadorder);\n\tnQuad = size(lambda,1);\n for p = 1:nQuad\n\t\t% quadrature points in the x-y coordinate\n\t\tpxy = lambda(p,1)*node(elem(:,1),:) ...\n\t\t\t+ lambda(p,2)*node(elem(:,2),:) ...\n\t\t\t+ lambda(p,3)*node(elem(:,3),:);\n\t\tfp = pde.f(pxy);\n\t\tfu = fu - weight(p)*fp;\n end\n fu = fu.*repmat(area,1,2);\nend\nclear fp\nF((Nsigma+1):Ndof,1) = fu(:);\n\n%% Boundary Conditions\nif ~exist('bdFlag','var'), bdFlag = []; end\neqn = struct('Am',Am,'B',B,'C',C,'f',F(1:Nsigma),'g',F(Nsigma+1:end));\nassembleTime = cputime - time;\n%% Solver\nbigA = [Am B'; B C];\nbigu = bigA\\F;\nsigma = bigu(1:Nsigma);\nu = bigu(Nsigma+1:end);\n\n%% Output information\ninfo.assembleTime = assembleTime; ", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/equation/elasticitymfemP1P0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6995266848691655}} {"text": "function [db,f]=lpccc2db(cc,np,nc,c0)\n%LPCCC2DB Convert complex cepstrum to dB power spectrum DB=(CC,NP,NC)\n%\n% Inputs: cc(nf,n) Complex ceptral coefficients excluding c(0), one frame per row\n% np Size of output spectrum is np+1 [n]\n% Alternatively, np can be a vector of output frequencies in the range 0 to 0.5\n% nc Highest cepstral coefficient to use [np or, if np is a vector, n]\n% Set nc=-1 to use n coefficients\n% c0(nf,1) Cepstral coefficient cc(0) [0]\n%\n% Outputs: db(nf,np+2) Power spectrum from DC to Nyquist in dB\n% f(1,np+2) Normalized frequencies (0 to 0.5)\n%\n% The \"complex cepstral coefficients\", cc(n), are the inverse discrete-time Fourier transform\n% of the log of the complex-valued spectrum. The cc(n) are real-valued and, for n<0, cc(n)=0.\n% The \"real cepstral coeffcients\", rc(n), are the inverse discrete-time Fourier transform\n% of the log of the magnitude spectrum; rc(0)=cc(0) and rc(n)=0.5*cc(n) for n~=0.\n% For highest speed, choose np to be a power of 2.\n\n% Copyright (C) Mike Brookes 1998-2014\n% Version: $Id: lpccc2db.m 5025 2014-08-22 17:07:24Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\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 can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n[nf,mc]=size(cc);\nif nargin<2 || ~numel(np)\n if nargout\n np=mc;\n else\n np=128;\n end\nend\nk=10/log(10);\nif nargin>=3 && numel(nc)==1 && nc==-1 nc=mc; end\nif nargin<4 || ~numel(c0) c0=zeros(nf,1); end\nif numel(np)>1 || np(1)<1\n if nargin<3 || ~numel(nc) nc=mc; end\n f=np(:)';\n if nc==mc\n db=k*(2*[c0 cc]*cos(2*pi*(0:mc)'*f));\n else\n db=k*(2*[c0 lpccc2cc(cc,nc)]*cos(2*pi*(0:nc)'*f));\n end\nelse\n if nargin<3 || ~numel(nc) nc=np; end\n if nc==mc\n db=k*(2*real(rfft([c0 cc].',2*np).'));\n else\n db=k*(2*real(rfft([c0 lpccc2cc(cc,nc)].',2*np).'));\n end\n f=linspace(0,0.5,np+1);\nend\nif ~nargout\n plot(f,db.');\n xlabel('Normalized frequency f/f_s');\n ylabel('Gain (dB)');\nend\n\n\n\n\n\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/lpccc2db.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.6995002504010835}} {"text": "function square_grid_test01 ( )\n\n%*****************************************************************************80\n%\n%% SQUARE_GRID_TEST01 tests SQUARE_GRID using the same parameters for all dimensions.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 31 August 2014\n%\n% Author:\n%\n% John Burkardt\n%\n a = [ -1.0, -1.0 ];\n b = [ +1.0, +1.0 ];\n c = [ 1, 1 ];\n ns = [ 3, 3 ];\n\n n = ns(1) * ns(2);\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SQUARE_GRID_TEST01\\n' );\n fprintf ( 1, ' Create a grid using SQUARE_GRID.\\n' );\n fprintf ( 1, ' Use the same parameters in every dimension.\\n' );\n fprintf ( 1, ' Number of grid points N = %d\\n', n );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I NS C A B\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : 2\n fprintf ( 1, ' %4d %4d %4d %8.4f %8.4f\\n', i, ns(i), c(i), a(i), b(i) );\n end\n\n x = square_grid ( n, ns, a, b, c );\n r8mat_transpose_print ( 2, n, x, ' Grid points:' );\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/square_grid/square_grid_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.8791467611766711, "lm_q1q2_score": 0.6995002501942271}} {"text": "% This code calculates the 3D distances between all possible pairs\n% (combination of n epicenters taken 2 at a time) of earthquakes of\n% a given dataset.\n%\n%\n% Attributing the corresponding catalog to E\n%\nif ~exist('index', 'var')\n index = 1;\nend\n\nif index == 1\n E = newt2;\nelseif index == 2\n E = ran;\nelseif index == 3\n E = rann;\nend\n%\n% Variables\n%\nN = size(E,1);\t\t\t\t% N= # of events in the catalogue; E= Earthquake catalogue\npairdist = []; \t\t\t% pairdist= Vector of interevent distances\nj = nchoosek(N,2)\t\t\t% j= # of interevent distances calculated\npairdist = zeros(j,1);\ndepth = zeros(j,1);\nk = 0;\n\nHo_Wb = waitbar(0,'Calculating the fractal dimension');\nHf_Cfig = gcf;\nHf_child = get(groot,'children');\nset(Hf_child,'pointer','watch','papertype','A4');\n%\n% Calculation of the interevent distances in 2D plus the depths differences.\n%\nfor i = 1:(N-1)\n\n lon1 = repmat(E(i,1), [(N-i),1]);\n lat1 = repmat(E(i,2), [(N-i),1]);\n depth1 = repmat(E(i,7), [(N-i),1]);\n lon2 = E((i+1):end, 1);\n lat2 = E((i+1):end, 2);\n depth2 = E((i+1):end, 7);\n pairdist(k+1:k + size(lon1, 1)) = distance(lat1,lon1,lat2,lon2);\n depth(k+1:k + size(lon1, 1)) = depth1-depth2;\n k = k + size(lon1,1);\n waitbar((0.5/(N-1))*i, Ho_Wb);\n\nend\n%\n% Converts the interevent distances from degrees to kilometers and calculates\n% the interevent distances in three dimensions.\n%\npairdist = pairdist.*111;\npairdist = (pairdist.^2 + depth.^2).^0.5;\nclear depth;\n%\n% Compute the correlation integral\n%\nd = 3;\t\t\t%the embedding dimension\ndocorint;\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/fractal/dopd3N.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.6995002345057849}} {"text": "% This example shows how to calculate and plot both the fundamental\n% quasi-TE eigenmode and quasi-TM eigenmode of an example 3-layer\n% ridge waveguide using the semivectorial eigenmode solver.\n\n% Refractive indices:\nn1 = 3.34; % Lower cladding\nn2 = 3.44; % Core\nn3 = 1.00; % Upper cladding (air)\n\n% Vertical dimensions:\nh1 = 2.0; % Lower cladding\nh2 = 1.3; % Core thickness\nh3 = 0.5; % Upper cladding\nrh = 1.1; % Ridge height\n\n% Horizontal dimensions:\nrw = 1.0; % Ridge half-width\nside = 1.5; % Space on side\n\n% Grid size:\ndx = 0.0125; % grid size (horizontal)\ndy = 0.0125; % grid size (vertical)\n\nlambda = 1.55; % vacuum wavelength\nnmodes = 1; % number of modes to compute\n\n[x,y,xc,yc,nx,ny,eps,edges] = waveguidemesh([n1,n2,n3],[h1,h2,h3], ...\n rh,rw,side,dx,dy); \n\n% First, consider the quasi-TE mode:\n\n[Ex,neff] = svmodes(lambda,n2,nmodes,dx,dy,eps,'000S','EX');\n\nfprintf(1,'neff = %.6f\\n',neff);\n\nfigure(1);\ncontourmode(x,y,Ex);\ntitle('Ex (TE Mode)'); xlabel('x'); ylabel('y'); \nfor v = edges, line(v{:}); end\n\n% Next, consider the quasi-TM mode:\n\n[Ey,neff] = svmodes(lambda,n2,nmodes,dx,dy,eps,'000S','EY');\n\nfprintf(1,'neff = %.6f\\n',neff);\n\nfigure(2);\ncontourmode(x,y,Ey);\ntitle('Ey (TM mode)'); xlabel('x'); ylabel('y'); \nfor v = edges, line(v{:}); end\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/12734-waveguide-mode-solver/examples/basic_semivector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.7577943603346811, "lm_q1q2_score": 0.6994738666603024}} {"text": "function [D]=distND(V1,V2)\n\nD=zeros(size(V1,1),size(V2,1));\n\nfor q=1:1:size(V1,2) %For all dimensions\n A=V1(:,q); %Coordinates of first set\n B=V2(:,q); %Coordinates of second set\n \n AB=A(:,ones(1,size(B,1)));\n BA=B(:,ones(1,size(A,1)))';\n \n D=D+(AB-BA).^2;\nend\nD=sqrt(D);\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-2020 Kevin Mattheus Moerman\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": "MultiDIC", "repo": "MultiDIC", "sha": "d363c3ea74673e58df275d4a4c8e528ef5472acb", "save_path": "github-repos/MATLAB/MultiDIC-MultiDIC", "path": "github-repos/MATLAB/MultiDIC-MultiDIC/MultiDIC-d363c3ea74673e58df275d4a4c8e528ef5472acb/lib_ext/GIBBON/lib/distND.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605945, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6994348307178078}} {"text": "function truncated_normal_a_cdf_test ( )\n\n%*****************************************************************************80\n%\n%% TRUNCATED_NORMAL_A_CDF_TEST tests TRUNCATED_NORMAL_A_CDF;\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 September 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRUNCATED_NORMAL_A_CDF_TEST\\n' );\n fprintf ( 1, ' TRUNCATED_NORMAL_A_CDF evaluates the lower Truncated Normal CDF.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The \"parent\" normal distribution has\\n' );\n fprintf ( 1, ' mean = mu\\n' );\n fprintf ( 1, ' standard deviation = sigma\\n' );\n fprintf ( 1, ' The parent distribution is truncated to\\n' );\n fprintf ( 1, ' the interval [a,+oo)\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Stored Computed\\n' );\n fprintf ( 1, ' X Mu S A CDF CDF\\n' );\n fprintf ( 1, '\\n');\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, mu, sigma, a, x, cdf1 ] ...\n = truncated_normal_a_cdf_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n cdf2 = truncated_normal_a_cdf ( x, mu, sigma, a );\n\n fprintf( 1, ' %8.1f %8.1f %8.1f %8.1f %14g %14g\\n', x, mu, sigma, a, cdf1, cdf2 );\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/truncated_normal/truncated_normal_a_cdf_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727028, "lm_q2_score": 0.8267118004748678, "lm_q1q2_score": 0.6993505826017812}} {"text": "function x = spgrid(n,d,options)\n% SPGRID Compute the sparse grid point coordinates\n% X = SPGRID(N,D) Computes the sparse grid points of level N\n% and problem dimension D. The coordinate value of dimension i\n% is stored in column i of the matrix X. One row of matrix X\n% represents one grid point.\n%\n% X = SPGRID(N, D, OPTIONS) computes the sparse grid points as\n% above, but with default grid type replaced by the grid type\n% specified in OPTIONS, an argument created with the SPSET\n% function. See SPSET for details.\n%\n% See also SPINTERP, SPVALS, SPDIM.\n\t\n% Author : Andreas Klimke\n% Version: 1.3\n% Date : November 18, 2007\n\n% Change log:\n% V1.0 : September 24, 2003\n% Initial version\n% V1.1 : April 20, 2004\n% Compute sequence of levels here instead of in spgridxx\n% subroutine. \n% V1.2 : June 15, 2004\n% Added new grid type : Chebyshev distributed nodes\n% (at the extrema of the Chebyshev polynomials)\n% V1.3 : November 18, 2007\n% Added new grid type : Gauss-Patterson\n\n% ------------------------------------------------------------\n% Sparse Grid Interpolation Toolbox\n% Copyright (c) 2006 W. Andreas Klimke, Universitaet Stuttgart \n% Copyright (c) 2007-2008 W. A. Klimke. All Rights Reserved.\n% See LICENSE.txt for license. \n% email: klimkeas@ians.uni-stuttgart.de\n% web : http://www.ians.uni-stuttgart.de/spinterp\n% ------------------------------------------------------------\n\t\nif nargin < 3, options = []; end\nif nargin < 2, d = []; end\n\ngridtype = spget(options, 'GridType', 'Clenshaw-Curtis');\nsparseIndices = spget(options, 'SparseIndices', 'auto');\noptions = spset(options, 'SparseIndices', sparseIndices);\n\nswitch lower(gridtype)\n case 'clenshaw-curtis'\n\tif strcmpi(sparseIndices, 'off')\n\t\tgridgen = 'spgridcc';\n\telse\n\t\tgridgen = 'spgridccsp';\n\tend\n case 'maximum'\n\tgridgen = 'spgridm';\n case 'noboundary'\n\tgridgen = 'spgridnb';\n case 'chebyshev'\n\tif strcmpi(sparseIndices, 'off')\n\t\tgridgen = 'spgridcb';\n\telse\n\t\tgridgen = 'spgridcbsp';\n\tend\n case 'gauss-patterson'\n\tif strcmpi(sparseIndices, 'off')\n\t\tgridgen = 'spgridgp';\n\telse\n\t\tgridgen = 'spgridgpsp';\n\tend\n otherwise\n\terror('MATLAB:spinterp:badopt',['Unknown grid type ''' gridtype '''.']);\nend\n\n% Get the sequence of levels\nif ~isempty(d)\n\tlevelseq = spgetseq(n,d,options);\nelse\n\t% For internal usage: pass sequence of levels directly.\n\tlevelseq = n;\nend\n\nx = feval(gridgen, levelseq);\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/spinterp/spgrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.699350582601781}} {"text": "function upsilon = lfmjpComputeUpsilonMatrix(gamma, sigma2, t1, t2, mode)\n\n% LFMJPCOMPUTEUPSILONMATRIX Upsilon matrix jolt. pos. with t1, t2 limits\n% FORMAT\n% DESC computes a portion of the LFMJ kernel.\n% ARG gamma : Gamma value for system.\n% ARG sigma2 : length scale of latent process.\n% ARG t1 : first time input (number of time points x 1).\n% ARG t2 : second time input (number of time points x 1).\n% ARG mode : operation mode, according to the derivative (mode 0,\n% derivative wrt t1, mode 1 derivative wrt t2)\n% RETURN upsilon : result of this subcomponent of the kernel for the given values.\n%\n% COPYRIGHT : Mauricio Alvarez, 2010\n%\n% SEEALSO : lfmComputeUpsilonMatrix.F, lfmComputeH3.m\n\n% KERN\n\nsigma = sqrt(sigma2);\ngridt1 = repmat(t1, 1, length(t2));\ngridt2 = repmat(t2', length(t1), 1);\ntimeGrid = gridt1 - gridt2;\n\nif mode ==0\n upsilon = gamma^2*lfmvpComputeUpsilonMatrix(gamma, sigma2, t1, t2, 0) ...\n + (4/(sqrt(pi)*sigma^3))*exp(-(timeGrid.^2)./sigma2).*...\n (timeGrid.*(gamma + 2*timeGrid/sigma2) - 1);\nelse\n upsilon = gamma^2*lfmvpComputeUpsilonMatrix(gamma, sigma2, t1, t2, 1) ...\n - (4/(sqrt(pi)*sigma^3))*exp(-(timeGrid.^2)./sigma2).*...\n (timeGrid.*(gamma + 2*timeGrid/sigma2) - 1) ...\n - (4/(sqrt(pi)*sigma^3))*exp(-gamma*t1)*((t2.*(gamma - 2*t2/sigma2) + 1).*...\n exp(-(t2.^2)/sigma2)).';\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/lfmjpComputeUpsilonMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6992823463800569}} {"text": "\n\nfunction [pos,vel,acc]=parabolicblend(t,tb,omega,thetai,thetaf)\n\ntoffset=t(1);\nt=t-toffset;\n\ntbefore=find(t Y = Y(-1)*F' + u\n\n% Note: compared to Eviews, there is a difference in the estimation of the \n% constant when lag is > 2. This is because Eviews initialize the trend\n% with the number of lags (i.e., when lag=2, the trend is [2 3 ...T]), \n% while VARmakexy.m initialize the trend always with 1.\n\n% I thank Jan Capek for spotting and addressing a compatibility issue with\n% Matlab R2014a\n\n\n%% Check inputs\n%===============================================\n[nobs, nvar] = size(ENDO);\n\n% Create VARopt and update it\nVARopt = VARoption;\nVAR.ENDO = ENDO;\nVAR.nlag = nlag;\n\n% Check if ther are constant, trend, both, or none\nif ~exist('const','var')\n const = 1;\nend\nVAR.const = const;\n\n% Check if there are exogenous variables \nif exist('EXOG','var')\n [nobs2, nvar_ex] = size(EXOG);\n % Check that ENDO and EXOG are conformable\n if (nobs2 ~= nobs)\n error('var: nobs in EXOG-matrix not the same as y-matrix');\n end\n clear nobs2\n % Check if there is lag order of EXOG, otherwise set it to 0\n if ~exist('nlag_ex','var')\n nlag_ex = 0;\n end\n VAR.EXOG = EXOG;\nelse\n nvar_ex = 0;\n nlag_ex = 0;\n VAR.EXOG = [];\nend\n\n\n%% Save some parameters and create data matrices\n%===============================================\n nobse = nobs - max(nlag,nlag_ex);\n VAR.nobs = nobse;\n VAR.nvar = nvar;\n VAR.nvar_ex = nvar_ex; \n VAR.nlag = nlag;\n VAR.nlag_ex = nlag_ex;\n ncoeff = nvar*nlag; \n VAR.ncoeff = ncoeff;\n ncoeff_ex = nvar_ex*(nlag_ex+1);\n ntotcoeff = ncoeff + ncoeff_ex + const;\n VAR.ntotcoeff = ntotcoeff;\n VAR.const = const;\n\n% Create independent vector and lagged dependent matrix\n[Y, X] = VARmakexy(ENDO,nlag,const);\n\n% Create (lagged) exogeanous matrix\nif nvar_ex>0\n X_EX = VARmakelags(EXOG,nlag_ex);\n if nlag == nlag_ex\n X = [X X_EX];\n elseif nlag > nlag_ex\n diff = nlag - nlag_ex;\n X_EX = X_EX(diff+1:end,:);\n X = [X X_EX];\n elseif nlag < nlag_ex\n diff = nlag_ex - nlag;\n Y = Y(diff+1:end,:);\n X = [X(diff+1:end,:) X_EX];\n end\nend\n\n\n%% OLS estimation equation by equation\n%===============================================\n\nfor j=1:nvar;\n Yvec = Y(:,j);\n OLSout = OLSmodel(Yvec,X,0);\n aux = ['eq' num2str(j)];\n eval( ['VAR.' aux '.beta = OLSout.beta;'] ); % bhats\n eval( ['VAR.' aux '.tstat = OLSout.tstat;'] ); % t-stats\n % compute t-probs\n tstat = zeros(ncoeff,1);\n tstat = OLSout.tstat;\n tout = tdis_prb(tstat,nobse-ncoeff);\n eval( ['VAR.' aux '.tprob = tout;'] ); % t-probs\n eval( ['VAR.' aux '.resid = OLSout.resid;'] );% resids \n eval( ['VAR.' aux '.yhat = OLSout.yhat;'] ); % yhats\n eval( ['VAR.' aux '.y = Yvec;'] ); % actual y\n eval( ['VAR.' aux '.rsqr = OLSout.rsqr;'] ); % r-squared\n eval( ['VAR.' aux '.rbar = OLSout.rbar;'] ); % r-adjusted\n eval( ['VAR.' aux '.sige = OLSout.sige;'] ); % standard error\nend \n\n\n%% Compute the matrix of coefficients & VCV\n%===============================================\nFt = (X'*X)\\(X'*Y);\nVAR.Ft = Ft;\nSIGMA = (1/(nobse-ntotcoeff))*(Y-X*Ft)'*(Y-X*Ft); % adjusted for # of estimated coeff per equation\nVAR.sigma = SIGMA;\nVAR.residuals = Y - X*Ft;\nVAR.X = X;\nVAR.Y = Y;\nif nvar_ex > 0\n VAR.X_EX = X_EX;\nend\n\n\n%% Companion matrix of Ft' and max eigenvalue\n%===============================================\nF = Ft';\nFcomp = [F(:,1+const:nvar*nlag+const); eye(nvar*(nlag-1)) zeros(nvar*(nlag-1),nvar)];\nVAR.Fcomp = Fcomp;\nVAR.maxEig = max(abs(eig(Fcomp)));\n\n%% Initialize other results\n%===============================================\nVAR.invA = []; % inverse of teh A matrix (need identification: see VARir/VARfevd)\nVAR.S = []; % Orthonormal matrix (need identification: see SR)\n\n\n", "meta": {"author": "ambropo", "repo": "VAR-Toolbox", "sha": "9fe5d763da307cdded2827851325766b3a7c60e1", "save_path": "github-repos/MATLAB/ambropo-VAR-Toolbox", "path": "github-repos/MATLAB/ambropo-VAR-Toolbox/VAR-Toolbox-9fe5d763da307cdded2827851325766b3a7c60e1/OldVersions/v2dot0/VAR/VARmodel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.6992409023789954}} {"text": "classdef KalmanPredictorX < PredictorX \n% KalmanPredictorX class\n%\n% Summary of KalmanPredictorX:\n% This is a class implementation of a standard Kalman Predictor.\n%\n% KalmanPredictorX Methods:\n% + KalmanPredictorX - Constructor method\n% + predict - Performs full KF prediction step (both state and measurement)\n% + predictState - Performs KF state prediction step\n% + predictMeasurement - Preforms KF measurement prediction step\n%\n% (+) denotes puplic properties/methods\n% \n% See also DynamicModelX, ObservationModelX and ControlModelX template classes\n \n methods (Static)\n \n function [xPred, PPred, yPred, S, Pxy] = predict(x,P,F,Q,H,R,u,B,O)\n % predict Perform the discrete-time KF state and measurement\n % prediction steps, under the assumption of additive process noise.\n %\n % Parameters\n % ----------\n % x: column vector\n % The (xDim x 1) state estimate at the previous time-step.\n % P: matrix \n % The (xDim x xDim) state covariance matrix at the previous\n % time-step.\n % F: matrix\n % An (xDim x xDim) state transition matrix.\n % Q: matrix\n % The (xDim x xDim) process noise covariance matrix.\n % H: matrix\n % A (xDim x yDim) measurement matrix.\n % R: matrix \n % The (yDim x yDim) measurement noise covariance matrix.\n % u: column vector, optional\n % A optional (xDim x 1) control input.\n % If omitted, no control input is used.\n % B: matrix, optional\n % An optional (xDim x xDim) control gain matrix.\n % If omitted, B is assumed to be 1.\n % O: matrix, optional\n % An optional (xDim x xDim) control noise covariance\n % matrix. If omitted, Q is assumed to be 0.\n %\n % Returns\n % -------\n % xPred: column vector\n % The (xDim x 1) predicted state estimate.\n % PPred: matrix\n % The (xDim x xDim) predicted state covariance matrix.\n % yPred: column vector\n % The (yDim x 1) predicted measurement estimate.\n % Pxy: matrix\n % The (xDim x yDim) cross-covariance matrix.\n % S: matrix\n % The (yDim x yDim) innovation covariance matrix.\n %\n %October 2017 Lyudmil Vladimirov, University of Liverpool.\n\n switch(nargin)\n case(6) \n u = 0;\n B = 0;\n O = 0;\n case(7)\n B = 1;\n O = 0;\n case(8)\n O = 0;\n end\n\n [xPred, PPred] = KalmanPredictorX.predictState(x,P,F,Q,u,B,O);\n [yPred, S, Pxy] = KalmanPredictorX.predictMeasurement(xPred,PPred,H,R);\n end\n \n function [xPred, PPred] = predictState(x,P,F,Q,u,B,Qu)\n % predictState Perform the discrete-time KF state prediction \n % step, under the assumption of additive process noise.\n %\n % Parameters\n % ----------\n % x: column vector\n % The (xDim x 1) state estimate at the previous time-step.\n % P: matrix\n % The (xDim x xDim) state covariance matrix at the previous\n % time-step.\n % F: matrix\n % An (xDim x xDim) state transition matrix.\n % Q: matrix\n % The (xDim x xDim) process noise covariance matrix.\n % u: column vector, optional\n % An optional (xDim x 1) control input.\n % If omitted, no control input is used.\n % B: matrix, optional\n % An optional (xDim x xDim) control gain matrix.\n % If omitted, B is assumed to be 1.\n % O: matrix, optional\n % An optional (xDim x xDim) control noise covariance\n % matrix. If omitted, Q is assumed to be 0.\n %\n % Returns\n % -------\n % xPred: column vector\n % The (xDim x 1) predicted state estimate.\n % PPred: matrix\n % The (xDim x xDim) predicted state covariance matrix.\n %\n %October 2017 Lyudmil Vladimirov, University of Liverpool.\n\n switch(nargin)\n case(4) \n u = 0;\n B = 0;\n Qu = 0;\n case(5)\n B = 1;\n Qu = 0;\n case(6)\n Qu = 0;\n end\n\n % Compute predicted state mean and covariance\n xPred = F*x + B*u;\n PPred =F*P*F' + Q + B*Qu*B';\n end\n\n function [yPred, S, Pxy] = predictMeasurement(xPred,PPred,H,R)\n % predictMeasurement Perform the discrete-time KF observation prediction \n % step, under the assumption of additive process noise.\n %\n % Parameters\n % ----------\n % xPred: column vector\n % The (xDim x 1) predicted state estimate at the current\n % time-step.\n % PPred: matrix\n % The (xDim x xDim) predicted state covariance matrix at \n % the current time-step.\n % H: matrix\n % An (xDim x yDim) measurement matrix.\n % R: matrix\n % The (yDim x yDim) measurement noise covariance matrix.\n %\n % Returns\n % -------\n % yPred: column vector\n % The (yDim x 1) predicted measurement estimate.\n % Pxy: matrix\n % The (xDim x yDim) cross-covariance matrix.\n % S: matrix\n % The (yDim x yDim) innovation covariance matrix.\n %\n %October 2017 Lyudmil Vladimirov, University of Liverpool.\n\n % Compute predicted measurement mean and covariance\n yPred = H*xPred;\n Pxy = PPred*H'; \n S = H*PPred*H' + R;\n end\n end\nend", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/Predictors/KalmanPredictorX/KalmanPredictorX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308036221031, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6992210688634735}} {"text": "close all; clear all;\n\n%% Setting of the problem\nglobal s\ns = 0.3;\nmaxIt = 4;\npde = fonedata;\npde.s = s;\npde.L = 1;\noption.solver = 'direct';\n% option.solver = 'amg';\noption.gNquadorder = 4;\n[node,elem] = squaremesh([-1,1,-1,1],2);\n% [node,elem] = delmesh(node,elem,'x>0 & y<0');\n\n%% Finite element approximation\nN = zeros(maxIt,1);\nenergy = zeros(maxIt,1);\nfor k = 1:maxIt\n [node,elem] = uniformrefine(node,elem);\n tic;\n [uh,eqn] = fracLapP1P1(node,elem,pde,option);\n Nv = size(node,1);\n figure(1); showresult(node,elem,uh(1:Nv)); \n pause(0.1) \n N(k) = length(uh);\n energy(k) = (uh'*eqn.A*uh)/2 - sum(eqn.b(1:Nv).*uh(1:Nv));\n fprintf('#Dof %d ',N(k)); \n toc;\nend\n[node,elem] = uniformrefine(node,elem); \ntic;\n[uh,eqn,info] = fracLapP1P1(node,elem,pde,option);\ntoc;\ndisplay(length(uh));\nfineEnergy = (uh'*eqn.A*uh)/2 - sum(eqn.b.*uh);\n\n%% Plot convergence rates\nenergyError = sqrt(2*(energy(1:k)-fineEnergy));\nfigure(2)\nshowrate(N(1:k),energyError(1:k),1,'r-*','Energy Error');\n\n%% Display error\ncolname = {' #Dof sqrt(2*(E(uh)-E(u)))'};\ndisptable(colname,N,[],energyError,'%0.5e')", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/fracLaplacian/femratefracLapP1P1Lshape.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6991940343651217}} {"text": "function window_sz = get_search_window_test( target_sz, im_sz)\n% GET_SEARCH_WINDOW\n\n% if(target_sz(1)/target_sz(2) > 2)\n% % For objects with large height, we restrict the search window with padding.height\n% window_sz = floor(target_sz.*[1+padding.height, 1+padding.generic]);\n% \n% elseif(prod(target_sz)/prod(im_sz(1:2)) > 0.05)\n% % For objects with large height and width and accounting for at least 10 percent of the whole image,\n% % we only search 2x height and width\n% window_sz=floor(target_sz*(1+padding.large));\n% \n% else\n% %otherwise, we use the padding configuration\n% window_sz = floor(target_sz * (1 + padding.generic));\n\nratio=target_sz(1)/target_sz(2);\nif ratio>1 \n window_sz=round(target_sz.*[2,2*ratio]);\nelse\n window_sz=round(target_sz.*[2/ratio,2]);\nend\n% \n% %window_sz=round(target_sz.*[5,9]);\nwindow_sz=window_sz-mod(window_sz,2)+1;\n\nend\n\n", "meta": {"author": "ybsong00", "repo": "CREST-Release", "sha": "e331e6763e6b683b1696e1d61420e902bfce4ef7", "save_path": "github-repos/MATLAB/ybsong00-CREST-Release", "path": "github-repos/MATLAB/ybsong00-CREST-Release/CREST-Release-e331e6763e6b683b1696e1d61420e902bfce4ef7/CREST/get_search_window_scale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6991940282746012}} {"text": "function Js = JacobianSpace_sym(Slist, thetalist)\n% *** CHAPTER 5: VELOCITY KINEMATICS AND STATICS ***\n% Takes Slist: The joint screw axes in the space frame when the manipulator\n% is at the home position, in the format of a matrix with the\n% screw axes as the columns,\n% thetalist: A list of joint coordinates. \n% Returns the corresponding space Jacobian (6xn real numbers).\n% Example Input:\n% \n% clear; clc;\n% Slist = [[0; 0; 1; 0; 0.2; 0.2], ...\n% [1; 0; 0; 2; 0; 3], ...\n% [0; 1; 0; 0; 2; 1], ...\n% [1; 0; 0; 0.2; 0.3; 0.4]];\n% thetalist = [0.2; 1.1; 0.1; 1.2];\n% Js = JacobianSpace(Slist, thetalist)\n% \n% Output:\n% Js =\n% 0 0.9801 -0.0901 0.9575\n% 0 0.1987 0.4446 0.2849\n% 1.0000 0 0.8912 -0.0453\n% 0 1.9522 -2.2164 -0.5116\n% 0.2000 0.4365 -2.4371 2.7754\n% 0.2000 2.9603 3.2357 2.2251\n\nJs = sym(Slist);\nT = eye(4);\nfor i = 2: length(thetalist)\n T = T * simplify(MatrixExp6_sym(VecTose3(Slist(:, i - 1)),thetalist(i - 1)));\n\tJs(:, i) = Adjoint(T) * Slist(:, i);\nend\nend", "meta": {"author": "ShuoYangRobotics", "repo": "QuadrupedSim", "sha": "8427715395b63bddb77329e66f7484e529998445", "save_path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim", "path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim/QuadrupedSim-8427715395b63bddb77329e66f7484e529998445/mr/JacobianSpace_sym.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6991597585781709}} {"text": "function szmM = calcSZM(quantizedM, nL, szmType)\n% function szmM = calcSZM(quantizedM, nL, szmType)\n%\n% This function calculates the Size-Zone matrix for the passed quantized\n% image.\n%\n% INPUTS:\n% quantizedM: quantized 3d matrix obtained, for example, by\n% imquantize_cerr.m\n% nL: Number of gray levels.\n% szmType: flag, 1 or 2.\n% 1: 3D zones\n% 2: 2D zones\n% OUTPUT:\n% szmM: size-zone matrix of size (nL x L)\n%\n% EXAMPLE:\n%\n% numRows = 10;\n% numCols = 10;\n% numSlcs = 1;\n% \n% % number of gray levels\n% nL = 3;\n% \n% % create an image with random numbers\n% imgM = randi(nL,numRows,numCols,numSlcs);\n% \n% % set option to add run lengths from all directions\n% szmType = 1;\n% \n% % call the rlm calculator\n% szmType = calcSZM(imgM, nL, szmType);\n%\n%\n% APA, 03/30/2017\n\nif szmType == 1\n numNeighbors = 26;\nelse\n numNeighbors = 8;\nend\n\nszmM = sparse(nL,numel(quantizedM));\nmaxSiz = 0;\nfor level = 1:nL\n connM = bwlabeln(quantizedM==level, numNeighbors);\n if any(connM(:))\n regiosSizV = accumarray(connM(connM > 0),1);\n if ~isempty(regiosSizV)\n maxSiz = max(maxSiz,max(regiosSizV));\n end\n szmM(level,:) = accumarray(regiosSizV,1,[size(szmM,2) 1])';\n end\nend\nszmM = szmM(:,1:maxSiz);\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/heterogenity_metrics/calcSZM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6991597542144729}} {"text": "function [k, sk, n2] = rbfperiodicKernCompute(kern, x, x2)\n\n% RBFPERIODICKERNCOMPUTE Compute the RBFPERIODIC kernel given the parameters and X.\n% FORMAT\n% DESC computes the kernel parameters for the RBF derived periodic\n% kernel given inputs associated with rows and columns.\n% ARG kern : the kernel structure for which the matrix is computed.\n% ARG x : the input matrix associated with the rows of the kernel.\n% ARG x2 : the input matrix associated with the columns of the kernel.\n% RETURN k : the kernel matrix computed at the given points.\n%\n% FORMAT\n% DESC computes the kernel matrix for the RBF derived periodic\n% kernel given a design matrix of inputs.\n% ARG kern : the kernel structure for which the matrix is computed.\n% ARG x : input data matrix in the form of a design matrix.\n% RETURN k : the kernel matrix computed at the given points.\n%\n% SEEALSO : rbfperiodicKernParamInit, kernCompute, kernCreate, rbfperiodicKernDiagCompute\n%\n% COPYRIGHT : Neil D. Lawrence, 2007, 2009\n\n% KERN\nif isfield(kern, 'period')\n factor = 2*pi/kern.period;\nelse\n factor = 1;\nend\nif nargin < 3\n n2 = sin(0.5*factor*(repmat(x, 1, size(x, 1)) - repmat(x', size(x, 1), 1)));\n n2 = n2.*n2;\n wi2 = (2 .* kern.inverseWidth);\n sk = exp(-n2*wi2);\nelse\n n2 = sin(0.5*factor*(repmat(x, 1, size(x2, 1)) - repmat(x2', size(x, 1), 1))); \n n2 = n2.*n2;\n wi2 = (2 .* kern.inverseWidth);\n sk = exp(-n2*wi2);\nend\nk = kern.variance*sk;\n \n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/rbfperiodicKernCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6991597541320362}} {"text": "function fd1d_advection_ftcs ( )\n\n%*****************************************************************************80\n%\n%% FD1D_ADVECTION_FTCS solves the advection equation using the FTCS method.\n%\n% Discussion:\n%\n% The FTCS method is unstable for the advection problem.\n%\n% Given a smooth initial condition, successive FTCS approximations will\n% exhibit erroneous oscillations of increasing magnitude.\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 timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FD1D_ADVECTION_FTCS:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Solve the constant-velocity advection equation in 1D,\\n' );\n fprintf ( 1, ' du/dt = - c du/dx\\n' );\n fprintf ( 1, ' over the interval:\\n' );\n fprintf ( 1, ' 0.0 <= x <= 1.0\\n' );\n fprintf ( 1, ' with periodic boundary conditions, and\\n' );\n fprintf ( 1, ' with a given initial condition\\n' );\n fprintf ( 1, ' u(0,x) = (10x-4)^2 (6-10x)^2 for 0.4 <= x <= 0.6\\n' );\n fprintf ( 1, ' = 0 elsewhere.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' We use a method known as FTCS:\\n' );\n fprintf ( 1, ' FT: Forward Time : du/dt = (u(t+dt,x)-u(t,x))/dt\\n' );\n fprintf ( 1, ' CS: Centered Space: du/dx = (u(t,x+dx)-u(t,x-dx))/2/dx\\n' );\n\n nx = 101;\n dx = 1.0 / ( nx - 1 );\n x = linspace ( 0.0, 1.0, nx );\n nt = 1000;\n dt = 1.0 / nt;\n c = 1.0;\n\n u = zeros ( 1, nx );\n i = find ( 0.4 <= x & x <= 0.6 );\n u(i) = ( 10.0 * x(i) - 4.0 ).^2 .* ( 6.0 - 10.0 * x(i) ).^2;\n\n iplot = 1;\n uplot(iplot,:) = u(:)';\n tplot(iplot) = 0.0;\n plotstep = ceil ( nt / 50 );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of nodes NX = %d\\n', nx );\n fprintf ( 1, ' Number of time steps NT = %d\\n', nt );\n fprintf ( 1, ' Constant velocity C = %g\\n', c );\n\n im1 = [ nx, 1:nx-2, nx-1 ];\n i = [ 1, 2:nx-1, nx ];\n ip1 = [ 2, 3:nx, 1 ];\n\n for j = 1 : nt\n\n unew(i) = u(i) - c * dt / dx / 2.0 * ( u(ip1) - u(im1) );\n u(i) = unew(i);\n\n if ( rem ( j, plotstep ) < 1 )\n iplot = iplot + 1;\n uplot(iplot,:) = u(:)';\n tplot(iplot) = j * dt;\n end\n\n end\n%\n% Plot.\n%\n mesh ( x, tplot, uplot );\n xlabel ( '<--X-->' );\n ylabel ( '<--T-->');\n title ( 'U(X,T)');\n\n filename = 'fd1d_advection_ftcs.png';\n print ( '-dpng', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Saving plot as \"%s\".\\n', filename );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FD1D_ADVECTION_FTCS\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\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/fd1d_advection_ftcs/fd1d_advection_ftcs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.6991591982744857}} {"text": "function [q num den]= get_q_RANSAC(N, N_I, k)\n\n% [q num den] = get_q_RANSAC(N, N_I, k)\n%\n% DESC:\n% calculates the probability q \n%\n% AUTHOR\n% Marco Zuliani - marco.zuliani@gmail.com\n%\n% VERSION:\n% 1.0\n%\n% INPUT:\n% N = number of elements\n% N_I = number of inliers\n% k = cardinality of the MSS\n%\n% OUTPUT:\n% q = probability\n% num, den = q = num / den\n\nif (k > N_I)\n error('k should be less or equal than N_I')\nend;\n\nif (N == N_I)\n q = 1;\n return;\nend;\n\nnum = N_I:-1:N_I-k+1;\nden = N:-1:N-k+1;\nq = prod(num./den);\n\nreturn\n", "meta": {"author": "RANSAC", "repo": "RANSAC-Toolbox", "sha": "c08308bf61aaf669b00533409cb0daaa10c000aa", "save_path": "github-repos/MATLAB/RANSAC-RANSAC-Toolbox", "path": "github-repos/MATLAB/RANSAC-RANSAC-Toolbox/RANSAC-Toolbox-c08308bf61aaf669b00533409cb0daaa10c000aa/Common/get_q_RANSAC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.6991557044319766}} {"text": "classdef ImplicitEquationSolver < handle\n \n properties (Access = public)\n xsol\n end\n \n properties (Access = private)\n x0\n functionToSolve\n end\n \n methods (Access = public)\n \n function obj = ImplicitEquationSolver(cParams)\n obj.init(cParams)\n end\n \n function r = solve(obj)\n F = obj.functionToSolve;\n [rub,rlb] = obj.findRbounds(F);\n r = fzero(F,[rlb,rub]);\n end\n \n end\n \n methods (Access = private)\n \n function init(obj,cParams)\n obj.x0 = cParams.x0;\n obj.functionToSolve = cParams.functionToSolve;\n end \n \n function [rub,rlb] = findRbounds(obj,F)\n r0 = 1;\n F0 = F(r0);\n eps = 10^(-6);\n if F0 >= 0\n r1 = 1 + eps;\n F1 = F(r1);\n while F1 >= 0\n rnew = obj.newPointBySecant(r0,r1,F0,F1);\n r0 = r1;\n F0 = F1;\n r1 = rnew;\n F1 = F(r1);\n end\n rub = r1;\n rlb = r0;\n else\n r0 = 1;\n r1 = 1 - eps;\n F1 = F(r1);\n while F1 <= 0\n rnew = obj.newPointBySecant(r0,r1,F0,F1);\n r0 = r1;\n F0 = F1;\n r1 = max(1e-12,rnew);\n F1 = F(r1);\n end\n rub = r0;\n rlb = r1;\n end\n end\n \n end\n \n methods (Access = private, Static)\n \n function x2 = newPointBySecant(x0,x1,f0,f1)\n x2 = x1 - (x1-x0)/(f1 - f0)*f1;\n end\n \n end\n \nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Vigdergauz/ImplicitEquationSolver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.6991557044319766}} {"text": "% Exact solution of Riemann problem\n\n% Theory in Section 10.2 of:\n\n% \tP. Wesseling: Principles of Computational Fluid Dynamics\n% \tSpringer, Heidelberg, 2000 ISBN 3-5453-0. XII, 642 pp.\n% See http://ta.twi.tudelft.nl/nw/users/wesseling/cfdbook.html\n\n% This program is called by Euler schemes\n\n% Functions called: f\n\nglobal PRL CRL MACHLEFT gamma pleft pright rholeft rhoright uleft...\n\turight tend lambda\t\t% lambda = dt/dx\n\t\ngammab = 1/(gamma - 1); gam1 = gamma-1;\n\n% Assumed structure of exact solution\n%\n% \\ / |con | |s|\n% \\ f / |tact| |h|\n% left \\ a / state |disc| state |o| right\n% state \\ n / 2 |cont| 3 |c| state\n% 1 \\ / |tinu| |k| 4\n% | |ity | | |\n\nPRL = pright/pleft;\ncright = sqrt(gamma*pright/rhoright); cleft = sqrt(gamma*pleft/rholeft);\nCRL = cright/cleft;\nMACHLEFT = (uleft - uright)/cleft;\n\np34 = fzero('f',3);\t\t% p34 = p3/p4\np3 = p34*pright; \talpha = (gamma+1)/(gamma-1);\nrho3 = rhoright*(1+alpha*p34)/(alpha+p34); \nrho2 = rholeft*(p34*pright/pleft)^(1/gamma);\nu2 = uleft-uright+(2/(gamma-1))*cleft*...\n\t(1-(p34*pright/pleft)^((gamma-1)/(2*gamma)));\nc2 = sqrt(gamma*p3/rho2);\nspos = 0.5 + ...\t\t% Shock position\n\ttend*cright*sqrt((gamma-1)/(2*gamma) + (gamma+1)/(2*gamma)*p34)+...\n\ttend*uright;\n\nconpos = 0.5 + u2*tend + tend*uright;\t% Position of contact discontinuity \npos1 = 0.5 + (uleft - cleft)*tend;\t% Start of expansion fan\npos2 = 0.5 + (u2+uright-c2)*tend;\t% End of expansion fan\nxx = 0:0.002:1;\npexact = zeros(size(xx)); uexact= zeros(size(xx)); rhoexact = zeros(size(xx));\nmachexact = zeros(size(xx)); cexact = zeros(size(xx));\nfor i = 1:length(xx)\n if xx(i) <= pos1\n pexact(i) = pleft; rhoexact(i) = rholeft;\n uexact(i) = uleft; cexact(i) = sqrt(gamma*pexact(i)/rhoexact(i));\n machexact(i) = uexact(i)/cexact(i);\n elseif xx(i) <= pos2\n pexact(i) = pleft*(1+(pos1-xx(i))/(cleft*alpha*tend))^(2*gamma/(gamma-1));\n rhoexact(i) = rholeft*(1+(pos1-xx(i))/(cleft*alpha*tend))^(2/(gamma-1));\n uexact(i) = uleft + (2/(gamma+1))*(xx(i)-pos1)/tend;\n cexact(i) = sqrt(gamma*pexact(i)/rhoexact(i));\n machexact(i) = uexact(i)/cexact(i);\n elseif xx(i) <= conpos\n pexact(i) = p3; \t rhoexact(i) = rho2;\n uexact(i) = u2+uright; cexact(i) = sqrt(gamma*pexact(i)/rhoexact(i));\n machexact(i) = uexact(i)/cexact(i);\n elseif xx(i) <= spos\n pexact(i) = p3; rhoexact(i) = rho3; uexact(i) = u2+uright; \n cexact(i) = sqrt(gamma*pexact(i)/rhoexact(i));\n machexact(i) = uexact(i)/cexact(i);\n else\n pexact(i) = pright; rhoexact(i) = rhoright;\n uexact(i) = uright; cexact(i) = sqrt(gamma*pexact(i)/rhoexact(i));\n machexact(i) = uexact(i)/cexact(i);\n end\nend\nentroexact = log(pexact./rhoexact.^gamma);\n\nsubplot(2,3,1), \tplot(xx,rhoexact)\nsubplot(2,3,2), \tplot(xx,uexact)\nsubplot(2,3,3), \tplot(xx,pexact)\nsubplot(2,3,4), \tplot(xx,machexact)\nsubplot(2,3,5), \tplot(xx,entroexact)\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/cfdbook/chap10.8/Riemann.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6991556997618654}} {"text": "% h = drawfly(trk,varargin)\n% h = drawfly(x,y,theta,quartermaj,quartermin,varargin)\n% draw triangle corresponding to fly position\n% extra arguments will be fed to patch\nfunction varargout = drawfly(x,y,varargin)\n\n% draw an isosceles triangle with center (x,y)\n% with rotation theta\n% with height maj*4\n% with base min*4\n\nif isstruct(x),\n fly = x;\n t = y;\n x = fly.x(t);\n y = fly.y(t);\n theta = fly.theta(t);\n maj = fly.a(t);\n min = fly.b(t); \nelse\n if nargin < 5,\n error('not enough arguments; usage: drawflyo(x,y,theta,a,b,...)');\n end\n theta = varargin{1};\n maj = varargin{2};\n min = varargin{3};\n varargin = varargin(4:end);\nend\n\n\nif 0,\n\nh = ellipsedraw(maj*2,min*2,x,y,theta);\n\nelse\n\n% isosceles triangle not yet rotated or centered\npts = [-maj*2,-min*2,\n -maj*2,min*2,\n maj*2,0];\n\n% rotate\ncostheta = cos(theta);\nsintheta = sin(theta);\nR = [costheta,sintheta;-sintheta,costheta];\npts = pts*R;\n\n% translate\npts(:,1) = pts(:,1) + x;\npts(:,2) = pts(:,2) + y;\n\n% plot\nif isempty(varargin),\n h = patch(pts([1:3,1],1),pts([1:3,1],2),'b');\nelse\n h = patch(pts([1:3,1],1),pts([1:3,1],2),varargin{:});\nend\n\nend\n\nif nargout > 0,\n varargout{1} = h;\nend;\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/misc/drawfly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6990697165331722}} {"text": "% At_fhp.m\n%\n% Adjoint of At_fhp (2D Fourier half plane measurements).\n%\n% Usage: x = At_fhp(b, OMEGA, n)\n%\n% b - K vector = [mean; real part(OMEGA); imag part(OMEGA)]\n%\n% OMEGA - K/2-1 vector denoting which Fourier coefficients to use\n% (the real and imag parts of each freq are kept).\n%\n% n - Image is nxn pixels\n%\n% x - N vector\n%\n% Written by: Justin Romberg, Caltech\n% Created: October 2005\n% Email: jrom@acm.caltech.edu\n%\n\nfunction x = At_fhp(y, OMEGA, n)\n\nK = length(y);\n\nfx = zeros(n,n);\nfx(1,1) = y(1);\nfx(OMEGA) = sqrt(2)*(y(2:(K+1)/2) + i*y((K+3)/2:K));\nx = reshape(real(n*ifft2(fx)), n*n, 1);\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/NESTA-1.1/Misc/At_fhp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513620489618, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6990696946576572}} {"text": "function x = gpml_randn(seed,varargin)\n\n% Generate pseudo-random numbers in a quick and dirty way.\n% The function makes sure, we obtain the same random numbers using Octave and\n% Matlab for the demo scripts.\n%\n% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch 2010-07-07.\n\nif nargin==2\n sz = varargin{1};\nelse\n sz = zeros(1,nargin-1);\n for i=1:nargin-1\n sz(i) = varargin{i};\n end\nend\n\nn = prod(sz); N = ceil(n/2)*2;\n\n% minimal uniform random number generator for uniform deviates from [0,1]\n% by Park and Miller\na = 7^5; m = 2^31-1; \n% using Schrage's algorithm\nq = fix(m/a); r = mod(m,a); % m = a*q+r\nu = zeros(N+1,1); u(1) = fix(seed*2^31);\nfor i=2:N+1\n % Schrage's algorithm for mod(a*u(i),m)\n u(i) = a*mod(u(i-1),q) - r*fix(u(i-1)/q);\n if u(i)<0, u(i) = u(i)+m; end\nend\nu = u(2:N+1)/2^31;\n\n% Box-Muller transform: Numerical Recipies, 2nd Edition, $7.2.8\n% http://en.wikipedia.org/wiki/Box-Muller_transform \nw = sqrt(- 2*log(u(1:N/2))); % split into two groups\nx = [w.*cos(2*pi*u(N/2+1:N)); w.*sin(2*pi*u(N/2+1:N))]; \nx = reshape(x(1:n),sz);\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/gpml/doc/gpml_randn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6990696900740511}} {"text": "function m_demo(index)\n% M_DEMO Demonstration program showing various maps in M_Map package\n% Dig into this to look for examples of things you want to do.\n%\n% M_DEMO runs all the demos.\n% M_DEMO(NUM) runs examples NUM (1<=NUM<=10), pausing between examples.\n%\n% Some demos may require you to install GSHHS or TerrainBase datafiles\n% (see documentation)\n\n% Rich Pawlowicz (rich@ocgy.ubc.ca) 7/May/1997\n% (thanks to Art Newhall for putting these examples into an m-file,\n% and the Chuck Denham for enhancing the interface)\n%\n% 27/July/98 - more examples.\n% 17/Aug/98 \"\n% 15/Nov/98 - another example, better interface.\n% 23/Dec/98 - another example.\n\n%\n% This software is provided \"as is\" without warranty of any kind. But\n% it's mine, so you can't sell it.\n\nglobal MAP_PROJECTION\n\nN_EXAMPLES=15;\n\nif nargin==0\n index=1:N_EXAMPLES;\nend\n\nfor i=index\n\nclf;\nswitch i\n\n case 1\n\n m_proj('ortho','lat',48','long',-123');\n m_coast('patch','r');\n m_grid('linestyle','-','xticklabels',[],'yticklabels',[],'ytick',[-80:40:80]);\n xlabel('Orthographic Projection','visible','on');\n\n case 2\n\n m_proj('lambert','long',[-160 -40],'lat',[30 80]);\n m_coast('patch',[1 .85 .7]);\n [CS,CH]=m_elev('contourf',[500:500:4000]);\n % m_elev('pcolor');\n m_grid('box','fancy','tickdir','in');\n colormap(flipud(copper));\n xlabel('Conic Projection of North America with elevations','visible','on');\n m_contfbar([0 .3],.9,CS,CH);\n \n case 3\n\n m_proj('stereographic','lat',90,'long',30,'radius',25);\n m_elev('contour',[-3500:1000:-500],'linecolor','b');\n m_grid('xtick',12,'tickdir','out','ytick',[70 80],'linestyle','-');\n m_coast('patch',[.7 .7 .7],'edgecolor','r');\n xlabel('Polar Stereographic Projection with bathymetry','visible','on');\n\n case 4\n \n subplot(211);\n Slongs=[-100 0;-75 25;0 45; 25 145;45 100;145 295;100 295];\n Slats= [ 8 80;-80 8; 8 80;-80 8; 8 80;-80 0; 0 80];\n for l=1:7\n m_proj('sinusoidal','long',Slongs(l,:),'lat',Slats(l,:));\n % colormap(m_colmap('blues'));caxis([-6000 0]);\n % m_elev('shadedrelief');\n m_grid('fontsize',6,'xticklabels',[],'xtick',[-180:30:360],...\n 'ytick',[-80:20:80],'yticklabels',[],'linestyle','-','color',[.9 .9 .9]);\n m_coast('patch','g');\n end\n xlabel('Interrupted Sinusoidal Projection of World Oceans');\n % In order to see all the maps we must undo the axis limits set by m_grid calls:\n set(gca,'xlimmode','auto','ylimmode','auto');\n\n subplot(212);\n Slongs=[-100 43;-75 20; 20 145;43 100;145 295;100 295];\n Slats= [ 0 90;-90 0;-90 0; 0 90;-90 0; 0 90];\n for l=1:6\n m_proj('mollweide','long',Slongs(l,:),'lat',Slats(l,:));\n % colormap(m_colmap('blues'));caxis([-6000 0]);\n % m_elev('shadedrelief');\n m_grid('fontsize',6,'xticklabels',[],'xtick',[-180:30:360],...\n 'ytick',[-80:20:80],'yticklabels',[],'linestyle','-','color','k');\n\n m_coast('patch',[.6 .6 .6]);\n end\n xlabel('Interrupted Mollweide Projection of World Oceans');\n set(gca,'xlimmode','auto','ylimmode','auto');\n\n case 5\n \n %% Nice looking data\n [lon,lat]=meshgrid([-136:2:-114],[36:2:54]);\n u=sin(lat/6);\n v=sin(lon/6);\n\n m_proj('oblique','lat',[56 30],'lon',[-132 -120],'aspect',.8);\n\n subplot(121);\n m_coast('patch',[.9 .9 .9],'edgecolor','none');\n m_grid('tickdir','out','yaxislocation','right',...\n\t 'xaxislocation','top','xlabeldir','end','ticklength',.02);\n hold on;\n m_quiver(lon,lat,u,v);\n xlabel('Simulated surface winds');\n\n subplot(122);\n m_coast('patch',[.9 .9 .9],'edgecolor','none');\n m_grid('tickdir','out','yticklabels',[],...\n\t 'xticklabels',[],'linestyle','none','ticklength',.02);\n hold on;\n [cs,h]=m_contour(lon,lat,sqrt(u.*u+v.*v));\n clabel(cs,h,'fontsize',8);\n xlabel('Simulated something else');\n\n case 6\n \n % Plot a circular orbit\n lon=[-180:180];\n lat=atan(tan(60*pi/180)*cos((lon-30)*pi/180))*180/pi;\n\n m_proj('miller','lat',82);\n m_coast('color',[0 .6 0]);\n m_line(lon,lat,'linewidth',3,'color','r');\n m_grid('linestyle','none','box','fancy','tickdir','out');\n\n\n case 7\n \n m_proj('lambert','lon',[-10 20],'lat',[33 48]);\n if MAP_PROJECTION.IsOctave\n [CS,CH]=m_etopo2('contourf',[-5000:500:0 250:250:3000],'linecolor','none'); \n else\n [CS,CH]=m_etopo2('contourf',[-5000:500:0 250:250:3000],'edgecolor','none');\n end\n m_grid('linestyle','none','tickdir','out','linewidth',3);\n\n colormap([ m_colmap('blues',80); m_colmap('gland',48)]);\n brighten(.5);\n \n ax=m_contfbar(1,[.5 .8],CS,CH);\n title(ax,{'Level/m',''}); % Move up by inserting a blank line\n\n case 8\n \n m_vec;\n colormap(jet);\n \n case 9\n\n % Example showing the default coastline and all of the GSHHS coastlines.\n\n axes('position',[.35 .6 .37 .37]);\n m_proj('albers equal-area','lat',[40 60],'long',[-90 -50],'rect','on');\n m_coast('patch',[0 1 0]);\n m_grid('linestyle','none','linewidth',2,'tickdir','out','xaxisloc','top','yaxisloc','right','fontsize',6);\n m_text(-69,51,'Standard coastline','color','r','fontweight','bold');\n m_ruler([.5 .9],.8,3,'fontsize',8);\n drawnow;\n \n axes('position',[.09 .5 .37 .37]);\n m_proj('albers equal-area','lat',[40 54],'long',[-80 -55],'rect','on');\n m_gshhs_c('patch',[.2 .8 .2]);\n m_grid('linestyle','none','linewidth',2,'tickdir','out','xaxisloc','top','fontsize',6);\n m_text(-80,52.5,'GSHHS\\_C (crude)','color','m','fontweight','bold');\n m_ruler([.5 .9],.8,2,'fontsize',8);\n drawnow;\n \n axes('position',[.13 .2 .37 .37]);\n m_proj('albers equal-area','lat',[43 48],'long',[-67 -58],'rect','on');\n m_gshhs_l('patch',[.4 .6 .4]);\n m_grid('linestyle','none','linewidth',2,'tickdir','out','fontsize',6);\n m_text(-66.5,43.5,'GSHHS\\_L (low)','color','m','fontweight','bold');\n m_ruler([.5 .9],.8,3,'fontsize',8);\n drawnow;\n \n axes('position',[.35 .05 .37 .37]);\n m_proj('albers equal-area','lat',[45.8 47.2],'long',[-64.5 -62],'rect','on');\n m_gshhs_i('patch',[.5 .6 .5]);\n m_grid('linestyle','none','linewidth',2,'tickdir','out','yaxisloc','right','fontsize',6);\n m_text(-64.4,45.9,'GSHHS\\_I (intermediate) ','color','m','fontweight','bold','horizontalalignment','right');\n m_ruler([.5 .8],.1,3,'fontsize',8);\n drawnow;\n \n axes('position',[.5 .1 .37 .37]);\n m_proj('albers equal-area','lat',[46.375 46.6],'long',[-64.2 -63.7],'rect','on');\n m_gshhs_h('patch',[.6 .7 .6]);\n m_grid('linestyle','none','linewidth',2,'tickdir','out','xaxisloc','top','yaxisloc','right','fontsize',6);\n m_text(-64.18,46.4,'GSHHS\\_H (high)','color','m','fontweight','bold');\n m_ruler([.5 .8],.2,3,'fontsize',8);\n drawnow;\n \n axes('position',[.55 .35 .37 .37]);\n m_proj('albers equal-area','lat',[46.55 46.65],'long',[-63.97 -63.77],'rect','on');\n m_gshhs_f('patch',[.7 .9 .7]);\n m_grid('linestyle','none','linewidth',2,'tickdir','out','xaxisloc','top','yaxisloc','right','fontsize',6);\n m_text(-63.95,46.56,'GSHHS\\_F (full)','color','m','fontweight','bold');\n m_ruler([.5 .8],.2,3,'fontsize',8);\n\n case 10\n \n % Example showing a trackline plot\n\n clf\n m_proj('UTM','long',[-72 -68],'lat',[40 44]);\n m_gshhs_i('color','k');\n m_grid('box','fancy','tickdir','in');\n m_ruler(1.2,[.5 .8]);\n \n % fake up a trackline\n lons=[-71:.1:-67];\n lats=60*cos((lons+115)*pi/180);\n dates=datenum(1997,10,23,15,1:41,zeros(1,41));\n\n m_track(lons,lats,dates,'ticks',0,'times',4,'dates',8,...\n 'clip','off','color','r','orient','upright'); \n \n case 11\n \n % example showing range rings\n \n clf\n m_proj('hammer','clong',170);\n m_grid('xtick',[],'ytick',[],'linestyle','-');\n m_coast('patch','g');\n m_line(100.5,13.5,'marker','s','color','r');\n m_range_ring(100.5,13.5,[1000:1000:15000],'color','b','linewidth',2);\n xlabel('1000km range rings from Bangkok');\n \n case 12\n \n % Example showing speckle\n \n bndry_lon=[-128.8 -128.8 -128.3 -128 -126.8 -126.6 -128.8];\n bndry_lat=[49 50.33 50.33 50 49.5 49 49];\n\n clf;\n m_proj('lambert','long',[-130 -121.5],'lat',[47 51]);\n m_gshhs_i('color','k');\n m_gshhs_i('speckle','color','k');\n m_line(bndry_lon,bndry_lat,'linewidth',2,'color','k'); % Area outline ...\n m_hatch(bndry_lon,bndry_lat,'single',30,5,'color','k'); % ...with hatching added.\n\n m_grid('linewidth',2,'linestyle','none');\n title({'Speckled Boundaries','for nice B&W presentation','(best in postscript format)'});\n m_text(-128,48,{'Pacific','Ocean'},'fontsize',18);\n \n case 13\n \n % Colouring the ocean blue\n \n clf\n m_proj('miller','lat',[-77 77]);\n % set(gca,'color',[.9 .99 1]);\n m_coast('patch',[.7 1 .7],'edgecolor','none');\n m_grid('box','fancy','linestyle','-','gridcolor','w','backcolor',[.2 .65 1]);\n \n cities={'Cairo','Washington','Buenos Aires'};\n lons=[ 30+2/60 -77-2/60 -58-22/60];\n lats=[ 31+21/60 38+53/60 -34-45/60];\n \n for k=1:3\n [range,ln,lt]=m_lldist([-123-6/60 lons(k)],[49+13/60 lats(k)],40);\n m_line(ln,lt,'color','r','linewidth',2);\n m_text(ln(end),lt(end),sprintf('%s - %d km',cities{k},round(range)));\n end\n \n % set(gcf,'color','w'); % To defeat the tendency of print to turn white into black\n \n title('Great Circle Routes','fontsize',12,'fontweight','bold');\n \n case 14\n clf\n m_proj('lambert','long',[-130 -122],'lat',[48 52.5],'rect','on');\n if MAP_PROJECTION.IsOctave\n [CS,CH]=m_elev('contourf',[-3000:500:-500 -200 -100 -50 -1 2 20 50 100 250:250:2000],'linecolor','none');\n else\n [CS,CH]=m_etopo2('contourf',[-3000:500:-500 -200 -100 -50 -1 2 20 50 100 250:250:2000],'edgecolor','none');\n end\n \n m_grid('linewi',2,'tickdir','out','yaxisloc','right');\n \n \n if MAP_PROJECTION.IsOctave\n ax=m_contfbar(-.03,[.5 .8],CS,CH,'linecolor','none');\n else\n ax=m_contfbar(-.03,[.5 .8],CS,CH,'edgecolor','none');\n end\n title(ax,{'meters',''}); % Move up by inserting a blank line\n \n colormap([m_colmap('blues',96);m_colmap('gland',64)]); \n caxis([-3000 2000]);\n \n case 15\n clf; \n m_proj('azimuthal equal-area','radius',156,'lat',-46,'long',-95,'rot',30);\n\n ax1=subplot(2,2,1,'align');\n m_coast('patch','r');\n m_grid('xticklabel',[],'yticklabel',[],'linestyle','-','ytick',[-60:30:60]);\n \n ax2=subplot(2,2,2,'align');\n if MAP_PROJECTION.IsOctave\n m_elev('contourf',[-7000:1000:0 500:500:3000],'linecolor','none');\n else\n m_elev('contourf',[-7000:1000:0 500:500:3000],'edgecolor','none');\n end\n colormap(ax2,[m_colmap('blues',70);m_colmap('gland',30)]); \n caxis(ax2,[-7000 3000]); \n m_grid('xticklabel',[],'yticklabel',[],'linestyle','-','ytick',[-60:30:60]);\n\n \n ax3=subplot(2,2,3,'align');\n colormap(ax3,[m_colmap('blues',70);m_colmap('gland',30)]); \n caxis(ax3,[-7000 3000]); \n m_elev('image');\n m_grid('xticklabel',[],'yticklabel',[],'linestyle','-','ytick',[-60:30:60]);\n\n \n ax4=subplot(2,2,4,'align');\n colormap(ax4,[m_colmap('blues')]); \n caxis(ax4,[-8000 000]); \n m_elev('shadedrelief','gradient',.5);\n m_coast('patch',[.7 .7 .7],'edgecolor','none');\n m_grid('xticklabel',[],'yticklabel',[],'linestyle','-','ytick',[-60:30:60]);\n\n ha = axes('Position',[0 0 1 1],'Xlim',[0 1],'Ylim',[0 1],'Box','off','Visible','off','Units','normalized', 'clipping' , 'off');\n text(0.5, 0.98,'This projection shows all oceans connected to each other','horiz','center','fontsize',20);\n \n \nend\n \n if i ballRadius)\n % The problem is infeasible\n vX = mean([vLowerBound, vUpperBound], 2);\n return;\nend\n\n% The dual objective function which should be maximized to find the optimal\n% 'paramLambda'.\n% The functios is negated as we want to maximize while using\n% MATLAB's minimization function\nhObjFun = @(paramLambda) -ObjectiveDualFunction(vY, ballRadius, vLowerBound, vUpperBound, paramLambda); %= 0 and vY(ii) <= 0\n valX = ProjBoxFunction(vY(ii) + paramLambda, vL(ii), 0); %= 0, vL(ii) <= 0 and vY(ii) >= 0\n valX = ProjBoxFunction(vY(ii) - paramLambda, 0, vU(ii)); %sqrt(nMics)-1\n warning('Set order too high for the number of microphones, should be N<=sqrt(Q)-1')\n order_sht = floor( sqrt(nMics)-1 );\nend\nnBins = nFFT/2+1;\nif isempty(w_grid)\n w_grid = ones(nGrid,1);\nend\n\n% SH matrix at grid directions\norder_array = floor(sqrt(nGrid)/2-1);\naziElev2aziPolar = @(dirs) [dirs(:,1) pi/2-dirs(:,2)]; % function to convert from azimuth-inclination to azimuth-elevation\nY_grid = sqrt(4*pi) * getSH(order_array, aziElev2aziPolar(grid_dirs_rad), 'real')'; % SH matrix for grid directions\n\n% compute inverse matrix\na_dB = amp_threshold;\nalpha = 10^(a_dB/20);\nbeta = 1/(2*alpha);\nW_grid = diag(w_grid);\nH_filt = zeros((order_sht+1)^2, nMics, nBins);\n% compute first the SHT of the array response\nfor kk=1:nBins\n tempH = squeeze(H_array(kk,:,:));\n H_nm(kk,:,:) = tempH * W_grid * Y_grid'* inv(Y_grid*W_grid*Y_grid');\nend\n% compute the inverse matrix in the SHD with regularization\nfor kk=1:nBins\n tempH_N = squeeze(H_nm(kk,:,:));\n tempH_N_trunc = tempH_N(:,1:(order_sht+1)^2);\n H_filt(:,:,kk) = tempH_N_trunc' * inv(tempH_N*tempH_N' + beta^2*eye(nMics));\nend\n\nif nargout>1\n % time domain filters\n h_filt = H_filt;\n h_filt(:,:,end) = abs(h_filt(:,:,end));\n h_filt = cat(3, h_filt, conj(h_filt(:,:,end-1:-1:2)));\n h_filt = real(ifft(h_filt, [], 3));\n h_filt = fftshift(h_filt, 3);\nend\n", "meta": {"author": "polarch", "repo": "Spherical-Array-Processing", "sha": "f08bed9b80ce580f9056fd6573ab0c08588ebc11", "save_path": "github-repos/MATLAB/polarch-Spherical-Array-Processing", "path": "github-repos/MATLAB/polarch-Spherical-Array-Processing/Spherical-Array-Processing-f08bed9b80ce580f9056fd6573ab0c08588ebc11/arraySHTfiltersMeas_regLSHD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6989508731671025}} {"text": "function XYZ = quat2cube(q)\n%\n% transforms unit quaternions (representing rotations) into cubochoric\n% representation \n% the transformation is achieved by going from representation as unit\n% quaternions to homochoric representation (Lambert) and then further to\n% cubochoric representation (ball2cube)\n% \n% Input\n% q - @quaternion\n%\n% Output\n% XYZ - cubochoric coordinates\n\nxyz = Lambert([q.a(:) q.b(:) q.c(:) q.d(:)]);\nXYZ = ball2cube(xyz);\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@homochoricSO3Grid/private/quat2cube.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294403959948495, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6989508695140789}} {"text": "function welldrawdown\n% Well drawdown - comparison for confined / half-confined / unconfined\n% aquifers\n% using analytocal solutions \n%\n% $Ekkehard Holzbecher $Date: 2006/04/30 $\n%--------------------------------------------------------------------------\nK = 1.1e-5; % hydraulic conductivity\nH = 10; % depth\nT = K*H; % transmissivity\nQ = 1.e-4; % pumping rate\nr0 = 0.1; % well radius\ns0 = -1.; % drawdown in well\nc = 0.8e8; % resistance of half-permeable layer\nR = 35; % maximum radius\n\nr = linspace (r0,R,100); \nhc = s0 + (Q/(2*pi*T))*log(r/r0); \nhu = -H + s0 + sqrt(H*H + (Q/(pi*K))*log(r/r0)); \nhh = -(Q/(2*pi*T))*besselk(0,r/sqrt(T*c)); \n\nplot (r,hc,r,hh,r,hu);\nlegend ('confined','half-confined','unconfined')\nxlabel ('distance [m]'); ylabel ('drawdown (neg) [m]');\ntitle('Groundwater Drawdown due to Pumping')", "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/41147-environmental-modeling-using-matlab/welldrawdown.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.698878365194329}} {"text": "function m=pesq2mos(p)\n%PESQ2MOS convert PESQ speech quality scores to MOS m=(p)\n%Inputs: p is a matrix of PESQ scores\n%\n%Outputs: m is a matrix, the same size as p, of MOS scores\n%\n% The PESQ measure is defined in [2]. The mapping function, defined in [3],\n% converts raw PESQ scores (which lie in the range -0.5 to 4.5) onto the\n% MOS-LQO (Mean Opinion Score - Listening Quality Objective [2]) scale in the\n% range 1 to 5. The MOS scale is defined in [1] as\n% 5=Excellent, 4=Good, 3=Fair, 2=Poor, 1=Bad.\n%\n% Refs: [1]\tITU-T. Methods for subjective determination of transmission quality.\n% Recommendation P.800, Aug. 1996.\n% [2]\tITU-T. Mean opinion score (MOS) terminology.\n% Recommendation P.800.1, July 2006.\n% [2]\tITU-T. Perceptual evaluation of speech quality (PESQ), an objective\n% method for end-to-end speech quality assessment of narrowband telephone\n% networks and speech codecs. Recommendation P.862, Feb. 2001.\n% [3]\tITU-T. Mapping function for transforming P.862 raw result scores to MOS-LQO.\n% Recommendation P.862.1, Nov. 2003.\n\n% Copyright (C) Mike Brookes 2012-2013\n% Version: $Id: pesq2mos.m 3289 2013-08-01 13:56:02Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\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 can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\npersistent a b c d\nif isempty(a)\n a=0.999;\n b=4.999-a;\n c=-1.4945;\n d=4.6607;\nend\nif nargout>0\n m=a+b./(1+exp(c*p+d));\nelse\n if nargin<1 || isempty(p)\n pp=linspace(-0.5,4.5,100);\n else\n pp=p;\n end\n plot(pp,pesq2mos(pp));\n xlabel('PESQ (P.862)');\n ylabel('Mean Opimion Score (MOS)');\nend\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/pesq2mos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.6988598713200977}} {"text": "function [y, stopCondition, sigma, sigma0, t] ...\n = cons_smacof_pip(dx, y, isFree, bnd, w, con, smacof_opts, scip_opts)\n% CONS_SMACOF_PIP SMACOF algorithm with polynomial constraints (PIP file\n% format).\n%\n% Scaling by MAjorizing a COnvex Function (SMACOF) is an iterative solution\n% to the Multidimensional Scaling (MDS) problem (see de Leeuw and Mair [1]\n% for an up to date review).\n%\n% The classic implementation of SMACOF uses an iterative algorithm that\n% relies on the Guttman transform update. Our function here implements a\n% different approach, where the Guttman transform update is replaced by\n% solving a Quadratic Program (QP) (as proposed by Dwyer et al [2]) with\n% polynomial constraints.\n%\n% In this implementation, we use the SCIP binary to solve the constrained\n% QP. This binary can be downloaded for Linux, MacOS X and Windows from the\n% Zuse Institute Berlin (ZIB) website\n%\n% http://scip.zib.de/#download\n%\n% The objective function is\n%\n% min_y 1/2 y' * H * y + f' * y\n%\n% subject to the constraints and bounds provided by the user.\n%\n% We use the PIP file format to formulate the constrained QP and pass it to\n% SCIP.\n%\n% http://polip.zib.de/pipformat.php\n%\n%\n% [Y, STOPCONDITION, SIGMA, SIGMA0, T] = CONS_SMACOF_PIP(D, Y0, ISFREE, BND, [], CON)\n%\n% D is an (N, N)-distance matrix, with distances between the points in an\n% N-point configuration. D can be full or sparse. D(i,j)=0 means that\n% vertices i and j are not directly connected.\n%\n% Y0 is an initial guess of the solution, given as an (N, P)-matrix,\n% where P is the dimensionality of the output points. Currently, P must\n% be either 2 or 3.\n%\n% BND is a cell array with the variable bounds in PIP format, and cannot\n% be empty (otherwise SCIP doesn't return a solution). E.g.\n%\n% BND = {'Bounds', ' -1 <= x1 <= 4', ' -1 <= y1 <= 2.5', ...\n% ' -1 <= x2 <= 4', ' -1 <= y2 <= 2.5'};\n%\n% CON is a cell array with the problem constraints in PIP format, and\n% cannot be empty (otherwise SCIP doesn't return a solution). E.g.\n%\n% CON = {'Subject to', ...\n% ' c1: -0.5 x6 y7 +0.5 x3 y7 +0.5 x7 y6 -0.5 x3 y6 -0.5 x7 y3 +0.5 x6 y3 >= 0.1'};\n%\n% Y is the best solution computed by the algorithm within all iterations.\n% Y is a point configuration with the same size as Y0. If the algorithm\n% cannot find any valid solution (e.g. because we set a too short time\n% limit, or because a valid solution doesn't exist, Y will be an array of\n% NaNs).\n%\n% STOPCONDITION is a cell array with a string for each stop condition\n% that made the algorithm stop at the last iteration.\n%\n% SIGMA is a vector with the stress value at each iteration. Weighted\n% stress is given as\n%\n% SIGMA = \\sum_{i\n% Copyright \u00a9 2014, 2016 University of Oxford\n% Version: 0.4.6\n%\n% University of Oxford means the Chancellor, Masters and Scholars of\n% the University of Oxford, having an administrative office at\n% Wellington Square, Oxford OX1 2JD, UK. \n%\n% This file is part of Gerardus.\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. The offer of this\n% program under the terms of the License is subject to the License\n% being interpreted in accordance with English Law and subject to any\n% action against the University of Oxford being under the jurisdiction\n% of the English Courts.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see\n% .\n\n%% Input arguments\n\n% check arguments\nnarginchk(6, 8);\nnargoutchk(0, 5);\n\n% start clock\ntic\n\n% number of points\nN = size(dx, 1);\n\n% dimensionality of the points\nD = size(y, 2);\nif ((D ~= 2) && (D ~= 3))\n error('Only implemented for 2D output')\nend\n \n\n% check inputs\nif (N ~= size(dx, 2))\n error('D must be a square matrix')\nend\nif (N ~= size(y, 1))\n error('Y0 must have the same number of rows as D')\nend\n\n% defaults\nif (nargin < 3 || isempty(isFree))\n isFree = true(N, 1);\nend\nNfree = nnz(isFree);\n\nif (isempty(w))\n % if the user doesn't provide a weight matrix, we simply assign 1 if\n % two vertices are connected, and 0 if not\n w = double(dx ~= 0);\n if (any(diag(w)) ~= 0)\n error('Assertion error: W matrix has diagonal elements that are non-zero')\n end\nend\nif (any(size(w) ~= [N N]))\n error('W must be a square matrix with the same size as D')\nend\n\n% if the user doesn't allow any vertices to be optimized, then we can exit\n% the function\nif (Nfree == 0)\n stopCondition = 'No free vertices to optimise';\n sigma = [];\n dy = dmatrix_con(dx, y);\n sigma0 = 0.5 * sum(sum(w .* (dx - dy).^2));\n t = [];\n return;\nend\n\n% SMACOF_OPTS defaults\nif (nargin < 7 || isempty(smacof_opts) || ~isfield(smacof_opts, 'MaxIter'))\n smacof_opts.MaxIter = 100;\nend\nif (nargin < 7 || isempty(smacof_opts) || ~isfield(smacof_opts, 'Epsilon'))\n smacof_opts.Epsilon = 0;\nend\nif (nargin < 7 || isempty(smacof_opts) || ~isfield(smacof_opts, 'Display'))\n smacof_opts.Display = 'off';\nend\nif (nargin < 7 || isempty(smacof_opts) || ~isfield(smacof_opts, 'TolFun'))\n smacof_opts.TolFun = 1e-12;\nend\n\n% SCIP_OPTS\nif (nargin < 8 || isempty(scip_opts) || ~isfield(scip_opts, 'scipbin'))\n \n % default name of the SCIP binary depending on the architecture\n if (isunix)\n SCIPBIN = 'scip.linux.x86_64.gnu.opt.spx';\n elseif (ismac)\n SCIPBIN = 'scip.darwin.x86_64.gnu.opt.spx';\n elseif (ispc)\n SCIPBIN = 'scip.mingw.x86_64.intel.opt.spx.exe';\n else\n error('Operating system not recognized: I do not know what is the default name for the SCIP binary')\n end\nend\n\nscip_opts_comm = {};\nif (nargin >= 8 && ~isempty(scip_opts))\n \n % SCIP binary\n if (isfield(scip_opts, 'scipbin'))\n SCIPBIN = scip_opts.scipbin;\n end\n \n % display options\n QUIETFLAG = [];\n OUTPUTREDIR = []; % output redirecton, e.g. \"> /dev/null\"\n if isfield(scip_opts, 'display_verblevel')\n if (scip_opts.display_verblevel == 0)\n QUIETFLAG = ' -q ';\n \n % bug workaround: there's a bug in\n % scip-3.1.0.linux.x86_64.gnu.opt.spx, which causes the\n % solution to be written as an empty file when the quiet flag\n % is used. As a workaround, we disable the quiet flag in that\n % case, and instead send the output to /dev/null, as suggested\n % by Stefan Vigerske\n if strcmp(SCIPBIN, 'scip-3.1.0.linux.x86_64.gnu.opt.spx')\n QUIETFLAG = [];\n OUTPUTREDIR = ' > /dev/null';\n end\n \n end\n scip_opts_comm{end+1} = [' -c \"set display verblevel ' num2str(scip_opts.display_verblevel) '\"'];\n end\n \n % frequency for displaying node information lines [100]\n if (isfield(scip_opts, 'display_freq'))\n scip_opts_comm{end+1} = [' -c \"set display freq ' num2str(scip_opts.display_freq) '\"'];\n end\n \n % limits options\n \n % solving stops, if the absolute gap = |primalbound - dualbound| is below the given value [0.0]\n if (isfield(scip_opts, 'limits_absgap'))\n scip_opts_comm{end+1} = [' -c \"set limits absgap ' num2str(scip_opts.limits_absgap) '\"'];\n end\n \n % solving stops, if the relative gap = |primal - dual|/MIN(|dual|,|primal|) is below the given value [0.0]\n if (isfield(scip_opts, 'limits_gap'))\n scip_opts_comm{end+1} = [' -c \"set limits gap ' num2str(scip_opts.limits_gap) '\"'];\n end\n \n % maximal time in seconds to run [1e+20]\n if (isfield(scip_opts, 'limits_time'))\n scip_opts_comm{end+1} = [' -c \"set limits time ' num2str(scip_opts.limits_time) '\"'];\n end\n \n % solving stops, if the given number of solutions were found (-1: no limit) [-1]\n if (isfield(scip_opts, 'limits_solutions'))\n scip_opts_comm{end+1} = [' -c \"set limits solutions ' num2str(scip_opts.limits_solutions) '\"'];\n end\n \n % lp options\n \n % number of threads used for solving the LP (0: automatic)\n if (isfield(scip_opts, 'lp_threads'))\n scip_opts_comm{end+1} = [' -c \"set lp advanced threads ' num2str(scip_opts.lp_threads) '\"'];\n end\n \n % numerics options\n \n % feasibility tolerance for constraints in SCIP [1e-6]\n if (isfield(scip_opts, 'numerics_feastol'))\n scip_opts_comm{end+1} = [' -c \"set numerics feastol ' num2str(scip_opts.numerics_feastol) '\"'];\n end\n \nend\n\n%% Objective function: 1/2 nu' * H * nu + f' * nu\n\n% pre-compute the weighted Laplacian matrix\nV = -w;\nV(1:N+1:end) = sum(w, 2);\n\n% quadratic terms of the objective function\n\n% upper triangular matrix terms (we assume symmetric matrix)\ndx = tril(dx);\n\n% remove pairs where both vertices are fixed, as those only contribute a\n% constant to the objective function and can be ignored in the optimization\ndx(~isFree, ~isFree) = 0;\n\nNterms = nnz(dx);\nobjfunq = cell(1, Nterms + Nfree);\ncount = 1;\nfor idx = find(dx)'\n \n % decode dx matrix index into [I, J] vertices (we swap I,J so that we\n % get I as smaller index, and J larger index\n [J, I] = ind2sub(size(dx), idx);\n \n % upper triangular terms\n \n % 2D outputs\n if (D == 2)\n \n % xi (free), xj (free)\n if (isFree(I) && isFree(J))\n objfunq{count} = sprintf(...\n '+%.16g x%d x%d + %.16g y%d y%d', ...\n 2*full(V(I, J)), I, J, ...\n 2*full(V(I, J)), I, J);\n % xi (free), xj (fixed)\n elseif (isFree(I) && ~isFree(J))\n objfunq{count} = sprintf(...\n '+%.16g x%d + %.16g y%d', ...\n 2*full(V(I, J)) * y(J, 1), I, ...\n 2*full(V(I, J)) * y(J, 2), I);\n % xi (fixed), xj (free)\n elseif (~isFree(I) && isFree(J))\n objfunq{count} = sprintf(...\n '+%.16g x%d + %.16g y%d', ...\n 2*full(V(I, J)) * y(I, 1), J, ...\n 2*full(V(I, J)) * y(I, 2), J);\n end\n count = count + 1;\n \n % 3D outputs\n elseif (D == 3)\n \n % xi (free), xj (free)\n if (isFree(I) && isFree(J))\n objfunq{count} = sprintf(...\n '+%.16g x%d x%d + %.16g y%d y%d + %.16g z%d z%d', ...\n 2*full(V(I, J)), I, J, ...\n 2*full(V(I, J)), I, J, ...\n 2*full(V(I, J)), I, J);\n % xi (free), xj (fixed)\n elseif (isFree(I) && ~isFree(J))\n objfunq{count} = sprintf(...\n '+%.16g x%d + %.16g y%d + %.16g z%d', ...\n 2*full(V(I, J)) * y(J, 1), I, ...\n 2*full(V(I, J)) * y(J, 2), I, ...\n 2*full(V(I, J)) * y(J, 3), I);\n % xi (fixed), xj (free)\n elseif (~isFree(I) && isFree(J))\n objfunq{count} = sprintf(...\n '+%.16g x%d + %.16g y%d + %.16g z%d', ...\n 2*full(V(I, J)) * y(I, 1), J, ...\n 2*full(V(I, J)) * y(I, 2), J, ...\n 2*full(V(I, J)) * y(I, 3), J);\n end\n count = count + 1;\n \n else\n error('Assertion fail: Output dimension D is not 2 or 3')\n end\nend\n\n% main diagonal terms\nfor I = find(isFree)'\n \n % 2D outputs\n if (D == 2)\n\n % only free vertices contribute to the objective function\n objfunq{count} = sprintf(...\n '+%.16g x%d^2 + %.16g y%d^2', ...\n full(V(I, I)), I, ...\n full(V(I, I)), I);\n \n % 3D outputs\n elseif (D == 3)\n \n % only free vertices contribute to the objective function\n objfunq{count} = sprintf(...\n '+%.16g x%d^2 + %.16g y%d^2 + %.16g z%d^2', ...\n full(V(I, I)), I, ...\n full(V(I, I)), I, ...\n full(V(I, I)), I);\n \n else\n error('Assertion fail: Output dimension D is not 2 or 3')\n end\n count = count + 1;\n \nend\nobjfunq{1} = [' obj: ' objfunq{1}];\n\n% the linear term of the objective function (f) has to be computed at each\n% iteration of the QPQC-SMACOF algorithm. Thus, it is not computed here\n\n%% SMACOF algorithm\n\n% file name and path to save PIP model, computed solution and initial guess\n% (generate unique names so that it is possible to run several instances of\n% this function in parallel)\n[~, aux] = fileparts(tempname);\npipfilename = [tempdir 'model-' aux '.pip']; % PIP model\nsolfilename = [tempdir 'model-' aux '.sol']; % output solution\nsol0filename = [tempdir 'model-' aux '.sol0']; % initial guess\n\n% init stopCondition\nstopCondition = [];\n\n% Euclidean distances between vertices in the current solution\ndy = dmatrix_con(dx, y);\n\n% initial stress\nsigma0 = 0.5 * sum(sum(w .* (dx - dy).^2));\n\n% if dx, dy are sparse matrices, sigma0 will be a sparse scalar, and this\n% gives an error with fprintf below\nsigma0 = full(sigma0);\n\n% vector of stress computed by the algorithm\nsigma = zeros(1, smacof_opts.MaxIter);\n\n% display algorithm's evolution\nt = zeros(1, smacof_opts.MaxIter); % time past from 0th iteration\nif (strcmp(smacof_opts.Display, 'iter'))\n fprintf('Iter\\t\\tSigma\\t\\t\\tTime (sec)\\n')\n fprintf('===================================================\\n')\n fprintf('%d\\t\\t%.4e\\t\\t%.4e\\n', 0, sigma0, 0.0)\nend\n\n% auxiliary intermediate result\nmwdx = -w .* dx;\n\n% initialize the storage of the best solution found by the algorithm. We\n% start with Inf so that the initial guess will always be replaced by any\n% valid solution. The reason is that we cannot be sure that the initial\n% guess fulfills the constraints, but any valid solution from a later\n% iteration does\nsigmabest = Inf;\nybest = nan(size(y));\n\n% majorization loop\nfor I = 1:smacof_opts.MaxIter\n\n % auxiliary matrix B: non-main-diagonal elements\n B = mwdx ./ dy;\n B(isnan(B)) = 0;\n\n % auxiliary matrix B: main diagonal elements\n B(1:N+1:end) = -sum(B, 2);\n \n % the linear term (f) of the quadratic objective function \n % 1/2 nu' * H * nu + f' * nu\n % has to be recomputed at every iteration\n f = -2 * B * y;\n \n % convert linear term to PIP format\n objfunl = cell(1, Nfree);\n J = find(isFree);\n for idx = 1:length(J)\n\n % 2D output\n if (D == 2)\n \n objfunl{idx} = sprintf(...\n '+%.16g x%d +%.16g y%d', ...\n f(J(idx), 1), J(idx), f(J(idx), 2), J(idx));\n \n % 3D output\n elseif (D == 3)\n \n objfunl{idx} = sprintf(...\n '+%.16g x%d +%.16g y%d +%.16g z%d', ...\n f(J(idx), 1), J(idx), f(J(idx), 2), J(idx), ...\n f(J(idx), 3), J(idx));\n \n else\n error('Assertion fail: Output dimension D is not 2 or 3')\n end\n \n end\n \n % create PIP file to describe problem\n fid = fopen(pipfilename, 'w');\n if (fid == -1)\n error(['Cannot open file ' pipfilename ' to save PIP model'])\n end\n fprintf(fid, '%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n', ...\n 'Minimize', objfunq{:}, objfunl{:}, bnd{:}, con{:}, 'End');\n if (fclose(fid) == -1)\n error(['Cannot close file ' pipfilename ' to save PIP model'])\n end\n \n % create file for the initial guess\n write_solution(sol0filename, y);\n \n % solve the quadratic problem\n system([...\n SCIPBIN...\n QUIETFLAG ...\n ' -c \"read ' pipfilename '\"'...\n strcat(scip_opts_comm{:}) ...\n ' -c \"optimize\"'...\n ' -c \"write solution ' solfilename '\"'...\n ' -c \"quit\"' ...\n OUTPUTREDIR]);\n \n % read solution\n [aux, status] = read_solution(solfilename, size(y));\n \n % delete temp files\n if (exist(pipfilename, 'file')), delete(pipfilename); end\n if (exist(solfilename, 'file')), delete(solfilename); end\n if (exist(sol0filename, 'file')), delete(sol0filename); end\n \n % if SCIP cannot find a valid solution (e.g. we set a too short time\n % limit or it doesn't exist), then we cannot update the current\n % solution. This also means that we need to stop the optimization,\n % because the problem matrices and vectors won't change, and basically\n % we would try to solve the same problem again, not reaching a solution\n % either. Note however that it's possible that we have been finding\n % valid solutions before, and it's only at a later iteration that we\n % get to this \"not valid solution\" situation. Thus, we cannot assume\n % that the stop condition below these lines means \"error\".\n if (isempty(aux))\n stopCondition{end+1} = ['SCIP: ' status];\n sigma(I) = NaN;\n t(I) = toc;\n break;\n end\n\n % we only have to update the positions of the free vertices. The values\n % for fixed vertices in aux are all 0, so they need to be ignored\n y(isFree, :) = aux(isFree, :);\n \n % check that no two vertices are overlapping. Duplicated vertices cause\n % errors in the SMACOF algorithm because they create dy=0 components,\n % that produce Inf values in B = mwdx ./ dy;. Ideally, we would like\n % to move one of them a bit so that they don't overlap, while\n % maintaining the positive orientation of the triangles they are\n % involved with. However, we don't have the triangulation in this\n % function, and leave that for future work. For the time being, we are\n % going to consider overlapping vertices as a failed solution, and exit\n if (size(unique(y, 'rows'), 1) ~= N)\n stopCondition{end+1} = 'Duplicated vertex/vertices';\n break\n end\n \n % recompute distances between vertices in the current solution\n dy = dmatrix_con(dx, y);\n\n % compute stress with the current solution\n sigma(I) = 0.5 * sum(sum(w .* (dx - dy).^2));\n \n % update best solution\n if (sigma(I) < sigmabest)\n sigmabest = sigma(I);\n ybest = y;\n end\n \n % display algorithm's evolution\n t(I) = toc;\n if (strcmp(smacof_opts.Display, 'iter'))\n fprintf('%d\\t\\t%.4e\\t\\t%.4e\\n', I, sigma(I), t(I))\n end\n \n % check whether the stress is under the tolerance level requested by\n % the user\n if (sigma(I) < smacof_opts.TolFun)\n stopCondition{end+1} = 'TolFun';\n end\n \n % check whether the improvement in stress is below the user's request,\n % and it's positive (don't stop if the stress gets worse, because\n % stress can go up and down in the optimization)\n if (I > 1)\n if ((sigma(I-1)-sigma(I))/sigma(I-1) < smacof_opts.Epsilon ...\n && (sigma(I-1)-sigma(I))/sigma(I-1) >= 0)\n stopCondition{end+1} = 'Epsilon';\n end\n end\n\n % stop if any stop condition has been met\n if (~isempty(stopCondition))\n break;\n end\n \nend\n\n% return the best solution the algorithm has found in all iterations\ny = ybest;\n\n% check whether the \"maximum number of iterations\" stop condition has been\n% met\nif (I == smacof_opts.MaxIter)\n stopCondition{end+1} = 'MaxIter';\nend\n\n% prune stress and time vectors if convergence was reached before the\n% maximum number of iterations\nsigma(I+1:end) = [];\nt(I+1:end) = [];\n\nend\n\n% read SCIP solution from a text file created by SCIP\n%\n% file: path and file name of the solution file.\n%\n% sz: size of the output matrix with the solution. This parameter makes the\n% code easier to write, and it also allows to detect missing variables\n% in the solution\n%\n% y: matrix with the solution as a point configuration (each row is a\n% point)\nfunction [y, status] = read_solution(file, sz)\n\nif ((sz(2) ~= 2) && (sz(2) ~= 3))\n error('We only know how to read solutions that are sets of 2D or 3D points')\nend\n\nfid = fopen(file, 'r');\nif (fid == -1)\n error(['Cannot open file ' file ' to read solution'])\nend\n\n% read status of the solution\nstatus = fgetl(fid);\nif ((isnumeric(status) && status == -1) ...\n || ~strcmp(status(1:16), 'solution status:'))\n error(['Assertion fail: File with SCIP solution does not start with string ''solution status:''. File ' file])\nend\nstatus = status(18:end);\n\n% unless we obtained a valid solution, we don't bother with the rest of the\n% file (which should be empty anyway), we exit, and the main function\n% should detect the empty solution y, and create a stopCondition with the\n% status returned by SCIP\nif (~strcmp(status, 'optimal solution found') ...\n && ~strcmp(status, 'solution limit reached'))\n fclose(fid);\n y = [];\n return;\nend\n\n% the second line in the file should be the value of the objective function\naux = fgetl(fid);\nif (~strcmp(aux(1:16), 'objective value:'))\n error(['Assertion fail: Second line in file with SCIP solution does not start with string ''objective value:''. File ' file])\nend\n\n% read contents of the file. Example result:\n%\n% solution status: optimal solution found\n% objective value: 468.345678663118\n% x1 -4 \t(obj:0)\n% y1 2 \t(obj:0)\n% x2 0.613516669331233 \t(obj:0)\n% y2 -4 \t(obj:0)\n% x3 1.24777861008035 \t(obj:0)\n% y3 -3.43327058768579 \t(obj:0)\n% x4 -4 \t(obj:0)\n% y4 -0.804343353251697 \t(obj:0)\n% x5 2 \t(obj:0)\n% y5 -4 \t(obj:0)\n% x6 -3.31069797707353 \t(obj:0)\n% y6 1.21192102496956 \t(obj:0)\n% x7 1.643412276563 \t(obj:0)\n% y7 -3.72674560989634 \t(obj:0)\n% quadobjvar 468.345678663118 \t(obj:1)\nc = textscan(fid, '%s%f%s', 'Delimiter', ' ', 'MultipleDelimsAsOne', true);\nfclose(fid);\n\nif isempty(c{1})\n error('SCIP did not return any solution')\nend\n\n% if SCIP has found a solution, read it from the file into the output\n% matrix. Note that if a variable = 0, SCIP will not put it in the output\n% file\ny = zeros(sz);\nfor I = 1:length(c{1})-1\n \n % variable name\n varname = c{1}{I};\n \n % if list of output variables has finished, we can exit the loop\n if (strcmp(varname, 'quadobjvar'))\n break;\n end\n \n % vertex index\n idx = str2double(varname(2:end));\n \n if (c{1}{I}(1) == 'x') % this is an x-coordinate\n y(idx, 1) = c{2}(I);\n elseif (c{1}{I}(1) == 'y') % this is a y-coordinate\n y(idx, 2) = c{2}(I);\n elseif (c{1}{I}(1) == 'z') % this is a z-coordinate\n y(idx, 3) = c{2}(I);\n end\n \nend\n\nend\n\n% write SCIP initial solution to a text file that SCIP can understand\n%\n% y: matrix with the solution as a point configuration (each row is a\n% point), including the points that are not free points\n%\n% file: path and file name of the solution file.\nfunction write_solution(file, y)\n\n% size of full solution configuration\nsz = size(y);\n\nif ((sz(2) ~= 2) && (sz(2) ~= 3))\n error('We only know how to read solutions that are sets of 2D or 3D points')\nend\n\nfid = fopen(file, 'w');\nif (fid == -1)\n error(['Cannot open file ' file ' to write solution'])\nend\n\n% write solution to file. Example result:\n%\n% x1 -4 \t(obj:0)\n% y1 2 \t(obj:0)\n% x2 0.613516669331233 \t(obj:0)\n% y2 -4 \t(obj:0)\n% x3 1.24777861008035 \t(obj:0)\n% y3 -3.43327058768579 \t(obj:0)\n% x4 -4 \t(obj:0)\n% y4 -0.804343353251697 \t(obj:0)\n% x5 2 \t(obj:0)\n% y5 -4 \t(obj:0)\n% x6 -3.31069797707353 \t(obj:0)\n% y6 1.21192102496956 \t(obj:0)\n% x7 1.643412276563 \t(obj:0)\n% y7 -3.72674560989634 \t(obj:0)\nfor I = 1:sz(1)\n \n % write x-coordinate\n fprintf(fid, '%s%d\\t%.16e\\t%s\\n', 'x', I, y(I, 1), '(obj:0)');\n\n % write y-coordinate\n fprintf(fid, '%s%d\\t%.16e\\t%s\\n', 'y', I, y(I, 2), '(obj:0)');\n \n % write z-coordinate\n if (sz(2) == 3)\n fprintf(fid, '%s%d\\t%.16e\\t%s\\n', 'z', I, y(I, 3), '(obj:0)');\n end\n \nend\n\n% close file\nst = fclose(fid);\nif (st == -1)\n error(['Cannot close file ' file ' after writing solution'])\nend\n\nend\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/PointsToolbox/cons_smacof_pip.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.6988598599455798}} {"text": "function [ lines ] = findlines( imge,map,theta,rho,minLen,maxLineNum,maxPeakNum,resol,maxGap )\n%FINDLINE Find line features in the image using Hough transform\n% LINES = FINDLINES(IMGE,MAP,THETA,RHO,MINLEN,MAXLINENUM,MAXPEAKNUM,RESOL,MAXGAP)\t\n%\tIMGE is the binary edge image; \n%\tMAP,THETA,RHO is the output of HOUGH;\n%\tMINLEN is the minimum length of lines that will be found;\n%\tNo more MAXLINENUM lines will be returned;\n%\tMAXPEAKNUM is the maximum peaks\tthat will be detected on the map;\n%\tMAXGAP is the maximum gap length that will be merged;\n%\tRESOL is the resolution of the detected lines, the smaller, the lines\n%\tmust be further away from each other. A suggest value is 100.\n%\tLINES is a struct array with members: theta,rho,point1([row,col]),point2. \n%\t\t\n%\tYan Ke @ THUEE, 20110123, xjed09@gmail.com\n\n% imge = edge(img);\n% [map theta rho] = hough1(imge,[]);\n[pri pti] = findpeaks(map,minLen,maxPeakNum,resol);\npeakNum = length(pri);\nprho = rho(pri); % peak points\npthe = theta(pti)*pi/180;\nrhoThres = abs(rho(2)-rho(1))/2;\n\nfitPts = cell(1,peakNum);\nfitPtsNum = zeros(1,peakNum);\nfor p = 1:peakNum\n\t % store points which are on the lines\n\tfitPts{p} = zeros(2,ceil(map(pri(p),pti(p))*1.2));\nend\n[Y X] = find(imge);\nX = X-1; % The origin is the bottom-left corner.\nM = size(imge,1);\nY = M-Y;\n\n% find the points that's on the selected lines\nfor p = 1:length(X)\n\trho1 = X(p)*sin(pthe)+Y(p)*cos(pthe);\n\tisOnPeak = find(abs(rho1-prho)<=rhoThres);\n\tfitPtsNum(isOnPeak) = fitPtsNum(isOnPeak)+1;\n\tfor q = isOnPeak\n\t\tfitPts{q}(:,fitPtsNum(q)) = [X(p);Y(p)];\n\tend\nend\n\n% track the points on each line, find the start points and the end points,\nlines = [];\ntempLine = struct;\nfor p = 1:peakNum\n\tt1 = [-cos(pthe(p)),sin(pthe(p))]; % the unit directional vector of the line\n\tdist1 = t1*fitPts{p}(:,1:fitPtsNum(p)); % dist along the line\n\t[ordDist ordIdx] = sort(dist1,'ascend');\n\tordPts = fitPts{p}(:,ordIdx);\n\t\n\t% handle with the gaps\n\tdist2 = diff(ordDist); % dist with each other\n\tgapPos = [0 find(dist2>maxGap) length(ordDist)];\n\tlineLen = diff(gapPos);\n\tfor q = find(lineLen>=minLen)\n\t\ttempLine.theta = pthe(p);\n\t\ttempLine.rho = prho(p);\n\t\ttempLine.point1 = [M-ordPts(2,gapPos(q)+1),ordPts(1,gapPos(q)+1)+1];\n\t\ttempLine.point2 = [M-ordPts(2,gapPos(q+1)),ordPts(1,gapPos(q+1))+1];\n\t\tlines = [lines,tempLine];\n\t\tif length(lines) == maxLineNum, break; end\n\tend\n\tif length(lines) == maxLineNum, break; end\nend\n\t\nend\n\nfunction [rows cols] = findpeaks(map,minLen,maxPeakNum,resol)\n%\tFind the at most maxLinNum points that's no less than minLen in map, meanwhile not\n%\t8-adjacent to each other, in MAP. Rows and cols are returned.\n\nif max(max(map)) < minLen, return; end\nrows = zeros(1,maxPeakNum);\ncols = rows;\nsz = size(map);\nsup = ceil(sz/resol);\nfor p = 1:maxPeakNum\n\t[V,I] = max(map(:));\n\tif V maxPeakNum, pt = pt(1:maxPeakNum); end\n% [rows cols] = ind2sub(size(map),pt);\n\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/30806-find-and-mark-lines-using-hough-transform/findlines.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6988598522323957}} {"text": "function line_num = sphere_llq_grid_line_count ( lat_num, long_num )\n\n%*****************************************************************************80\n%\n%% SPHERE_LLQ_GRID_LINE_COUNT counts lines for an LLQ grid on a sphere.\n%\n% Discussion:\n%\n% A SPHERE LLQ grid imposes a grid of quadrilaterals on a sphere,\n% using latitude and longitude lines.\n%\n% The number returned is the number of pairs of points to be connected\n% to form all the line segments.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 28 April 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer LAT_NUM, LONG_NUM, the number of latitude and\n% longitude lines to draw. The latitudes do not include the North and South\n% poles, which will be included automatically, so LAT_NUM = 5, for instance,\n% will result in points along 7 lines of latitude.\n%\n% Output, integer LINE_NUM, the number of grid lines.\n%\n line_num = long_num * ( lat_num + 1 ) ...\n + lat_num * long_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/sphere_llq_grid/sphere_llq_grid_line_count.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.6988370751333428}} {"text": "function value = index3_row ( i_min, i, i_max, j_min, j, j_max, ...\n k_min, k, k_max, index_min )\n\n%*****************************************************************************80\n%\n%% INDEX3_ROW indexes a 3D array by rows.\n%\n% Discussion:\n%\n% When we say \"by rows\", we really just mean that entries of the array are\n% indexed starting at entry (I_MIN,J_MIN,K_MIN), and the increasing the LAST\n% index first, then the next-to-the-last, and so on.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 April 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer I_MIN, I, I_MAX, for row indices,\n% the minimum, the index, and the maximum.\n%\n% Input, integer J_MIN, J, J_MAX, for column indices,\n% the minimum, the index, and the maximum.\n%\n% Input, integer K_MIN, K, K_MAX, for plane indices,\n% the minimum, the index, and the maximum.\n%\n% Input, integer INDEX_MIN, the index of (I_MIN,J_MIN,K_MIN).\n% Typically, this is 0 or 1.\n%\n% Output, integer VALUE, the index of element (I,J,K).\n%\n value = index_min ...\n + ( k - k_min ) ...\n + ( j - j_min ) * ( k_max + 1 - k_min ) ...\n + ( i - i_min ) * ( j_max + 1 - j_min ) * ( k_max + 1 - k_min );\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/subpak/index3_row.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.6988370699835429}} {"text": "function [ t, rank ] = subset_next ( n, t, rank )\n\n%*****************************************************************************80\n%\n%% SUBSET_NEXT computes the subset lexicographic successor.\n%\n% Discussion:\n%\n% This is a lightly modified version of \"subset_lex_successor()\" from COMBO.\n%\n% Example:\n%\n% On initial call, N is 5 and the input value of RANK is -1.\n% Then here are the successive outputs from the program:\n%\n% Rank T1 T2 T3 T4 T5\n% ---- -- -- -- -- --\n% 0 0 0 0 0 0\n% 1 0 0 0 0 1\n% 2 0 0 0 1 0\n% 3 0 0 0 1 1\n% .. .. .. .. .. ..\n% 30 1 1 1 1 0\n% 31 1 1 1 1 1\n% -1 0 0 0 0 0 <-- Reached end of cycle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 May 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Donald Kreher, Douglas Simpson,\n% Combinatorial Algorithms,\n% CRC Press, 1998,\n% ISBN: 0-8493-3988-X,\n% LC: QA164.K73.\n%\n% Parameters:\n%\n% Input, integer N, the number of elements in the master set.\n% N must be positive.\n%\n% Input/output, integer T(N), describes a subset. T(I) is 0 if\n% the I-th element of the master set is not in the subset, and is\n% 1 if the I-th element is part of the subset.\n% On input, T describes a subset.\n% On output, T describes the next subset in the ordering.\n%\n% Input/output, integer RANK, the rank.\n% If RANK = -1 on input, then the routine understands that this is\n% the first call, and that the user wishes the routine to supply\n% the first element in the ordering, which has RANK = 0.\n% In general, the input value of RANK is increased by 1 for output,\n% unless the very last element of the ordering was input, in which\n% case the output value of RANK is -1.\n%\n\n%\n% Return the first element.\n%\n if ( rank == -1 )\n t = zeros ( n, 1 );\n rank = 0;\n return\n end\n\n for i = n : -1 : 1\n\n if ( t(i) == 0 )\n t(i) = 1;\n rank = rank + 1;\n return\n else\n t(i) = 0;\n end\n\n end\n\n rank = -1;\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/partition_problem/subset_next.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.6987925734522048}} {"text": "function poly2 = densifyPolygon(poly, N)\n%DENSIFYPOLYGON Add several points on each edge of the polygon.\n%\n% POLY2 = densifyPolygon(POLY, N)\n% POLY is a NV-by-2 array containing polygon coordinates. The function\n% iterates on polygon edges, divides it into N subedges (by inserting N-1\n% new vertices on each edges), and return the resulting polygon.\n% The new polygon POLY has therefore N*NV vertices.\n%\n% Example\n% % Densifies a simple polygon\n% poly = [0 0 ; 10 0;5 10;15 15;5 20;-5 10];\n% poly2 = densifyPolygon(poly, 10);\n% figure; drawPolygon(poly); axis equal\n% hold on; drawPoint(poly2);\n%\n% See also \n% drawPolygon, edgeToPolyline\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2011-11-25, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011-2022 INRA - Cepia Software Platform\n\n% number of vertices, and of edges\nNv = size(poly, 1);\n\n% number of vertices in new polygon\nN2 = N * Nv;\npoly2 = zeros(N2, 2);\n\n% iterate on polygon edges\nfor i = 1:Nv\n % extract current edge\n v1 = poly(i, :);\n v2 = poly(mod(i, Nv) + 1, :);\n \n % convert current edge to polyline\n newVertices = edgeToPolyline([v1 v2], N);\n \n % indices of current polyline to resulting polygon\n i1 = (i-1)*N + 1;\n i2 = i * N;\n \n % fill up polygon\n poly2(i1:i2, :) = newVertices(1:end-1, :);\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/polygons2d/densifyPolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.6987925593248685}} {"text": "% another simple 1D convection example with periodic BC\n% diffusion coefficients are defined but not used\n% It compares the results of upwind with TVD and shows how diffusive the upwind\n% See how diffusive the upwind scheme can be althou it is so bad \n% everywhere. Play with flux limiters, time steps, initial condition and time steps\n% and see the difference between schemes in action\n% Written by Ali A. Eftekhari\n% Last checked: June 2021\nclc\n% define a 1D domain and mesh\nW = 1;\nNx = 500;\nmesh1 = createMesh1D(Nx, W);\nx = mesh1.cellcenters.x;\n% define the boundaries\nBC = createBC(mesh1); % all Neumann\nBC.left.periodic=1;\nBC.right.periodic =1;\n% Initial values\nphi_old = createCellVariable(mesh1, 0.0, BC);\nphi_old.value(20:120) = 1;\nphi_old.value(180:400)= sin(x(180:400)*10*pi());\n% initial guess for phi\nphi = phi_old;\n% initial values for upwind scheme\nphiuw = phi;\nphiuw_old=phi;\n% keep the initial values for visualization\nphiinit=phi_old;\n% velocity field\nu = 0.3;\nuf = createFaceVariable(mesh1, u);\n% diffusion field\nD = 1e-2;\nDf = createFaceVariable(mesh1, D);\n% transient term coefficient\nalfa = createCellVariable(mesh1,1.0);\n% upwind convection term\nMconvuw = convectionUpwindTerm1D(uf);\n% define the BC term\n[Mbc, RHSbc] = boundaryCondition(BC);\n% choose a flux limiter\nFL = fluxLimiter('Superbee');\n% solver\ndt = 0.0005; % time step\nfinal_t = W/u;\nt = 0;\nwhile t> icp_demo\n% in MATLAB\n\n% size of model/data\nn_model=2000;\nn_data=1300;\n\n% model points\nmodel=4*randn(3,n_model)-2*ones(3,n_model);\nbol=(model(1,:).^2+model(2,:).^2)<2^2;\nwhile any(not(bol))\n model(:,not(bol))=4*randn(3,sum(not(bol)))-2*ones(3,sum(not(bol)));\n bol=(model(1,:).^2+model(2,:).^2)<2^2;\nend\nmodel(:,not(bol))=4*randn(3,sum(not(bol)))-2*ones(3,sum(not(bol)));\nmodel(3,:)=0.5*(model(1,:).^2-model(2,:).^2);\nbol=(model(1,:).^2+model(2,:).^2)<0.9^2;\nmodel(3,bol)=3.5-3.5*(1/0.9)*sqrt(model(1,bol).^2+model(2,bol).^2);\n\n% data points\ndata=model(:,1:n_data);\n\n% weights\nweights=ones(1,n_data);weights=rand(1,n_data);\n\n% Transform points in data (move away from start position).\ndeg=15;\nv1=2*(rand-0.5)*deg*(pi/180);\nv2=2*(rand-0.5)*deg*(pi/180);\nv3=2*(rand-0.5)*deg*(pi/180);\nTR0=[cos(v1) sin(v1) 0;-sin(v1) cos(v1) 0;0 0 1];\nTR0=TR0*[cos(v2) 0 sin(v2);0 1 0;-sin(v2) 0 cos(v2)];\nTR0=TR0*[1 0 0;0 cos(v3) sin(v3);0 -sin(v3) cos(v3)];\nTT0=3.0*(rand(3,1)-0.5);\ndata=TR0*data+repmat(TT0,1,n_data);\n\n% randvec\nrndvec=uint32(randperm(n_data)-1);\n\n% sizerand, number of point-matchings in each iteration.\nsizernd=ceil(1.45*n_data);\n\n% Number of iterations.\niter=40;\n\n% Compile the c++ files (not nessesacily if it is already done).\ntry\n make\nend\n\n% Create the kd-tree, TreeRoot is the pointer to the kd-tree\n[tmp, tmp, TreeRoot] = kdtree( model', []);\n\n% Run the ICP algorithm.\n[R,T]=icpCpp(model,data,weights,rndvec,sizernd,TreeRoot,iter);\n\n% Free allocated memory for the kd-tree.\nkdtree([],[],TreeRoot);\n\n\n\nfigure(1),plot3(model(1,:),model(2,:),model(3,:),'r.',data(1,:),data(2,:),data(3,:),'c.'),hold off;\n\n% Transform the data points.\ndata=R*data+repmat(T,1,n_data);\n\nfigure(2),plot3(model(1,:),model(2,:),model(3,:),'r.',data(1,:),data(2,:),data(3,:),'b.'),hold off;\n\nclear functions\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/16766-iterative-closest-point-method-c++/icp_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567085, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6986425938028279}} {"text": "% DeInterleaver function\nfunction [data_out]=deinterleav_d(data_in,rate_id)\n\nswitch (rate_id)\n case 0\n Ncbps=192; % In BPSK no.of bits allocated to subcarrier in a OFDM symbol\n Ncpc=1; % In cash of BPSK No. of coded bit per carrier.\n case {1,2}\n Ncbps=384; \n Ncpc=2; \n case {3,4} %% note: no. of coded bit Ncpc=1,2,4,6 for bpsk,qpsk,16qam,64qam respectivly%% \n Ncbps=768; \n Ncpc=4; \n case {5,6} \n Ncbps=1152; \n Ncpc=6; \n otherwise\n display('error in interleaver give proper rate_id')\nend\n\ns=ceil(Ncpc/2); \n\n\ndata=data_in';\n%%% Deinterleaving \n % j-->index of the bit encoded BEFORE the first permutation\n % mj-->index of this bit BEFORE the second permutation and AFTER the first one\n % kj-->index after the SECOND permutation, just before the mapping of the sign.\n\n j = 0:Ncbps-1;\n mj = s*floor(j/s) + mod((j + floor(12*j/Ncbps)),s); % First permutation\n kj = 12*mj-(Ncbps-1)*floor(12*mj/Ncbps); % Second permutation\n \n % The indices are ordered to know what must be taken.\n [c d]= sort(kj);\n\n% finally the bits are rearranged.\n\n i = 1:Ncbps;\n data_out = zeros(1,Ncbps);\n data_out(i) = data(d(i));\n data_out=data_out';\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/24369-wimax-physical-layer-simulation/wimax phy layer simulation code/deinterleav_d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6986271806255956}} {"text": "function coeff = reg_als(basis_cr, y, r, n)\n%REG_ALS Summary of this function goes here\n% d - dimension of the regression function\n% N - number of regression points\n% y - 1 x N array of values of the function to approximate\n% n - d x 1 array, stores number of basis functions in each dimension\n% r - d+1 x 1 array, stores TT-ranks of the tensor of coefficients of the\n% regression function\n% basis_cr - array that stores values of basis functions at regression\n% points\n% fixed - d x 1 cell of aggregated fixed dimensions of the regression \n% function at k-th step of the ALS algorithm\n% coeff - TT-tensor of coefficient of the regression function\n\nN = size(y, 2);\nd = numel(n);\ncoeff = tt_rand(n, d, r);\ncoeff_ps = coeff.ps;\ncoeff_cr = coeff.core;\nbasis_ps = cumsum([1 ; n*N]);\n \n% assemble fixed part of the TT-function\nfixed_ps = cumsum([1 ; N ; r(2:d)*N ; N]);\nfixed_cr = zeros(fixed_ps(d+2) - fixed_ps(1), 1);\nfixed_cr(fixed_ps(d+1): fixed_ps(d+2)-1) = ones(N, r(d+1));\nfor dim = d: -1: 2\n c = reshape(coeff_cr(coeff_ps(dim): coeff_ps(dim+1)-1), [r(dim) n(dim) r(dim+1)]);\n c = permute(c, [1 3 2]);\n b = reshape(basis_cr(basis_ps(dim): basis_ps(dim+1)-1), [n(dim) N]);\n t1 = ten_conv(c, 3, b); % r(dim) x r(dim+1) x N\n t2 = reshape(fixed_cr(fixed_ps(dim+1): fixed_ps(dim+2)-1), [r(dim+1), N]);\n t1 = reshape(t1, [r(dim), r(dim+1)*N]);\n t2 = kron(ones(r(dim),1), reshape(t2, [1, r(dim+1)*N]));\n t3 = t1.*t2;\n t3 = reshape(t3, [r(dim) r(dim+1) N]);\n\tt3 = sum(t3, 2);\n fixed_cr(fixed_ps(dim): fixed_ps(dim+1)-1) = reshape(t3, [r(dim)*N, 1]);\nend\nfixed_cr(fixed_ps(1): fixed_ps(2)-1) = ones(N, r(1));\n\n% initial sum of squares\nVAR = var(y);\n\nn_swp = 0;\nR2 = 0;\nswp_tp = 'f';\ndim = 1;\nwhile R2 < 0.9999 && n_swp < 10\n n1 = r(dim);\n n2 = n(dim);\n n3 = r(dim+1);\n \n u1 = reshape(fixed_cr(fixed_ps(dim): fixed_ps(dim+1)-1), [N n1]);\n u2 = reshape(basis_cr(basis_ps(dim): basis_ps(dim+1)-1), [n2 N]);\n u3 = reshape(fixed_cr(fixed_ps(dim+1): fixed_ps(dim+2)-1), [n3 N]);\n \n t1 = kron(kron(ones(n3,1), ones(n2,1)), u1');\n t2 = kron(kron(ones(n3,1), u2), ones(n1,1));\n t3 = kron(kron(u3, ones(n2,1)), ones(n1,1));\n t = t1.*t2.*t3;\n \n A = t*t';\n b = t*y';\n c = A\\b;\n coeff_cr(coeff_ps(dim):coeff_ps(dim+1)-1) = c;\n \n if (swp_tp == 'f' && dim < d) || (swp_tp == 'b' && dim == 1)\n c = permute(reshape(c, [n1 n2 n3]), [1 3 2]);\n t1 = ten_conv(c, 3, u2);\n t1 = reshape(t1, [n1*n3, N]);\n u1 = kron(ones(1,n3), u1);\n t2 = u1.*t1';\n t2 = reshape(t2, [N n1 n3]);\n t2 = sum(t2, 2);\n t2 = reshape(t2, [N, n3]);\n fixed_cr(fixed_ps(dim+1): fixed_ps(dim+2)-1) = reshape(t2, [N*n3, 1]);\n \n %R^2\n if swp_tp == 'b'\n MSE = sum((sum(t2'.*u3,1) - y).^2)/N;\n R2 = 1 - MSE/VAR;\n end\n elseif (swp_tp == 'b' && dim > 1) || (swp_tp == 'f' && dim == d)\n c = permute(reshape(c, [n1 n2 n3]), [1 3 2]);\n t1 = ten_conv(c, 3, u2);\n t1 = reshape(t1, [n1, n3*N]);\n u3 = kron(ones(n1,1), reshape(u3, [1, n3*N]));\n t2 = t1.*u3;\n t2 = reshape(t2, [n1 n3 N]);\n t2 = sum(t2, 2);\n t2 = reshape(t2, [n1 N]);\n fixed_cr(fixed_ps(dim): fixed_ps(dim+1)-1) = reshape(t2, [n1*N, 1]);\n \n %R^2\n if swp_tp == 'f'\n MSE = sum((sum(u1'.*t2,1) - y).^2)/N;\n R2 = 1 - MSE/VAR;\n end\n end\n \n if swp_tp == 'f'\n if dim < d\n dim = dim + 1;\n elseif dim == d\n swp_tp = 'b';\n dim = dim - 1;\n n_swp = n_swp + 1;\n fprintf('=tt_reg_als= Sweep %d, R^2: %.2f%%, MSE: %1.2e\\n', n_swp, 100*R2, MSE);\n end\n elseif swp_tp == 'b'\n if dim > 1\n dim = dim - 1;\n elseif dim == 1\n swp_tp = 'f';\n dim = dim + 1;\n n_swp = n_swp + 1;\n fprintf('=tt_reg_als= Sweep %d, R^2: %.2f%%, MSE: %1.2e\\n', n_swp, 100*R2, MSE);\n end\n end\nend\n\ncoeff.core = coeff_cr;\n\nend", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/tt_regression/reg_als.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6986271772083449}} {"text": "%% Total Variation Denoising\n% Test for Rudin-Osher-Fatemi denoising (ROF) using FB-like method.\n\naddpath('../');\naddpath('../toolbox/');\n\n%%\n% Load image.\n\nn = 256;\ny = load_image('lena',n*2);\ny = rescale(crop(y,n));\ny = y + randn(n)*.06;\n\n%%\n% Display it.\n\nclf;\nimageplot(clamp(y));\n\n%%\n% We aim at minimising:\n\n%%\n% |min_x 1/2*norm(y-x,'fro')^2 + lambda*norm(K(x),1)|\n\n\n%%\n% Regularization parameter.\n\nlambda = .2;\n\n%%\n% where |K| is a vectorial gradient and |norm(u,1)| is a vectorial L1\n% norme.\n\nK = @(x)grad(x);\nKS = @(x)-div(x);\n\n%%\n% It can be put as the minimization of |F(K*x) + G(x)|\n\nAmplitude = @(u)sqrt(sum(u.^2,3));\nF = @(u)lambda*sum(sum(Amplitude(u)));\nG = @(x)1/2*norm(y-x,'fro')^2;\n\n%%\n% The proximity operator of |F| is the vectorial soft thresholding.\n\nNormalize = @(u)u./repmat( max(Amplitude(u),1e-10), [1 1 2] );\nProxF = @(u,tau)repmat( perform_soft_thresholding(Amplitude(u),lambda*tau), [1 1 2]).*Normalize(u);\nProxFS = compute_dual_prox(ProxF);\n\n%%\n% The proximity operator of G.\n\nProxG = @(x,tau)(x+tau*y)/(1+tau);\n\n%%\n% Function to record progression of the functional.\n\noptions.report = @(x)G(x) + F(K(x));\n\n%%\n% Run the ADMM algorihtm.\n\noptions.niter = 300;\n[xAdmm,EAdmm] = perform_admm(y, K, KS, ProxFS, ProxG, options);\n\n%%\n% Display image.\n\nclf;\nimageplot(xAdmm);\n\n%%\n% Since the functional to mimize is stricly convex, we can use a FB scheme\n% on the dual problem.\n\nGradGS = @(x)x+y;\nL = 8;\noptions.method = 'fista';\n[xFista,EFista] = perform_fb_strongly(y, K, KS, GradGS, ProxFS, L, options);\n\n%%\n% Compare the energy decays.\n\nclf;\nplot([EAdmm(:) EFista(:)]);\naxis tight;\nlegend('ADMM', 'FISTA');\naxis([1 length(EAdmm) EFista(end)*.9 2000]);\n\n \n ", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_optim/tests/test_tv_lagrangian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6986127590552124}} {"text": "%% Classic Monte Carlo simualtion\n% Vincent Leclercq, The MathWorks, 2007, vincent.leclercq@mathworks.fr\n%\n\nclear all;\nclose all;\n\n\nNbTrials = 10000;\n\n%RunMode = 'LogNomrality';\n\nRunMode = 'OptionPricing';\n%% Load Data (retrieved originally from Thomson Datastream)\n\nload Equities.mat\nPastDate = today()-1 * 365;\n\n%% Retrieve the dates in a numeric format\n\nDates = cellfun(@(x)(datenum(x,'yyyy-mm-ddTHH:MM:SS')),Equities.DATE);\nAssetPrices = cellfun(@(x) (str2double(x)),Equities.P );\n \n%% Plot the Series\n\nplot(Dates,AssetPrices);set(gcf,'WindowStyle','Docked');\nlegend(Equities.DISPNAME);\ndatetick('x','mmmyy');\nxlim([PastDate, today()]);\ngrid on;\n\n\n%% Compute the returns\n% We can compute the returns for one or many stocks at the same time using\n% matrix computation and matlab easy syntax\n\nSuez_Returns = tick2ret(AssetPrices);\nDailyVol = std(Suez_Returns);\nAnnualVol = DailyVol * sqrt(252);\n\nSpotPrice = AssetPrices(end);\n\nInterestRate = 0.0375;\n\n%% Portfolio simulation (Monte Carlo) using the Financial toolbox function\n% For help, one can use the doc portsim function\n% We call the portfolio simulation using Financial toolbox to\n% simulate 10000 scenarios. Of course, correlation are preserved\n% We assume an horizon of 6 * 22 trading days, ie 6 month maturity\n\n%% Using Annual statistics\n\n\nSimulatedRetsAnnual = portsim(InterestRate,AnnualVol^2, 12, 1/12, NbTrials,'Expected'); % NbStep * TimeStep = 1 (in years !!!)\n\n%% Using Daily statistics\nNumberOfSimulationSteps = 12;\nSimulatedRetsDaily = portsim(InterestRate./252, DailyVol^2, 12, 252./12, NbTrials,'Expected');% NbStep * TimeStep = 252 (in days!!!)\n\n\n\n\n%% Generate the Prices and plot them\n\nSimulatedPricesAnnual = ret2tick(squeeze(SimulatedRetsAnnual) ,SpotPrice);\nSimulatedPricesDaily = ret2tick(squeeze(SimulatedRetsDaily) ,SpotPrice );\n\nfigure;hist(SimulatedPricesAnnual(end,:),40);title('Prices, annual timestep used');set(gcf,'WindowStyle','Docked');\nfigure;hist(SimulatedPricesDaily(end,:),40);title('Prices, daily timestep used');set(gcf,'WindowStyle','Docked');\n\n%% Check For LogNormality of the Price series\n\nExpectedVariance = (SpotPrice^2) * (exp(AnnualVol^2) - 1)* exp(2*InterestRate);\n\ndisp(['Mean Price (Annual Parameters) -> ', num2str(mean(SimulatedPricesAnnual(end,:))) ' , Theoric value (Hull) :' num2str(SpotPrice * exp(InterestRate))]);\ndisp(['Mean Price (Daily Parameters) -> ', num2str(mean(SimulatedPricesDaily(end,:))) ' , Theoric value (Hull) :' num2str(SpotPrice * exp(InterestRate))]);\n\ndisp(['Expected Variance (Annual Parameters) -> ', num2str(var(SimulatedPricesAnnual(end,:))) ' , Theoric value (Hull) :' num2str(ExpectedVariance)]);\ndisp(['Expected Variance (Daily Parameters) -> ', num2str(var(SimulatedPricesDaily(end,:))) ' , Theoric value (Hull) :' num2str(ExpectedVariance)]);\n\n\n%% Parameter sweep\n% Now that we have done this, we can ccompute the same thing for different\n% Exercise prices\nif strcmp(RunMode,'OptionPricing')\n k = 1;\n NumberOfSteps = 400;\n ExercisePrices= linspace(0.8 * SpotPrice,1.2 * SpotPrice,NumberOfSteps);\n\n\n VanillaPriceAnnual = zeros(NumberOfSteps,1);\n VanillaPriceDaily = zeros(NumberOfSteps,1);\n\n ProbabilityITMAnnual = zeros(NumberOfSteps,1);\n ProbabilityITMDaily = zeros(NumberOfSteps,1);\n CIAnnual = zeros(NumberOfSteps,2);\n CIDaily = zeros(NumberOfSteps,2);\n BLSPrices = zeros(NumberOfSteps,1);\n\n %%\n TimeInYear = 1;\n for i = 1 : NumberOfSteps\n [BLSPrices(i),dummy] = blsprice(SpotPrice, ExercisePrices(i), InterestRate, TimeInYear, AnnualVol, 0);\n [VanillaPriceAnnual(i), ProbabilityITMAnnual(i) ,CIAnnual(i,:)] = GetOptionPrice(SimulatedPricesAnnual,ExercisePrices(i),TimeInYear,InterestRate,'Vanilla');\n [VanillaPriceDaily(i), ProbabilityITMDaily(i) , CIDaily(i,:)] = GetOptionPrice(SimulatedPricesDaily,ExercisePrices(i),TimeInYear,InterestRate,'Vanilla');\n\n end;\n\n%% \n \n h = figure;\n [AX,H1,H2] = plotyy(ExercisePrices,[VanillaPriceAnnual BLSPrices CIAnnual] , ExercisePrices,ProbabilityITMAnnual);\n\n\n xlabel('Exercise Price');\n title('Option prices for a Vanilla option using a 1 year - Annual volatility');\n Axes_YLabels = get(AX,'Ylabel');\n set(Axes_YLabels{1},'String','Option Price') ;\n\n set(H1(1),'LineStyle','-');\n set(H1(1),'Color','r');\n set(H1(1),'LineWidth',2);\n\n\n set(H1(2),'LineStyle','-');\n set(H1(2),'Color','b');\n set(H1(2),'LineWidth',2);\n\n set(H1(3),'LineStyle','--');\n set(H1(3),'Color','r');\n set(H1(3),'LineWidth',1);\n\n set(H1(4),'LineStyle',':');\n set(H1(4),'Color','r');\n set(H1(4),'LineWidth',1);\n\n\n set(H2,'LineStyle','-');\n set(H2,'Color','g');\n set(H2,'LineWidth',2);\n\n set(get(AX(2),'Ylabel'),'String','Probability of being In the Money');\n legend(H1,{['Option Price (Monte Carlo)'], ['Option Price (Black Scholes)'], ['99% Confidence interval (Lower)'],['99% Confidence interval (Upper)']},'Location','NorthEast');\n legend(H1(2),{'Option Price (Black Shcoles)'},'Location','NorthEast');\n legend(H2,{'Probability'},'Location','SouthWest');\n grid on;\nset(h,'WindowStyle','Docked');\n\n%%\nh= figure;\n [AX,H1,H2] = plotyy(ExercisePrices,[VanillaPriceDaily BLSPrices CIDaily] , ExercisePrices,ProbabilityITMDaily);\n\n\n xlabel('Exercise Price');\n title('Option prices for a Vanilla option using a 1 year - Daily volatility');\n Axes_YLabels = get(AX,'Ylabel');\n set(Axes_YLabels{1},'String','Option Price') ;\n\n set(H1(1),'LineStyle','-');\n set(H1(1),'Color','r');\n set(H1(1),'LineWidth',2);\n\n\n set(H1(2),'LineStyle','-');\n set(H1(2),'Color','b');\n set(H1(2),'LineWidth',2);\n\n\n set(H1(3),'LineStyle','--');\n set(H1(3),'Color','r');\n set(H1(3),'LineWidth',1);\n\n set(H1(4),'LineStyle',':');\n set(H1(4),'Color','r');\n set(H1(4),'LineWidth',1);\n \n\n set(H2,'LineStyle','-');\n set(H2,'Color','g');\n set(H2,'LineWidth',2);\n\n set(get(AX(2),'Ylabel'),'String','Probability of being In the Money');\n legend(H1,{['Option Price (Monte Carlo)'], ['Option Price (Black Scholes)'], ['99% Confidence interval (Lower)'],['99% Confidence interval (Upper)']},'Location','NorthEast');\n legend(H2,{'Probability'},'Location','SouthWest');\n grid on;\n set(h,'WindowStyle','Docked');\n 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/17964-monte-carlo-simulations-using-matlab/MonteCarlo/Demos/PortSim/WebinarScript.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940927, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.698565409949215}} {"text": "function f = cumsum(f, m, dim)\n%CUMSUM Indefinite integral of a TRIGTECH.\n% CUMSUM(F) is the indefinite integral of the TRIGTECH F, whose mean\n% is zero, with the constant of integration chosen so that F(-1) = 0.\n% If the mean of F is not zero then an error is thrown since the indefinite\n% integral would no longer be periodic.\n%\n% CUMSUM(F, M) will compute the Mth definite integral with the constant of\n% integration chosen so that each intermediary integral evaluates to 0 at\n% -1.\n% Thus, CUMSUM(F, 2) is equivalent to CUMSUM(CUMSUM(F)).\n%\n% CUMSUM(F, M, 2) will take the Mth cumulative sum over the columns F an\n% array-valued TRIGTECH.\n%\n% See also DIFF, SUM.\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% If the TRIGTECH G of length n is represented as\n% \\sum_{k=-(n-1)/2}^{(n-1)/2} c_k exp(i*pi*kx)\n% its integral is represented with a TRIGTECH of length n given by\n% \\sum_{k=-(n-1)/2}^{(n-1)/2} b_k exp(i*pi*kx)\n% where b_0 is determined from the constant of integration as\n% b_0 = \\sum_{k=-(n-1)/2}^{(n-1)/2} (-1)^k/(i*pi*k) c_k;\n% with c_0 := 0. The other coefficients are given by\n% b_k = c_k/(i*pi*k). \n%\n% If the TRIGTECH G of length n is represented as\n% \\sum_{k=-n/2+1}^{n/2-1} c_k exp(i*pi*kx) + c(n/2)cos(n*pi/2x)\n% then first set c(n) = 0.5*c(n) and define a = [0.5*c(n/2) c] so that we\n% have the equivalent expansion:\n% \\sum_{k=-n/2}^{n/2} a_k exp(i*pi*kx)\n% The integral of this is represented with a TRIGTECH of length n+1 given by\n% \\sum_{k=-n/2}^{n/2} b_k exp(i*pi*kx)\n% where b_0 is determined from the constant of integration as\n% b_0 = \\sum_{k=-n/2}^{n/2} (-1)^k/(i*pi*k) a_k;\n% with a_0 := 0. The other coefficients are given by\n% b_k = a_k/(ik).\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Trivial case of an empty TRIGTECH:\nif ( isempty(f) )\n return\nend\n\nif ( nargin < 2 || isempty(m) )\n % Order of integration not passed in. Assume 1 by default:\n m = 1; \nelseif ( m == 0 )\n % Nothing to do here!\n return\nend \n\n% Sum with respect to the continuous variable by default:\nif ( nargin < 3 )\n dim = 1;\nend\n\nif ( dim == 1 )\n % Take difference across 1st dimension:\n f = cumsumContinuousDim(f, m);\nelse\n % Take difference across 2nd dimension:\n f = cumsumFiniteDim(f, m);\nend\n\nend\n\nfunction f = cumsumContinuousDim(f, m)\n% CUMSUM over the continuous dimension.\n\n % Initialize storage:\n c = f.coeffs; % Obtain Fourier coefficients {c_k}\n numCoeffs = size(c,1);\n \n fIsEven = mod(numCoeffs, 2) == 0;\n\n % index of constant coefficient\n if fIsEven\n ind = numCoeffs/2 + 1;\n else\n ind = (numCoeffs + 1)/2;\n end\n\n % Check that the mean of the TRIGtech is zero. If it is not, then\n % throw an error.\n if ( any(abs(c(ind,:)) > 1e1*vscale(f)*eps) )\n error('CHEBFUN:TRIGTECH:cumsum:meanNotZero', ...\n ['Indefinite integrals are only possible for TRIGTECH objects '...\n 'with zero mean.']);\n end\n \n % Force the mean to be exactly zero.\n if ( fIsEven )\n % Set coeff corresponding to the constant mode to zero:\n c(numCoeffs/2+1,:) = 0;\n % Expand the coefficients to be symmetric (see above discussion).\n c(1,:) = 0.5*c(1,:);\n c = [c; c(1,:)];\n highestDegree = numCoeffs/2;\n else\n c((numCoeffs+1)/2,:) = 0;\n highestDegree = (numCoeffs-1)/2;\n end\n \n % Loop for integration factor for each coefficient:\n sumIndicies = (-highestDegree:highestDegree).';\n integrationFactor = (-1i./sumIndicies/pi).^m;\n % Zero out the one corresponding to the constant term.\n integrationFactor(highestDegree+1) = 0;\n c = bsxfun(@times,c,integrationFactor);\n % If this is an odd order cumsum and there are an even number of\n % coefficients then zero out the cofficient corresponding to sin(N/2x)\n % term, since this will be zero on the Fourier grid.\n if ( (mod(m, 2) == 1) && fIsEven )\n c(1,:) = 0;\n c(numCoeffs+1,:) = 0;\n end\n \n % Fix the constant term. \n c(highestDegree+1,:) = -sum(bsxfun(@times,c,(-1).^sumIndicies));\n \n % If the original TRIGTECH had an even number of coefficients then\n % shrink the coefficent vector corresponding to its indefinite integral\n % back to its original size since it was increased by one above to make\n % the integration code slicker.\n if ( fIsEven )\n c = c(1:end-1,:);\n end\n \n % Recover values and attach to output:\n f.values = f.coeffs2vals(c);\n f.values(:,f.isReal) = real(f.values(:,f.isReal));\n \n f.coeffs = c;\n\n % Simplify (as suggested in Chebfun ticket #128)\n f = simplify(f);\n \n % Ensure f(-1) = 0:\n lval = get(f, 'lval');\n f.coeffs(1,:) = f.coeffs(1,:) - lval;\n f.values = bsxfun(@minus, f.values, lval);\n \nend\n\nfunction f = cumsumFiniteDim(f, m)\n% CUMSUM over the finite dimension.\n\n for k = 1:m\n f.values = cumsum(f.values, 2);\n f.coeffs = cumsum(f.coeffs, 2);\n end\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/@trigtech/cumsum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.6985654086371353}} {"text": "function f = projectOntoBMCIII( f )\n% PROJECTONTOBMCI Projection onto BMC-III symmetry.\n%\n% f = projectOntoBMCIII(f) is the orthogonal projection of f onto BMC-III\n% symmetry, i.e., a function that is\n% 1. even in theta for every even wave number in lambda;\n% 2. odd in theta for every odd wave number in lambda;\n% Additionally, for all but k=0 wavenumber lambda the resulting projection\n% enforces the ballfun is zero at the poles. \n%\n% The projection is orthogonal, i.e., the correction matrix to fix up the\n% structure has the smallest possible Frobenius norm.\n\n% Copyright 2019 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif isempty( f )\n return\nend\n\n% Get the tensor of coefficients\nF = f.coeffs;\n\n% Permute F\nF = permute(F,[1,3,2]);\n\n% Loop over lambda\nfor l = 1:size(F,3)\n % Update the matrix\n F(:,:,l) = projectOntoRTheta(F(:,:,l));\nend\n\n% Permute back\nF = permute(F,[1,3,2]);\nf = ballfun(F, 'coeffs');\nend\n\nfunction X = projectOntoRTheta( X )\n% Project the matrix of Chebyshev--Fourier coefficients onto a BMC-II\n% function. The projection is orthogonal, i.e., the correction matrix to\n% fix up the structure has the smallest possible Frobenius norm. \n\n% Get the discretization\n[m,n] = size(X);\n\nzeroMode = floor(n/2)+1;\nevenModes = [fliplr(zeroMode-2:-2:1) zeroMode+2:2:n]; % Not including the zero mode\noddModes = [fliplr(zeroMode-1:-2:1) zeroMode+1:2:n];\n\n% First do the zero-periodic mode in theta. \n% Enforce the expansion is even in r.\nI = eye( m ); A = I(2:2:end,:); \nC = A \\ ( A * X(:,zeroMode) ); \nC = I \\ C; \n\n% Update coeff matrix: \nX(:,zeroMode) = X(:,zeroMode) - C; \n\n% Second do the even-periodic, non-zero modes in theta.\n% Enforce these are zero at the pole and that the expansion is even in \n% theta\n% Vectors [ T_k(0) ]: \nA = real( (-1i).^(0:m-1) ); % A * X should be the zero vector. \n\n% Solution to underdetermined system A*(X + Y) = 0 with smallest Frobenius\n% norm: \nC = A \\ ( A * X(:,evenModes) ); \nC = I \\ C; \nX(:,evenModes) = X(:,evenModes) - C;\n\n% Now project onto odd-anti-periodic. Nothing special has to be done at\n% the poles since enforcing the expansion is odd in r guarantees that it\n% sums to zero.\nA = I(1:2:end,:); \nC = A \\ ( A * X(:,oddModes) ); \nC = I \\ C; \nX(:,oddModes) = X(:,oddModes) - C; \nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@ballfun/projectOntoBMCIII.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197768, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.698565399366494}} {"text": "% WSUM - Weighted sum of a matrix along one dimension.\n%\n% Y = WSUM(X,W,DIM)\n%\n% X : matrix\n% W : vector of weights\n% DIM : dimension to sum along (default: first non-singleton dimension)\n%\n% When X is a 2D-matrix, one can simply use W'*X or X*W for more\n% efficient performace.\n\n% Last modified 2010-06-09\n% Copyright (c) Jaakko Luttinen (jaakko.luttinen@tkk.fi)\n\nfunction y = wsum(X,w,dim)\n\n% warning('This function seems to be inefficient..')\n\nif ~isvector(w)\n error('Weights must be given as a vector.');\nend\n\nif nargin < 3\n % Default dimension: first non-singleton dimension\n dim = find(size(X)>1, 1);\n if isempty(dim)\n dim = 1;\n end\nend\n\nif size(X,dim) ~= length(w)\n error(['The length of the weight vector does not match with the size ' ...\n 'of the matrix.']);\nend\n\ns = ones(1,max(dim,2));\ns(dim) = length(w);\ny = sum(bsxfun(@times, X, reshape(w,s)), dim);", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/algebra/wsum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6985120377877674}} {"text": "function [Phi,S,Lambda,M] = extract_eigen_functions_new(shape,k)\n \n [M,S]=laplacian([shape.X shape.Y shape.Z],shape.TRIV);\n M = diag(sum(M,2));\n [Phi,Lambda] = eigs(-S,M,k,1e-5);\n Lambda = diag(Lambda);\n [Lambda,idx] = sort(Lambda,'descend');\n Phi = Phi(:,idx);\n% PhiI = Phi'*M;\n Lambda = abs(Lambda); %added this to return positive eigen values. \n\nend\n", "meta": {"author": "OshriHalimi", "repo": "unsupervised_learning_of_dense_shape_correspondence", "sha": "440643d633a6db3f947ac71a247c8083cb3aeadc", "save_path": "github-repos/MATLAB/OshriHalimi-unsupervised_learning_of_dense_shape_correspondence", "path": "github-repos/MATLAB/OshriHalimi-unsupervised_learning_of_dense_shape_correspondence/unsupervised_learning_of_dense_shape_correspondence-440643d633a6db3f947ac71a247c8083cb3aeadc/Tools/laplacian eigendecomposition/extract_eigen_functions_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6985120257780199}} {"text": "function C=clustering_coef_bu(G)\n%CLUSTERING_COEF_BU Clustering coefficient\n%\n% C = clustering_coef_bu(A);\n%\n% The clustering coefficient is the fraction of triangles around a node\n% (equiv. the fraction of node's neighbors that are neighbors of each other).\n%\n% Input: A, binary undirected connection matrix\n%\n% Output: C, clustering coefficient vector\n%\n% Reference: Watts and Strogatz (1998) Nature 393:440-442.\n%\n%\n% Mika Rubinov, UNSW, 2007-2010\n\nn=length(G);\nC=zeros(n,1);\n\nfor u=1:n\n V=find(G(u,:));\n k=length(V);\n if k>=2 %degree must be at least 2\n S=G(V,V);\n C(u)=sum(S(:))/(k^2-k);\n end\nend", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/2019_03_03_BCT/clustering_coef_bu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6985120141592394}} {"text": "%% IPOPT PARFOR testing\nclc\nclear all\n\n%Objective\nfun = @(x) 20 + x(1)^2 + x(2)^2 - 10*(cos(2*pi*x(1)) + cos(2*pi*x(2)));\n%Constraints\nlb = [5*pi;-20*pi];\nub = [20*pi;-4*pi];\n%Setup Options\nopts = optiset('solver','ipopt');\nOpt = opti('fun',fun,'bounds',lb,ub,'opts',opts);\n\n%Generate a series of starting points\nn = 1000;\nX0 = [linspace(lb(1),lb(end),n); linspace(ub(1),ub(end),n)];\n\n%Preallocate solution vector\nsols = zeros(2,n);\nsolp = zeros(2,n);\n\n%% run serial (8.17s)\ntic\nfor i = 1:n\n sols(:,i) = solve(Opt,X0(:,i));\nend\ntoc\n\n%%\nmatlabpool(4);\n\n%% run parfor (2.6s)\ntic\nparfor i = 1:n\n solp(:,i) = solve(Opt,X0(:,i));\nend\ntoc\n\n%% check results\nerr = norm(sols-solp)", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Test Problems/Development/test_ipopt_parfor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.6985120123877084}} {"text": "function W = randInitializeWeights(L_in, L_out)\n%RANDINITIALIZEWEIGHTS Randomly initialize the weights of a layer with L_in\n%incoming connections and L_out outgoing connections\n% W = RANDINITIALIZEWEIGHTS(L_in, L_out) randomly initializes the weights \n% of a layer with L_in incoming connections and L_out outgoing \n% connections. \n%\n% Note that W should be set to a matrix of size(L_out, 1 + L_in) as\n% the column row of W handles the \"bias\" terms\n%\n\n% You need to return the following variables correctly \nW = zeros(L_out, 1 + L_in);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Initialize W randomly so that we break the symmetry while\n% training the neural network.\n%\n% Note: The first row of W corresponds to the parameters for the bias units\n%\n\n\n\nepsilon = 0.12;\nW = rand(L_out, 1 + L_in) * 2 * epsilon - epsilon;\n\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-ex4/ex4/randInitializeWeights.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.6985119211406573}} {"text": "function pinv = perm_inverse ( n, p )\n\n%*****************************************************************************80\n%\n%% PERM_INVERSE computes the inverse of a permutation.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Donald Kreher, Douglas Simpson,\n% Combinatorial Algorithms,\n% CRC Press, 1998,\n% ISBN: 0-8493-3988-X,\n% LC: QA164.K73.\n%\n% Parameters:\n%\n% Input, integer N, the number of values being permuted.\n% N must be positive.\n%\n% Input, integer P(N), describes the permutation.\n% P(I) is the item which is permuted into the I-th place\n% by the permutation.\n%\n% Output, integer PINV(N), the inverse permutation.\n%\n\n%\n% Check.\n%\n perm_check ( n, p );\n\n pinv(p(1:n)) = 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/unicycle/perm_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.8670357529306639, "lm_q1q2_score": 0.6985119115585416}} {"text": "function prob_test135 ( )\n\n%*****************************************************************************80\n%\n%% TEST135 tests SECH_CDF, SECH_CDF_INV, SECH_PDF.\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 fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST135\\n' );\n fprintf ( 1, ' For the Hyperbolic Secant PDF:\\n' );\n fprintf ( 1, ' SECH_CDF evaluates the CDF.\\n' );\n fprintf ( 1, ' SECH_CDF_INV inverts the CDF.\\n' );\n fprintf ( 1, ' SECH_PDF evaluates the PDF.\\n' );\n\n a = 3.0;\n b = 2.0;\n\n check = sech_check ( a, b );\n\n if ( ~check );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST135 - Fatal error!\\n' );\n fprintf ( 1, ' The parameters are not legal.\\n' );\n return\n end\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, ' PDF parameter A = %14f\\n', a );\n fprintf ( 1, ' PDF parameter B = %14f\\n', b );\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X PDF CDF CDF_INV\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : 10\n\n [ x, seed ] = sech_sample ( a, b, seed );\n\n pdf = sech_pdf ( x, a, b );\n\n cdf = sech_cdf ( x, a, b );\n\n x2 = sech_cdf_inv ( cdf, a, b );\n\n fprintf ( 1, ' %14f %14f %14f %14f\\n', x, pdf, cdf, x2 );\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/prob_test135.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040853, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.6985104334250914}} {"text": "function a = rutis1 ( )\n\n%*****************************************************************************80\n%\n%% RUTIS1 returns the RUTIS1 matrix.\n%\n% Example:\n%\n% 6 4 4 1\n% 4 6 1 4\n% 4 1 6 4\n% 1 4 4 6\n%\n% Properties:\n%\n% A is symmetric: A' = A.\n%\n% A is integral, therefore det ( A ) is integral, and \n% det ( A ) * inverse ( A ) is integral.\n%\n% A has constant row sums.\n%\n% Because it has a constant row sum of 15,\n% A has an eigenvalue of 15, and\n% a (right) eigenvector of ( 1, 1, 1, 1 ).\n%\n% A has constant column sums.\n%\n% Because it has a constant column sum of 15,\n% A has an eigenvalue of 15, and\n% a (left) eigenvector of ( 1, 1, 1, ..., 1 ).\n%\n% A has a repeated eigenvalue.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Joan Westlake,\n% A Handbook of Numerical Matrix Inversion and Solution of \n% Linear Equations,\n% John Wiley, 1968,\n% ISBN13: 978-0471936756,\n% LC: QA263.W47.\n%\n% Parameters:\n%\n% Output, real A(4,4), the matrix.\n%\n\n%\n% Note that the matrix entries are listed by row.\n%\n a(1:4,1:4) = [ ...\n 6.0, 4.0, 4.0, 1.0; ...\n 4.0, 6.0, 1.0, 4.0; ...\n 4.0, 1.0, 6.0, 4.0; ...\n 1.0, 4.0, 4.0, 6.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/test_mat/rutis1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914788, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.6985104212248665}} {"text": "function res = smoothPolyline(poly, M)\n%SMOOTHPOLYLINE Smooth a polyline using local averaging.\n%\n% RES = smoothPolygon(POLY, M)\n% POLY contains the polyline vertices, and M is the size of smoothing\n% (given as the length of the convolution window).\n% Extremities of the polyline are smoothed with reduced window (last and\n% first vertices are kept identical, second and penultimate vertices are\n% smoothed with 3 values, etc.).\n%\n% Example\n% img = imread('circles.png');\n% img = imfill(img, 'holes');\n% contours = bwboundaries(img');\n% poly = contours{1}(201:500,:);\n% figure; drawPolyline(poly, 'b'); hold on;\n% poly2 = smoothPolyline(poly, 21);\n% drawPolygon(poly2, 'm');\n%\n% See also \n% polygons2d, smoothPolygon, simplifyPolyline, resamplePolyline\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2015-02-17, using Matlab 8.4.0.150421 (R2014b)\n% Copyright 2015-2022 INRA - Cepia Software Platform\n\n% compute the number of elements before and after\nM1 = floor((M - 1) / 2);\nM2 = ceil((M - 1) / 2);\n\n% create convolution vector\nv2 = ones(M, 1) / M;\n\n% apply filtering on central part of the polyline\nres(:,1) = conv(poly(:,1), v2, 'same');\nres(:,2) = conv(poly(:,2), v2, 'same');\n\n% need to recompute the extremities\nfor i = 1:M1\n i2 = 2 * i - 1;\n res(i, 1) = mean(poly(1:i2, 1));\n res(i, 2) = mean(poly(1:i2, 2));\nend\nfor i = 1:M2\n i2 = 2 * i - 1;\n res(end - i + 1, 1) = mean(poly(end-i2+1:end, 1));\n res(end - i + 1, 2) = mean(poly(end-i2+1:end, 2));\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/polygons2d/smoothPolyline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.6985104192226986}} {"text": "% Computes the probability density function of the multivariate gaussian distribution.\nfunction probabilities = multivariate_gaussian(X, mu, sigma2)\n % Get number of training sets and features.\n [m n] = size(X);\n\n % Init probabilities matrix.\n probabilities = ones(m, 1);\n\n % Go through all training examples and through all features.\n for i=1:m\n for j=1:n\n p = (1 / sqrt(2 * pi * sigma2(j))) * exp(-(X(i, j) - mu(j)) .^ 2 / (2 * sigma2(j)));\n probabilities(i) = probabilities(i) * p;\n end\n end\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/anomaly-detection/multivariate_gaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533088603708, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.69848885571697}} {"text": "function value = c8_le_l2 ( x, y )\n\n%*****************************************************************************80\n%\n%% C8_LE_L2 := X <= Y for complex values, and the L2 norm.\n%\n% Definition:\n%\n% The L2 norm can be defined here as:\n%\n% C8_NORM_L2(X) = sqrt ( ( real (X) )**2 + ( imag (X) )**2 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 September 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, complex X, Y, the values to be compared.\n%\n% Output, logical VALUE, is TRUE if X <= Y.\n%\n if ( ( real ( x ) )^2 + ( imag ( x ) )^2 ...\n <= ( real ( y ) )^2 + ( imag ( y ) )^2 ) \n value = 1;\n else\n value = 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/test_mat/c8_le_l2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.6984815828066077}} {"text": "function x = discrete_sample(p, n)\n% Samples from a discrete distribution\n%\n% x = discretesample(p, n)\n% independently draws n samples (with replacement) from the \n% distribution specified by p, where p is a probability array \n% whose elements sum to 1.\n%\n% Suppose the sample space comprises K distinct objects, then\n% p should be an array with K elements. In the output, x(i) = k\n% means that the k-th object is drawn at the i-th trial.\n% \n% Remarks\n% -------\n% - This function is mainly for efficient sampling in non-uniform \n% distribution, which can be either parametric or non-parametric. \n%\n% - The function is implemented based on histc, which has been \n% highly optimized by mathworks. The basic idea is to divide\n% the range [0, 1] into K bins, with the length of each bin \n% proportional to the probability mass. And then, n values are\n% drawn from a uniform distribution in [0, 1], and the bins that\n% these values fall into are picked as results.\n%\n% - This function can also be employed for continuous distribution\n% in 1D/2D dimensional space, where the distribution can be\n% effectively discretized.\n%\n% - This function can also be useful for sampling from distributions\n% which can be considered as weighted sum of \"modes\". \n% In this type of applications, you can first randomly choose \n% a mode, and then sample from that mode. The process of choosing\n% a mode according to the weights can be accomplished with this\n% function.\n%\n% Examples\n% --------\n% % sample from a uniform distribution for K objects.\n% p = ones(1, K) / K;\n% x = discretesample(p, n);\n%\n% % sample from a non-uniform distribution given by user\n% x = discretesample([0.6 0.3 0.1], n);\n%\n% % sample from a parametric discrete distribution with\n% % probability mass function given by f.\n% p = f(1:K);\n% x = discretesample(p, n);\n%\n\n% Created by Dahua Lin, On Oct 27, 2008\n%\n\n%% parse and verify input arguments\n\nassert(isfloat(p), 'discretesample:invalidarg', ...\n 'p should be an array with floating-point value type.');\n\nassert(isnumeric(n) && isscalar(n) && n >= 0 && n == fix(n), ...\n 'discretesample:invalidarg', ...\n 'n should be a nonnegative integer scalar.');\n\n%% main\n\n% process p if necessary\n\nK = numel(p);\nif ~isequal(size(p), [1, K])\n p = reshape(p, [1, K]);\nend\n\n% construct the bins\n\nedges = [0, cumsum(p)];\ns = edges(end);\nif abs(s - 1) > eps\n edges = edges * (1 / s);\nend\n\n% draw bins\n\nrv = rand(1, n);\nc = histc(rv, edges);\nce = c(end);\nc = c(1:end-1);\nc(end) = c(end) + ce;\n\n% extract samples\n\nxv = find(c);\n\nif numel(xv) == n % each value is sampled at most once\n x = xv;\nelse % some values are sampled more than once\n xc = c(xv);\n d = zeros(1, n);\n dv = [xv(1), diff(xv)];\n dp = [1, 1 + cumsum(xc(1:end-1))];\n d(dp) = dv;\n x = cumsum(d);\nend\n\n% randomly permute the sample's order\nx = x(randperm(n));\n\n\n", "meta": {"author": "baptistar", "repo": "BOCS", "sha": "fef0d4e34e376e8bb0dae9955d70c2155530b9eb", "save_path": "github-repos/MATLAB/baptistar-BOCS", "path": "github-repos/MATLAB/baptistar-BOCS/BOCS-fef0d4e34e376e8bb0dae9955d70c2155530b9eb/algorithms/SMC_Code/discrete_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156293, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6984815691943393}} {"text": "function R=estExpDecayReliability(t,T,method)\n%%ESTEXPDECAYRELIABILITY Determine the probability that a particular\n% example of something will be functional after time T given\n% independent the failure times of n other examples under the\n% assumption that the time of failure given something is functional\n% at time zero is exponentially distributed, so the probability of\n% success (it lasting longer than T) given that it works at time zero\n% is Pr{T>t}=exp(-t/theta) for some parameter theta. \n%\n%INPUTS: t A 1Xn or nX1 vector of the times when something failed. All\n% elements should be >=0.\n% T The desired time after which a failure is acceptable. T>=0.\n% method The estimation approach. Possible values are:\n% 0 (The default if omitted or an empty matrix is passed) Use the\n% expected value estimate.\n% 1 Use the maximum likelihood estimate. This estimate is biased.\n%\n%OUTPUTS: R The probability that the system will still be operational at\n% some point after time T.\n%\n%This implements the methods of [1]. The basic reliability model is\n%R=p*P\n%where p is the probability of a failure at time 0 and P is the probability\n%of a failure between time 0 and T. THe exponential decay model applies to\n%P.\n%\n%EXAMPLE:\n%We demonstrate here that the value of R at time T is more reliable when\n%computing using method 0 than method 1 given n=30 samples of the data.\n% p=0.9;\n% T=2;\n% theta=3;\n% lambda=1/theta;\n% RTrue=p*(1-ExponentialD.CDF(T,lambda))\n% \n% numRuns=1e4;\n% R0=0;\n% R1=0;\n% for curRun=1:numRuns\n% n=30;\n% t=zeros(n,1);\n% for k=1:n\n% if(rand()0.\nt=t(sel);\nn=length(t);\n\nif(n==0)\n R=0;\n return;\nend\n\ntheta=sum(t)/n;%Equation 7.\nswitch(method)\n case 0%The expected value solution.\n R=p*(1-T/(n*theta))^(n-1);%Equation 17 (with p inserted).\n case 1%The ML solution.\n R=p*exp(-T/theta);%Equation 6 (with p inserted).\n otherwise\n error('Unknown 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/Statistics/estExpDecayReliability.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.69848156744585}} {"text": "% BOX_INTERSECT Given sets of axis-aligne boxes determine which pairs overlap.\n%\n% I = box_intersect(A1,A2)\n%\n% Inputs:\n% A1 #A by dim list of minimum corners \n% A2 #A by dim list of maximum corners \n% Outputs:\n% I #I by 2 list of indices into A such that box I(i,1) of set A intersects\n% with box I(i,2) of set A.\n% \n% I = box_intersect(A1,A2,B1,B2)\n%\n% Inputs:\n% A1 #A by dim list of minimum corners \n% A2 #A by dim list of maximum corners \n% B1 #B by dim list of minimum corners \n% B2 #B by dim list of maximum corners \n% Outputs:\n% I #I by 2 list of indices into A such that box I(i,1) of set A intersects\n% with box I(i,2) of set B.\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_gptoolbox/mex/box_intersect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6984815532507512}} {"text": "function [px, py, gx, gy] = position_5_link(z,P) \n%[px,py,gx,gy] = POSITION_5_LINK(Z,P)\n% \n%FUNCTION: This function computes the cartesian positions\n% of the CoM and tip of each link\n%INPUTS: \n%\n%\n%OUTPUTS: \n% px = [nLink X nTime] position of the end of each link\n% py = [nLink X nTime] position of the end of each link\n% gx = [nLink X nTime] position of the CoM of each link\n% gy = [nLink X nTime] position of the CoM of each link\n% \n%NOTES:\n% This file was automatically generated by writePosition.m\n\ng = P.g ; %gravity\nm1 = P.m(1); % Link 1 mass\nm2 = P.m(2); % Link 2 mass\nm3 = P.m(3); % Link 3 mass\nm4 = P.m(4); % Link 4 mass\nm5 = P.m(5); % Link 5 mass\nl1 = P.l(1); % Link 1 length\nl2 = P.l(2); % Link 2 length\nl3 = P.l(3); % Link 3 length\nl4 = P.l(4); % Link 4 length\nl5 = P.l(5); % Link 5 length\nI1 = P.I(1); % Link 1 moment of inertia about its center of mass\nI2 = P.I(2); % Link 2 moment of inertia about its center of mass\nI3 = P.I(3); % Link 3 moment of inertia about its center of mass\nI4 = P.I(4); % Link 4 moment of inertia about its center of mass\nI5 = P.I(5); % Link 5 moment of inertia about its center of mass\nd1 = P.d(1); % Link 1 distance between center of mass and parent joint\nd2 = P.d(2); % Link 2 distance between center of mass and parent joint\nd3 = P.d(3); % Link 3 distance between center of mass and parent joint\nd4 = P.d(4); % Link 4 distance between center of mass and parent joint\nd5 = P.d(5); % Link 5 distance between center of mass and parent joint\n\nth1 = z(1,:); \nth2 = z(2,:); \nth3 = z(3,:); \nth4 = z(4,:); \nth5 = z(5,:); \n\nnTime = length(th1); \npx = zeros(5,nTime);\npy = zeros(5,nTime);\ngx = zeros(5,nTime);\ngy = zeros(5,nTime);\n\npx(1,:) = l1.*cos(th1);\npy(1,:) = l1.*sin(th1);\ngx(1,:) = d1.*cos(th1);\ngy(1,:) = d1.*sin(th1);\n\npx(2,:) = l1.*cos(th1) + l2.*cos(th2);\npy(2,:) = l1.*sin(th1) + l2.*sin(th2);\ngx(2,:) = d2.*cos(th2) + l1.*cos(th1);\ngy(2,:) = d2.*sin(th2) + l1.*sin(th1);\n\npx(3,:) = l1.*cos(th1) + l2.*cos(th2) + l3.*cos(th3);\npy(3,:) = l1.*sin(th1) + l2.*sin(th2) + l3.*sin(th3);\ngx(3,:) = d3.*cos(th3) + l1.*cos(th1) + l2.*cos(th2);\ngy(3,:) = d3.*sin(th3) + l1.*sin(th1) + l2.*sin(th2);\n\npx(4,:) = l1.*cos(th1) + l2.*cos(th2) + l3.*cos(th3) + l4.*cos(th4);\npy(4,:) = l1.*sin(th1) + l2.*sin(th2) + l3.*sin(th3) + l4.*sin(th4);\ngx(4,:) = d4.*cos(th4) + l1.*cos(th1) + l2.*cos(th2) + l3.*cos(th3);\ngy(4,:) = d4.*sin(th4) + l1.*sin(th1) + l2.*sin(th2) + l3.*sin(th3);\n\npx(5,:) = l1.*cos(th1) + l2.*cos(th2) + l3.*cos(th3) + l4.*cos(th4) + l5.*cos(th5);\npy(5,:) = l1.*sin(th1) + l2.*sin(th2) + l3.*sin(th3) + l4.*sin(th4) + l5.*sin(th5);\ngx(5,:) = d5.*cos(th5) + l1.*cos(th1) + l2.*cos(th2) + l3.*cos(th3) + l4.*cos(th4);\ngy(5,:) = d5.*sin(th5) + l1.*sin(th1) + l2.*sin(th2) + l3.*sin(th3) + l4.*sin(th4);\n\n\nend \n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/LagrangeMechanics/nLinkPendulum/position_5_link.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.754914997895581, "lm_q1q2_score": 0.6984699726674801}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Setting up advection-diffusion solver\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction C = please_Update_Adv_Diff_Concentration_Unsplit(C,dt,dx,dy,uX,uY,k)\n\n% C: concentration \n% dt: time-step\n% dx,dy: spatial steps in x and y, respectively\n% uX: x-Component of Velocity\n% uY: y-Component of Velocity\n% k: diffusion coefficient\n\n% Compute Necessary Derivatives (Note: these calculations could be parallalized)\nCx = give_Necessary_Derivative(C,dx,uX,'x');\nCy = give_Necessary_Derivative(C,dy,uY,'y'); \nCxx = DD(C,dx,'x');\nCyy = DD(C,dy,'y');\n \n% Update Concentration \n%C = C + dt * ( k*(Cxx+Cyy) - uX'.*Cx - uY'.*Cy );\n\nC = C + dt * ( k*(Cxx+Cyy) - uX.*Cx - uY.*Cy );\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Computes derivative based on sign of Velocity, u, using UPWIND\n% approach\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction C_z = give_Necessary_Derivative(C,dz,uZ,string)\n\nC_z = zeros(size(C));\nlen = length(uZ(:,1));\nsigns = sign(uZ);\n\nif strcmp(string,'x')\n\n %For periodicity on ends w/ UPWIND\n for i=1:len\n\n %left side of grid\n if signs(i,1) <= 0 \n C_z(i,1) = ( C(i,2) - C(i,1) ) / (dz);\n else\n C_z(i,1) = ( C(i,1) - C(i,len) ) / (dz);\n end\n\n %right side of grid\n if signs(i,len) <= 0 \n C_z(i,len) = ( C(i,1) - C(i,len) ) / (dz);\n else\n C_z(i,len) = ( C(i,len) - C(i,len-1) ) / (dz);\n end\n\n end\n \n %Standard Upwind \n for i=1:len\n for j=2:len-1\n if signs(i,j) <= 0\n C_z(i,j) = ( C(i,j+1) - C(i,j) ) / (dz);\n else\n C_z(i,j) = ( C(i,j) - C(i,j-1) ) / (dz);\n end\n end\n end\n\n % Ends x-Direction calculation %\n \nelseif strcmp(string,'y') \n\n %For periodicity on ends w/ UPWIND\n for i=1:len\n\n %bottom of grid\n if signs(1,i) <= 0 \n C_z(1,i) = ( C(2,i) - C(1,i) ) / (dz);\n else\n C_z(1,i) = ( C(1,i) - C(len,i) ) / (dz);\n end\n\n %top of grid\n if signs(len,i) <= 0 \n C_z(len,i) = ( C(1,i) - C(len,i) ) / (dz);\n else\n C_z(len,i) = ( C(len,i) - C(len-1,i) ) / (dz);\n end\n\n end\n \n %Standard Upwind\n for i=2:len-1\n for j=1:len\n if signs(i,j) <= 0\n C_z(i,j) = ( C(i+1,j) - C(i,j) ) / (dz);\n else\n C_z(i,j) = ( C(i,j) - C(i-1,j) ) / (dz);\n end\n end\n end\n\n % Ends y-Direction calculation %\n \nelse\n \n fprintf('\\n\\n\\n ERROR IN FUNCTION D FOR COMPUTING 1ST DERIVATIVE\\n');\n fprintf('Need to specify which desired derivative, x or y.\\n\\n\\n'); \n \nend\n \nclear signs; clear len;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Finds CENTERED finite difference approximation to 2ND\n% DERIVATIVE in z direction, specified by input and 'string' \n% Note: It automatically accounts for periodicity of the domain.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction u_zz = DD(u,dz,string)\n\n% u: velocity \n% dz: spatial step in \"z\"-direction\n% string: specifies which 2ND derivative to take (to enforce periodicity)\n\nlen = length(u(:,1));\n\nif strcmp(string,'x')\n\n %For periodicity on ends\n u_zz(:,1) = ( u(:,2) - 2*u(:,1) + u(:,len) ) / (dz^2);\n u_zz(:,len)= ( u(:,1) - 2*u(:,len) + u(:,len-1) ) / (dz^2);\n\n %Standard Upwind Scheme (Centered Difference)\n for j=2:len-1\n u_zz(:,j) = ( u(:,j+1) - 2*u(:,j) + u(:,j-1) ) / (dz^2);\n end\n\nelseif strcmp(string,'y')\n\n %For periodicity on ends\n u_zz(1,:) = ( u(2,:) - 2*u(1,:) + u(len,:) ) / (dz^2);\n u_zz(len,:)= ( u(1,:) - 2*u(len,:) + u(len-1,:) ) / (dz^2);\n\n %Standard Upwind Scheme (Centered Difference)\n for j=2:len-1\n u_zz(j,:) = ( u(j+1,:) - 2*u(j,:) + u(j-1,:) ) / (dz^2);\n end\n\nelse\n \n fprintf('\\n\\n\\n ERROR IN FUNCTION DD FOR COMPUTING 2ND DERIVATIVE\\n');\n fprintf('Need to specify which desired derivative, x or y.\\n\\n\\n'); \n \nend\n\n\n\n", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Testing/Advection_Diffusion/please_Update_Adv_Diff_Concentration_Unsplit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.698469964020503}} {"text": "function [Ex Ey Ez] = MiePECBall(cart, k, R, N)\n% The code caculates the time-harmonic scattered field value at point 'cart' \n% due to a PEC ball with radius R centered at the origin. \n% The incident wave is E=exp(-ikz).\n% The formulation is based on H.C. van de Hulst, P123\n% 'light scattering by small particles', Dover, 1981\n% Input: cart -- cartiesian coordiante (1x3) of the point ouside the ball\n% k -- wavenumber\n% R -- radius of the PEC ball\n% N -- number of terms used in Mie series\n% Output: [Ex Ey Ez] -- the scattering electric field\n% Author: Jiguang Sun, 02/13/2011, jsun@desu.edu\n% Please report bugs to jsun@desu.edu\n% Copyright (c) 2011, Jiguang Sun, rights reserved. \n% THIS SOFTWARE IS PROVIDED \"AS IS\".\n% Redistribution and use in source and binary forms, with or without \n% modification, are permitted.\ni = sqrt(-1); \n[phi,th,r] = cart2sph(cart(1), cart(2), cart(3)); th = pi/2-th;\nif r < R\n % disp('The point is inside the ball!')\n Ex = 0; Ey = 0; Ez = 0;\n return;\nend\n\nn = 1:N+2; \nx = k*R; \n[j(n), ierr(1,n)] = besselj(n - 1 + 1/2, x); j = j*sqrt(pi/(2*x));\n[h(n), ierr(1,n)] = besselh(n - 1 + 1/2, 2, x); h = h*sqrt(pi/(2*x));\nif any(any(ierr)) \n disp('Accuracy error in a Bessel or Hankel function.');\n Ex = 0; Ey = 0; Ez = 0;\n return;\nend\n% scattering coefficients\nan = j(2:N+1)./h(2:N+1);\nbn = (j(2:N+1)+k*R*j(1:N)-k*R*j(3:N+2))./(h(2:N+1)+k*R*h(1:N)-k*R*h(3:N+2));\n% various terms ralated to Racati-Bessel's functions\nn = 1:N+4;\nz = k*r; k2r = k^2*r;\n[h(n), ierr(2,n)] = besselh(n - 2 + 1/2, 2, z); h = h*sqrt(pi/(2*z));\nhn = h(3:N+2);\ndrh = (h(3:N+2)+k*r*h(2:N+1)-k*r*h(4:N+3))/2;\nddrh=(k2r*h(1:N)+2*k*h(2:N+1)-(1/r+2*k2r)*h(3:N+2)-2*k*h(4:N+3)+k2r*h(5:N+4))/4;\n% \nif any(any(ierr)) \n disp('Accuracy error in a Bessel or Hankel function.')\n Ex = 0; Ey = 0; Ez = 0;\n return;\nend\n% various terms related to associated Legendre polynomials\nPn(1) = 1;\nPn(2) = cos(th);\nfor n=2:N-1\n Pn(n+1) = ((2*n-1)*cos(th)*Pn(n)-(n-1)*Pn(n-1))/n;\nend\n% Pn1 starts from n = 1.\nPn1(1) = -sin(th);\nPn1(2) = -3.0*sin(th)*cos(th);\nfor n=2:N-1\n Pn1(n+1) = (2.0*n+1)*cos(th)*Pn1(n)/n-(n+1)*Pn1(n-1)/n;\nend\n% Pn1S starts from n = 1;\nPn1S(1) = -1;\nPn1S(2) = -3.0*cos(th);\nfor n = 2:N-1\n Pn1S(n+1) = Pn1S(n-1)-(2*n+1)*Pn(n+1);\nend\n\nfor n = 1:N\n if n == 1\n dPn1(n) = -cos(th);\n elseif n == 2\n dPn1(n) = 3*(2*sin(th)*sin(th)-1);\n else\n dPn1(n) = (2*n-1)/(n-1)*Pn1(n-1)*(-sin(th))+(2*n-1)/(n-1)*cos(th)*dPn1(n-1)-n/(n-1)*dPn1(n-2);\n end\nend\n% compute M and N\nMrho = 0; Mth = 0; Mphi = 0;\nfor n = 1:N\n c = (-i)^(n)*(2*n+1)/(n*(n+1));\n Mth = Mth + c*an(n)*hn(n)*Pn1S(n)*cos(phi);\n Mphi = Mphi-c*an(n)*hn(n)*dPn1(n)*sin(phi);\nend\nNrho = 0; Nth = 0; Nphi = 0;\nfor n = 1:N\n c = (-i)^(n)*(2*n+1)/(n*(n+1));\n Nrho = Nrho + bn(n)*c*(ddrh(n)+k^2*r*hn(n))*Pn1(n)*cos(phi)/(k);\n Nth = Nth + bn(n)*c/r*drh(n)*dPn1(n)*cos(phi)/(k);\n Nphi = Nphi + bn(n)*c/r*drh(n)*Pn1S(n)*(-sin(phi))/(k);\nend\n% compute scattering field in Spherical coordinate\nErho = Mrho + i*Nrho;\nEphi = Mphi + i*Nphi;\nEth = Mth + i*Nth;\n% change back to cartisian coordinate\nEx = Erho*sin(th)*cos(phi)+Eth*cos(th)*cos(phi)-Ephi*sin(phi);\nEy = Erho*sin(th)*sin(phi)+Eth*cos(th)*sin(phi)+Ephi*cos(phi);\nEz = Erho*cos(th)-Eth*sin(th);", "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/30922-scattered-field-of-a-pec-ball/MiePECBall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229959153748, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6984699573623916}} {"text": "%% RATE OF CONVERGENCE OF MIXED FINITE ELEMENT METHOD IN 2D\n%\n% This example is to show the rate of convergence of mixed finite element\n% (RT0-P0) approximation of the Poisson equation on the unit square:\n%\n% $$- \\Delta u = f \\; \\hbox{in } (0,1)^2$$\n%\n% for the following boundary condition:\n%\n% # Pure Dirichlet boundary condition. $\\Gamma _D = \\partial \\Omega$. \n% # Pure Neumann boundary condition. $\\Gamma _N = \\partial \\Omega$.\n% # Mix Dirichlet and Neumann boundary condition. $u=g_D \\hbox{ on }\\Gamma_D, \n% \\quad \\nabla u\\cdot n=g_N \\hbox{ on }\\Gamma_N. \\Gamma _N = \\{(x,y): x=0, \n% y\\in [0,1]\\}, \\; \\Gamma _D = \\partial \\Omega \\backslash \\Gamma _N$. \n%\n% Written by Ming Wang.\n\n%% \nclear all; close all;\n[node,elem] = squaremesh([0,1,0,1],0.25); \npde = mixBCdata;\noption.L0 = 2;\noption.maxIt = 4;\noption.printlevel = 1;\noption.elemType = 'RT0-P0';\n% option.solver = 'uzawapcg';\noption.solver = 'dmg';\n\n%% Pure Dirichlet boundary condition.\n% option.plotflag = 0;\nbdFlag = setboundary(node,elem,'Dirichlet');\nmfemPoisson3(node,elem,pde,bdFlag,option);\n\n%% Pure Neumann boundary condition.\n% option.plotflag = 0;\nbdFlag = setboundary(node,elem,'Neumann');\nmfemPoisson(node,elem,pde,bdFlag,option);\n\n%% Mix Dirichlet and Neumann boundary condition.\noption.plotflag = 1;\noption.solver = 'uzawapcg';\nbdFlag = setboundary(node,elem,'Dirichlet','~(x==0)','Neumann','x==0');\nmfemPoisson(node,elem,pde,bdFlag,option);\n\n%% Conclusion\n%\n% The optimal rates of convergence for u and sigma are observed, namely,\n% 1st order for L2 norm of u, L2 norm of sigma and H(div) norm of sigma. \n% The 2nd order convergent rates between two discrete functions ||uI-uh|| \n% and ||sigmaI-sigmah|| are known as superconvergence.\n%\n% dmg and uzawapcg converges uniformly in all cases. Distributive MG is two\n% times faster than uzawapcg.", "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/mfemrate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6982585554920943}} {"text": "function lattice_rule_test07 ( )\n\n%*****************************************************************************80\n%\n%% LATTICE_RULE_TEST07 tests LATTICE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 November 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Ian Sloan, Stephen Joe,\n% Lattice Methods for Multiple Integration,\n% Oxford, 1994, page 18.\n%\n dim_num = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LATTICE_RULE_TEST07\\n' );\n fprintf ( 1, ' LATTICE applies a lattice rule to integrate\\n' );\n fprintf ( 1, ' a function over the unit hypercube.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The spatial dimension DIM_NUM = %d\\n', dim_num );\n fprintf ( 1, ' The lattice rule order M will vary.\\n' );\n\n z(1:dim_num) = [ 1, 2 ];\n a(1:dim_num) = 0.0;\n b(1:dim_num) = 1.0;\n\n i4vec_print ( dim_num, z, ' The lattice generator vector:' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I M EXACT ESTIMATE ERROR\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : 10\n\n m = prime ( 3 * i );\n\n quad = lattice ( dim_num, m, z, @f_01_2d );\n\n exact = e_01_2d ( dim_num, a, b );\n\n error = abs ( exact - quad );\n\n fprintf ( 1, ' %8d %8d %10.6f %10.6f %10.6e\\n', i, m, exact, quad, error );\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/lattice_rule/lattice_rule_test07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.6982585418416264}} {"text": "% This is a demo for segmentation using local gaussian distribution (LGD)\n% fitting energy\n%\n% Reference:
  • \n%\n% Please DO NOT distribute this code to anybody.\n% Copyright (c) by Li Wang\n%\n% Author: Li Wang\n% E-mail: li_wang@med.unc.edu\n% URL: http://www.unc.edu/~liwa/\n%\n% 2010-01-02 PM\n\n\n\nclc;clear all;close all;\n\nImg=imread('1.bmp');\nImg = double(Img(:,:,1));\n\nNumIter = 300; %iterations\ntimestep=0.1; %time step\nmu=0.1/timestep;% level set regularization term, please refer to \"Chunming Li and et al. Level Set Evolution Without Re-initialization: A New Variational Formulation, CVPR 2005\"\nsigma = 3;%size of kernel\nepsilon = 1;\nc0 = 2; % the constant value \nlambda1=1.0;%outer weight, please refer to \"Chunming Li and et al, Minimization of Region-Scalable Fitting Energy for Image Segmentation, IEEE Trans. Image Processing, vol. 17 (10), pp. 1940-1949, 2008\"\nlambda2=1.0;%inner weight\n%if lambda1>lambda2; tend to inflate\n%if lambda1.\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/Math/gauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6982486198703116}} {"text": "function pde = oscdiffdata3\n\npde = struct('f',1,'d',@d);\n\n function K = d(p) % Diffusion constant\n x = p(:,1); y = p(:,2); z = p(:,3); \n K = 2*(2+sin(10*pi*x).*cos(10*pi*y)*sin(20*pi*z));\n end\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/data/oscdiffdata3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6981750997461124}} {"text": "function showrateh3(h1,err1,k1,opt1,str1,h2,err2,k2,opt2,str2,h3,err3,k3,opt3,str3)\n%% SHOWRATEH3 rate of two error sequences\n%\n% showrate3(N1,err1,k1,opt1,str1,N2,err2,k2,opt2,str2,N3,err3,k3,opt3,str3)\n% plots the err1 vs N1, err2 vs N2, and err3 vs N3 in the loglog scale.\n% Additional input\n%\n% - k1, k2, k3: specify the starting indices; see showrate\n% - opt1, opt2, opt3: the line color and style \n% - str1, str2, str3: strings used in legend\n%\n% Example\n%\n% showrate2(N,energyErr,1,'r-+','||u-u_h||_A',...\n% N,L2Err,1,'b-+','||u-u_h||');\n%\n% See also showrate, showresult, showmesh, showsolution\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nN1 = 1./h1; N2 = 1./h2; N3 =1./h3;\nif (nargin<=2) \n k1 = 1; opt1 = '-*';\nend\nr1 = showrate(N1,err1,k1,opt1);\nhold on\nr2 = showrate(N2,err2,k2,opt2);\nr3 = showrate(N3,err3,k3,opt3);\nh_legend = legend(str1,['C_1h^{' num2str(-r1) '}'],...\n str2,['C_2h^{' num2str(-r2) '}'],...\n str3,['C_3h^{' num2str(-r3) '}'],'LOCATION','Best');\nset(h_legend,'FontSize',12);\nxlabel('log(1/h)');\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/tool/showrateh3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.6981715208019194}} {"text": "function [idx, dist]=closestnode(node,p)\n%\n% [idx, dist]=closestnode(node,p)\n%\n% Find the closest point in a node list and return its index\n\n% author: Qianqian Fang (q.fang at neu.edu)\n%\n% input:\n% node: each row is an N-D node coordinate\n% p: a given position in the same space\n%\n% output:\n% idx: the index of the position in the node list that has the shortest\n% Euclidean distance to the position p\n% dist: the distances between p and each node\n%\n%\n% -- this function is part of brain2mesh toolbox (http://mcx.space/brain2mesh)\n% License: GPL v3 or later, see LICENSE.txt for details\n%\n\ndd=node-repmat(p,size(node,1),1);\n[dist,idx]=min(sum(dd.*dd,2));\n", "meta": {"author": "fangq", "repo": "iso2mesh", "sha": "556f4c321467a3ee042d4c559b4edc11e01dc574", "save_path": "github-repos/MATLAB/fangq-iso2mesh", "path": "github-repos/MATLAB/fangq-iso2mesh/iso2mesh-556f4c321467a3ee042d4c559b4edc11e01dc574/closestnode.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7956581024858785, "lm_q1q2_score": 0.6981715208019192}} {"text": "% program demo_tutor.m\n%\n% P.M.T. Broersen, July 2004\n% June 2005 \n% P.M.T. Broersen, November 2007\n\n% see also demo_armasa for extensive example\n% demo_simple for basic example PSD and autocorrelation computation \n%\n% Background information can be found in\n\n% Book:\n% Piet M.T. Broersen\n% Automatic Autocorrelation and Spectral Analysis\n% Springer-Verlag,London, 2006.\n% ISBN 1-84628-328.\n\n% Journal paper:\n% P. M. T. Broersen, Automatic Spectral Analysis with\n% Time Series Models, IEEE Transactions on Instrumentation\n% and Measurement, Vol. 51, No. 2, April 2002, pp. 211-216.\n% \n% and many papers given in ARMASA info.txt\n\nclc,\nclose all\nclear all\necho on \n\n% Generate stationary AR en MA polynomials a and b from reflection coefficients smaller than 1\n% By taking reflection coefficients between -1 and +1, stationary invertible\n% models are guaranteed with all poles and zeros inside the unit circle\n% Reflection coefficients are transformed into parameters with rc2arset:\n%\n\na = rc2arset([1 .3 .3])\n\nb = rc2arset([1 -.9])\n\n% From reflection coefficients to parameters and vice versa\n[dum rc] = ar2arset(a)\n\nN = 500; \n\n% Generating data by starting with initial zeros is a poor idea.\n% Simuarma generates N stationary data, with the asymptotical properties \n% applicable from the first observation\n\ndata = simuarma(a,b,N);\n\n% Compute and select time series models, \n% with asel and bsel as parameters of the selected model\n% Compute the accuracy of the selected model type and the best alternative\n% model types and put them in sellog\n \n[asel bsel sellog] = armasel(data)\n \n% Compute the accuracy of the estimated model in comparison with \n% the true process with the parameters a and b\n\nME = moderr(asel,bsel,a,b,N)\n\n% Compute and plot the autocorrelation functions and spectra of the\n% generating true model and the ARMAsel selected model.\n% gain is the power gain or the ratio between output and input variance of ARMA process\n% The length of the correlation function is chosen as 50.\n%\n[cortrue gain] = arma2cor(a,b,50);\ncorsel = arma2cor(asel,bsel,50);\n[psdtrue fas] = arma2psd(a,b);\npsdsel = arma2psd(asel,bsel); \n\necho off\n\nfigure(1),\nplot(data),\nxlabel('\\rightarrow time axis [s]')\ntitle([int2str(N),' ARMA(2,1) observations'])\n\nfigure(2),\nplot(0:50,cortrue,0:50,corsel,'r')\ntitle('True and estimated autocorrelation function')\nxlabel('\\rightarrow time lag [s]')\nlegend('true','estimated')\n\nfigure(3),\nsubplot(121),\nplot(fas,psdtrue,fas,psdsel,'r')\ntitle('True and estimated spectrum')\nxlabel('\\rightarrow normalized frequency \\it{f/f_s}'),\nlegend('true','estimated',2)\nylabel('Lineair scale for PSD'),\naxis tight\nsubplot(122),\nsemilogy(fas,psdtrue,fas,psdsel,'r')\ntitle('True and estimated spectrum')\nxlabel('\\rightarrow normalized frequency \\it{f/f_s}'),\nlegend('true','estimated',4)\nylabel('Log scale for PSD'),\naxis tight, \nsubplot,\n\nfigure(4),\necho on\n\n% The spectra on a linear scale are hardly to discern for high frequencies.\n% That improves with a logaritmic scale.\n% The frequency axis is between 0 and fs/2, where fs is the sampling frequency.\n% Very often, fs is taken as 1 without mentioning it.\n%\n% Investigate the accuracy as estimated by ARMAsel for all models\n% That accuracy is stored in sellog in pe_est files\n% The accuracy of all models can be interpreted as the language of random data\n%\n% This example demonstrates how axis can be generated automatically for a\n% properly scaled plot of the prediction errors\n%\nplot(sellog.ar.cand_order,sellog.ar.pe_est)\ntitle('Estimated model accuracies as a function of model order and type')\nxlabel('\\rightarrow model order \\itr')\nylabel('\\rightarrow normalized model accuracy')\nminar=min(sellog.ar.pe_est); \nas2=axis; \nas2(3)=.9*minar; \nas2(4)=sellog.ar.pe_est(end);\naxis(as2);\nhold on, \nplot(sellog.ma.cand_order,sellog.ma.pe_est,'r')\nplot(sellog.arma.cand_ar_order,sellog.arma.pe_est,'g')\nlegend('AR(\\itr\\rm)','MA(\\itr\\rm)','ARMA(\\itr,r\\rm-1)',4), \nhold off, \n\n% A similar result in one line can be obtained with plotpe(sellog),\n% where sellog is the third output argument of armasel\n\nplotpe(sellog)\n\n% Retrieve the reflection coefficients of the longest AR model that has been used in ARMAsel\n% The longest AR model is allways saved as ASAglob_rc!!\n%\n% Recent versions of ARMASA (after 2008) save that model additionally as sellog.ar.rcarlong\n%\nrcarlong = ASAglobretr('ASAglob_rc');\n\n% Determine the highest AR order that has been estimated with ARMAsel. \n% Transform reflection coefficients rcarlong into a parameter vector.\n% Plot spectrum (PSD) and autocorrelation function of selected and of long model.\n%\n% The correlation function and the PSD of the long model arlong\n% are very irregular.\n% Selection of the model order and type gives results with only\n% statisatically significant details included.\n%\nmaximum_order = length(rcarlong)-1\narlong = rc2arset(rcarlong); \ncorlang = arma2cor(arlong,1,50);\npsdlang = arma2psd(arlong,1); echo off\n\n% In arma2cor and arma2psd, 1 is used as the second parameter vector. \n% That is the MA vector for true AR processes.\n% The programs expect both an AR and a MA parameter vector.\n% The first element of the parameter vector must always be 1.\n% That can be the only parameter of the vector.\n\nfigure,\nplot(0:50,cortrue,0:50,corsel,0:50,corlang)\ntitle('True and estimated autocorrelation function')\nxlabel('\\rightarrow time lag [s]'),\nlegend('true','estimated','ARlong')\n\n% Linear and logarithmic spectra of the same data demonstrate a strong \n% preference for logarithmic plots of the PSD (power spectral density)\n\nfigure,\nsubplot(121),\nplot(fas,psdtrue,fas,psdsel,fas,psdlang)\ntitle('True and estimated spectrum')\nxlabel('\\rightarrow normalized frequency \\it{f/f_s}'),\nlegend('true','estimated','ARlong',2)\nylabel('Linear scale for PSD'),\naxis tight\nsubplot(122),\nsemilogy(fas,psdtrue,fas,psdsel,fas,psdlang)\ntitle('True and estimated spectrum')\nxlabel('\\rightarrow normalized frequency \\it{f/f_s}'),\nlegend('true','estimated','ARlong',4)\nylabel('Log scale for PSD'),\naxis tight, \nsubplot \n\necho on\n\n% Demo of variation of input variables for candidate orders\n% Computation of models with prescribed type and order\n%\necho off\ndisp('AR(10) with ar10 = armasel(data,10,0,0)')\nar10 = armasel(data,10,0,0), % AR(10)\ndisp(' ')\ndisp('AR selected from orders between 2 and 20 with arselect= armasel(data,2:20,0,0)')\narselect = armasel(data,2:20,0,0), % AR(selected between candidate orders 2 and 20)\ndisp(' ')\ndisp('AR(10) with ar10fromarlong = rc2arset(rcarlong,10)')\nar10fromarlong = rc2arset(rcarlong,10) % AR(10) computed with first 10 reflection coefficients\ndisp(' ')\ndisp('MA(6) model with ma6 = armasel(data,0,6,0)')\n[dummy ma6] = armasel(data,0,6,0), % MA(6)\ndisp(' ')\ndisp('ARMA(2,1) model with armasel(data,0,0,2)')\n[ar2 ma1] = armasel(data,0,0,2), % ARMA(2,1) \ndisp(' ')\ndisp('ARMA(4,3) model with armasel(data,0,0,4)')\n[ar4 ma3] = armasel(data,0,0,4), % ARMA(4,3)\ndisp(' ')\ndisp('Selection between candisdates AR(2), MA(3) and ARMA(5,4) with armasel(data,2,3,5)')\n[arx brx] = armasel(data,2,3,5) % selects between the candidates AR(2), MA(3) and ARMA(5,4) \ndisp(' ')\n\n% Accuracy of these models and of the selected model\n\ndisp(['ARMAsel selected from all candidates for N = ',int2str(N),' observations: ARMA(', ...\n int2str(length(asel)-1),',',int2str(length(bsel)-1),')']) \nME_selected = moderr(asel,bsel,a,b,N)\nME_ar10 = moderr(ar10,1,a,b,N)\nME_ma6 = moderr(1,ma6,a,b,N)\nME_arma21 = moderr(ar2,ma1,a,b,N)\nME_arma43 = moderr(ar4,ma3,a,b,N)\nME_arlong = moderr(arlong,1,a,b,N)\n\necho on,\n\n% Prediction of the observations after the data with the selected model with arma2pred \n% Lpred is the prediction horizon\n% Normalizing the accuracy with the power gain\n% Take care because the mean has been subtracted automatically, \n% it should be added again for a correct prediction of the future \n% pred_acc is the variance of the predictions\n% asel and bsel have been found before with armasel in line 35\n%\nLpred = 15\n[pred pred_acc] = arma2pred(asel,bsel,data,Lpred);\n[corsel gainsel]= arma2cor(asel,bsel)\npred_acc = pred_acc*std(data)^2/gainsel; echo off\n\nfigure, \nplot(0:Lpred,[data(end) pred+mean(data)],'r*',1:Lpred, ...\n pred+1.96*sqrt(pred_acc)+mean(data),1:Lpred,pred-1.96*sqrt(pred_acc)+mean(data))\ntitle('Prediction for \\it{t > N} \\rmof continuation of data \\it{x_n}\\rm , with 95 % confidence interval')\nxlabel('\\rightarrow Prediction starting with the last observation \\it{x_N} \\rmof the data') \n\necho on,\n\n%\n% Using reduced statistics \n%\n% REDUCED STATISTICS REDUCED STATISTICS REDUCED STATISTICS REDUCED STATISTICS\n%_____________________________________________________________________________\n%\n% Computes the best model for the data if only a long AR model is available\n% and the sample size N of the observations that were used to compute the long AR model \n% Generally, there is a only small difference between ARMA models estimated from data and \n% ARMA models estimated with reduced statistics.\n% \n%\n% S. de Waele \n% Automatic Spectral Analysis,\n% This and more extensions of ARMASA can be found under \n% spectral analysis at the download address\n% http: www.mathworks.com/matlabcentral/fileexchange/\n\n% Also programs for equidistant data where some data are missing can be\n% found and programs for irregular data, all at various places in \n% http: www.mathworks.com/matlabcentral/fileexchange/\n% by the authors Piet Broersen and Stijn de Waele\n%\n% An error message can be found if the additional software is not down loaded\n%\necho off\n\ntry\n disp('The model selected from armasel applied to the data was')\n asel\n bsel\n disp(' ')\n disp(' [asel_rs bsel_rs sellog_rs] = armasel_rs(arlong,N) gives:')\n disp(' ')\n [asel_rs bsel_rs sellog_rs] = armasel_rs(arlong,N)\n disp(' ')\n disp(' The accuracy of the selected reduced statistics model')\n ME_rs = moderr(asel_rs,bsel_rs,a,b,N)\n disp(' ')\n disp(' The difference between the selected data model and the reduced statistics model')\n ME_dif = moderr(asel_rs,bsel_rs,asel,bsel,N)\n\n disp(' ')\n disp(' Computation of the ARMA(3,2) model with the reduced statistics algorithm')\n disp(' ')\n [a_rs b_rs sellog32_rs] = armasel_rs(arlong,N,0,0:1,3) %ARMA(3,2)\n disp(' ')\n disp(' The accuracy of the ARMA(3,2) model')\n ME_arma32_rs = moderr(a_rs,b_rs,a,b,N)\n\n % some care is required for giving a fixed MA or ARMA order in armasel_rs\n % using only candidate order 0 might give error messages\n % the example shows how those messages are suppressed\ncatch\n disp(' The program armasel_rs requires additional software of Stijn de Waele')\n disp(' Automatic Spectral Analysis')\n disp(' This can be found under spectral analysis at the download address')\n disp(' http: www.mathworks.com/matlabcentral/fileexchange/')\nend\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/1330-armasa/ARMASA/demo_tutor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985636, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.6981372606932558}} {"text": "function point_num = sparse_grid_f2s_size ( dim_num, level_max )\n\n%*****************************************************************************80\n%\n%% SPARSE_GRID_F2S_SIZE sizes a sparse grid using Fejer Type 2 Slow rules.\n%\n% Discussion:\n%\n% The grid is defined as the sum of the product rules whose LEVEL\n% satisfies:\n%\n% 0 <= LEVEL <= LEVEL_MAX.\n%\n% This calculation is much faster than a previous method. It simply\n% computes the number of new points that are added at each level in the\n% 1D rule, and then counts the new points at a given DIM_NUM dimensional\n% level vector as the product of the new points added in each dimension.\n%\n% This approach will work for nested families, and may be extensible\n% to other families, and to mixed rules.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 26 December 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer LEVEL_MAX, the maximum value of LEVEL.\n%\n% Output, integer POINT_NUM, the total number of unique \n% points in the grids.\n%\n\n%\n% Special case.\n%\n if ( level_max < 0 )\n point_num = 0;\n return\n end\n\n if ( level_max == 0 )\n point_num = 1;\n return\n end\n%\n% Construct the vector that counts the new points in the 1D rule.\n%\n new_1d = zeros ( level_max+1, 1 );\n\n new_1d(0+1) = 1;\n\n p = 1;\n o = 1;\n\n for l = 1 : level_max\n p = 2 * l + 1;\n if ( o < p )\n new_1d(l+1) = o + 1;\n o = 2 * o + 1;\n else\n new_1d(l+1) = 0;\n end\n end\n%\n% Count the number of points by counting the number of new points \n% associated with each level vector.\n%\n level_1d = zeros ( dim_num, 1 );\n\n point_num = 0;\n\n for level = 0 : level_max\n\n more = 0;\n h = 0;\n t = 0;\n\n while ( 1 )\n\n [ level_1d, more, h, t ] = comp_next ( level, dim_num, level_1d, more, h, t );\n\n point_num = point_num + prod ( new_1d(level_1d(1:dim_num)+1) );\n\n if ( ~more )\n break\n end\n\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_open/sparse_grid_f2s_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.6980327219474746}} {"text": "function himmelblau_test ( )\n\n%*****************************************************************************80\n%\n%% HIMMELBLAU_TEST works with the Himmelblau function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HIMMELBLAU_TEST:\\n' );\n fprintf ( 1, ' Test COMPASS_SEARCH with the Himmelblau function.\\n' );\n m = 2;\n delta_tol = 0.00001;\n delta = 0.3;\n k_max = 20000;\n\n x = [ 1.0, 1.0 ];\n r8vec_print ( m, x, ' Initial point X0:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X0) = %g\\n', himmelblau ( m, x ) );\n\n [ x, fx, k ] = compass_search ( @himmelblau, m, x, delta_tol, delta, k_max );\n r8vec_print ( m, x, ' Estimated minimizer X1:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X1) = %g, number of steps = %d\\n', fx, k );\n\n x = [ -1.0, 1.0 ];\n r8vec_print ( m, x, ' Initial point X0:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X0) = %g\\n', himmelblau ( m, x ) );\n\n [ x, fx, k ] = compass_search ( @himmelblau, m, x, delta_tol, delta, k_max );\n r8vec_print ( m, x, ' Estimated minimizer X1:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X1) = %g, number of steps = %d\\n', fx, k );\n\n x = [ -1.0, -1.0 ];\n r8vec_print ( m, x, ' Initial point X0:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X0) = %g\\n', himmelblau ( m, x ) );\n\n [ x, fx, k ] = compass_search ( @himmelblau, m, x, delta_tol, delta, k_max );\n r8vec_print ( m, x, ' Estimated minimizer X1:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X1) = %g, number of steps = %d\\n', fx, k );\n\n x = [ 1.0, -1.0 ];\n r8vec_print ( m, x, ' Initial point X0:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X0) = %g\\n', himmelblau ( m, x ) );\n\n [ x, fx, k ] = compass_search ( @himmelblau, m, x, delta_tol, delta, k_max );\n r8vec_print ( m, x, ' Estimated minimizer X1:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X1) = %g, number of steps = %d\\n', fx, k );\n%\n% Demonstrate Himmelblau minimizers.\n%\n x = [ 3.0, 2.0 ];\n r8vec_print ( m, x, ' Correct Himmelblau minimizer X1*:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X*) = %g\\n', himmelblau ( m, x ) );\n\n x = [ 3.58439, -1.84813 ];\n r8vec_print ( m, x, ' Correct Himmelblau minimizer X2*:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X*) = %g\\n', himmelblau ( m, x ) );\n\n x = [ -3.77934, -3.28317 ];\n r8vec_print ( m, x, ' Correct Himmelblau minimizer X3*:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X*) = %g\\n', himmelblau ( m, x ) );\n\n x = [ -2.80512, 3.13134 ];\n r8vec_print ( m, x, ' Correct Himmelblau minimizer X4*:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X*) = %g\\n', himmelblau ( m, x ) );\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/compass_search/himmelblau_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.6980093102142289}} {"text": "% QQDIAGRAM - Empirical quantile-quantile diagram.\n%\n% Description:\n% The quantiles (percentiles) of the input distribution Y are plotted (Y-axis)\n% against the corresponding quantiles of the input distribution X.\n% If only X is given, the corresponding quantiles are plotted (Y-axis)\n% against the quantiles of a Gaussian distribution ('Normal plot').\n% Two black dots indicate the lower and upper quartiles.\n% If the data in X and Y belong the same distribution the plot will be linear.\n% In this case,the red and black reference lines (.-.-.-.-) will overlap.\n% This will be true also if the data in X and Y belong to two distributions with\n% the same shape, one distribution being rescaled and shifted with respect to the\n% other.\n% If only X is given, a line is plotted to indicate the mean of X, and a segment\n% is plotted to indicate the standard deviation of X. If the data in X are normally\n% distributed, the red and black reference lines (.-.-.-.-) will overlap.\n%\n% Usage:\n% >> ah = qqdiagram( x, y, pk );\n%\n% Inputs:\n% x - vector of observations\n%\n% Optional inputs:\n% y - second vector of observation to compare the first to\n% pk - the empirical quantiles will be estimated at the values in pk [0..1]\n%\n% Author: Luca Finelli, CNL / Salk Institute - SCCN, 20 August 2002\n%\n% Reference: Stahel W., Statistische Datenanalyse, Vieweg, Braunschweig/Wiesbaden, 1995\n%\n% See also: \n% QUANTILE, SIGNALSTAT, EEGLAB \n\n% Copyright (C) 2002 Luca Finelli, Salk/SCCN, La Jolla, CA\n%\n% Reference: Stahel, W. Statistische Datenanalyse, Vieweg, Braunschweig/Wiesbaden 1995\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction qqdiagram( x , y, pk )\n\nif nargin < 1\n\thelp qqdiagram;\n\treturn;\nend;\t\n\nif (nargin == 3 && (any(pk > 1) || any(pk < 0)))\n error('qqdiagram(): elements in pk must be between 0 and 1');\nend\n\nif nargin==1\n\ty=x; \n\tnn=max(1000,10*length(y))+1;\n\tx=randn(1,nn);\nend\n\nif nargin < 3\n\tnx=sum(~isnan(x));\n\tny=sum(~isnan(y));\n \tk=min(nx,ny);\n pk=((1:k) - 0.5) ./ k; % values to estimate the empirical quantiles at \nelse \n k=length(pk);\nend\n\nif nx==k\n xx=sort(x(~isnan(x)));\nelse\n xx=quantile(x(~isnan(x)),pk);\nend\n\nif ny==k\n yy=sort(y(~isnan(y)));\nelse\n yy=quantile(y(~isnan(y)),pk);\nend\n\n% QQ diagram\nplot(xx,yy,'+')\nhold on\n\n% x-axis range\nmaxx=max(xx);\nminx=min(xx);\nrangex=maxx-minx;\nxmin=minx-rangex/50;\nxmax=maxx+rangex/50;\n\n% Quartiles\nxqrt1=quantile(x,0.25); xqrt3=quantile(x,0.75);\nyqrt1=quantile(y,0.25); yqrt3=quantile(y,0.75);\n\nplot([xqrt1 xqrt3],[yqrt1 yqrt3],'k-','LineWidth',2); % IQR range\n\n% Drawing the line\nsigma=(yqrt3-yqrt1)/(xqrt3-xqrt1);\ncy=(yqrt1 + yqrt3)/2;\n\t\nif nargin ==1\n maxy=max(y);\n miny=min(y);\n rangey=maxy-miny;\n\tymin=miny-rangey/50;\n\tymax=maxy+rangey/50;\n\t\n\tplot([(miny-cy)/sigma (maxy-cy)/sigma],[miny maxy],'r-.') % the line\n % For normally distributed data, the slope of the plot line\n % is equal to the ratio of the standard deviation of the distributions\n\tplot([0 (maxy-mean(y))/std(y)],[mean(y) maxy],'k-.') % the ideal line\n\t\n\txlim=get(gca,'XLim');\n\tplot([1 1],[ymin mean(y)+std(y)],'k--')\n\tplot([1 1],[mean(y) mean(y)+std(y)],'k-','LineWidth',2)\n % textx = 1.0;\n % texty = mean(y)+3.0*rangey/50.0;\n\t% text(double(textx), double(texty),' St. Dev.','horizontalalignment','center')\n set(gca,'xtick',get(gca,'xtick')); % show that vertical line is at 1 sd\n\tplot([0 0],[ymin mean(y)],'k--')\n\tplot(xlim,[mean(y) mean(y)],'k--')\n\t% text(double(xlim(1)), double(mean(y)+rangey/50),'Mean X')\n\tplot([xqrt1 xqrt3],[yqrt1 yqrt3],'k.','MarkerSize',10)\n\tset(gca,'XLim',[xmin xmax],'YLim',[ymin ymax])\n\txlabel('Standard Normal Quantiles')\n\tylabel('X Quantiles')\nelse\n cx=(xqrt1 + xqrt3)/2;\n maxy=cy+sigma*(max(x)-cx);\n\tminy=cy-sigma*(cx-min(x));\n\t\n\tplot([min(x) max(x)],[miny maxy],'r-.'); % the line\n xlabel('X Quantiles');\n ylabel('Y Quantiles');\nend\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/sigprocfunc/qqdiagram.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6979870481010365}} {"text": "function det = r8po_det ( n, a_lu )\n\n%*****************************************************************************80\n%\n%% R8PO_DET computes the determinant of a matrix factored by R8PO_FA.\n%\n% Discussion:\n%\n% The R8PO storage format is appropriate for a symmetric positive definite \n% matrix and its inverse. (The Cholesky factor of a R8PO matrix is an\n% upper triangular matrix, so it will be in R8GE storage format.)\n%\n% Only the diagonal and upper triangle of the square array are used.\n% This same storage scheme is used when the matrix is factored by\n% R8PO_FA, or inverted by R8PO_INVERSE. For clarity, the lower triangle\n% is set to zero.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 March 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real A_LU(N,N), the LU factors from R8PO_FA.\n%\n% Output, real DET, the determinant of A.\n%\n det = 1.0E+00;\n\n for i = 1 : n\n det = det * a_lu(i,i);\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/r8po_det.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.6979870390790465}} {"text": "function y = quadcc(fun,a,b,tol)\n%QUADCC Numerical integration using Clenshaw-Curtis quadrature.\n% Y = QUADCC(FUN,A,B) estimates the definite integral of the\n% function FUN from A to B, using an adaptive Clenshaw-Curtis \n% quadrature scheme. FUN is either a MATLAB expression written \n% as a string or inline function, or a function M-file. A and\n% B are the lower and upper limits of integration, respectively.\n%\n% QUADCC computes the integral by recursively dividing the interval\n% (A,B) into finer subintervals, defined by the zero-points of the\n% Type 1 Chebyshev polynomials. The recursion continues until \n% either (1) the difference between computed estimates of the \n% integral in successive recursion steps falls below a tolerance \n% (default TOL = 1e-6), or (2) the integral domain has been \n% divided into 1024 subintervals. A warning is returned if the \n% maximum number of subintervals is reached before the tolerance\n% criterion is met.\n% Y = QUADCC(FUN,A,B,TOL) uses the supplied value of TOL instead\n% of the default.\n%\n% QUADCC provides limited handling of certain types of improper\n% integral. If the integrand has a pole at one (or both) of the\n% integration limits, QUADCC returns a warning and attempts to\n% evaluate the integral by shifting the integration limit a \n% distance EPS inside the integration interval. If QUADCC\n% encounters a pole inside the integration interval, an error is\n% produced.\n%\n% Examples:\n%\n% 1) String expression\n% Y = quadcc('1./(x.^2-5)',-1,2)\n%\n% 2) Inline function\n% foo = inline('x.*sin(x)')\n% Y = quadcc(foo,0,2*pi)\n%\n% 3) Function M-file\n% Y = quadcc(@foo,0,1)\n% with foo.m a function M-file:\n%\n% function y = foo(x)\n% y = tan(x);\n%\n% See also QUAD, QUADL, DBLQUAD, TRIPLEQUAD, INLINE\n\n% References\n% ----------\n% \"Numerical Recipes in C. The Art of Scientific Computing, 2nd edition\".\n% W. H. Press, S. A. Teukolsky, W. T. Vetterling, and B. P. Flannery.\n% Cambridge Unversity Press, 2002.\n\n% Paul Fricker 12/09/2002\n\nif a==b\n y = 0;\n return\nend\n\nif ~exist('tol')\n tol = 1e-6;\nend\n\n% Make sure 'fun' is an inline function\nf = fcnchk(fun);\n\n% Initialize by breaking the integration interval into four regions.\nN = 4;\np = (b+a)/2;\nq = (b-a)/2;\n% Write out [ cos((0:4)/4*pi) ] explicitly to avoid cos(pi/2) roundoff\nx = p-q*[1 0.7071067811865475 0 -0.7071067811865475 -1];\nF = feval(f,x);\n\n% Simple attempt to handle improper integral\nif isinf(F(1))\n F(1) = feval(f,x(1)+eps);\n warning('QUADCC:improperLower', ...\n ['Improper integral: Integrand has pole ' ...\n 'at lower integration limit.'])\nend\n\nif isinf(F(5))\n F(5) = feval(f,x(5)-eps);\n warning('QUADCC:improperUpper', ...\n ['Improper integral: Integrand has pole ' ...\n 'at upper integration limit.'])\nend\n\n% Modify the first and last terms of 'F'.\nF(1) = F(1)/2;\nF(end) = F(end)/2;\n\n% Call the integrator function recursively\n[y,warn] = intcc(f,x,F,N,p,q,tol,Inf);\n\nif warn==1\n warning('QUADCC:MaxSubDivide', ...\n ['Computation terminated before tolerance criterion (TOL = ' num2str(tol) ') was met.'])\nend\n\n\n% EOF 'quadcc'\n\n\nfunction [y,warn] = intcc(f,x,F,N,p,q,tol,yinit)\n% INTCC Recursive integrator function for the QUADCC routine.\n%\n% Input parameters:\n% f : Integrand\n% x : Chebyshev polynomial zero-points between the integration limits (a,b)\n% F : Values of 'f' evaluated at 'x'\n% N : Initial number of zero-points ('discretization')\n% p,q : Endpoint parameters (from integration limits)\n% tol : Integration tolerance (terminates the recursion)\n% yinit : Estimated value of the integral from the previous pass\n\n% Terminate recursion if integral has not converged before 1024 points\nif size(x,2) > 2^10\n warn = 1;\n y = yinit;\n return\nelse\n warn = 0;\nend\n\n% Double the size of the approximation\nN = 2*N;\nNvec = 0:N;\n\nx2 = zeros(1,N+1);\nx2(1:2:end) = x;\nx2(2:2:end) = p-q*cos((1:2:N)/N*pi);\n\nG = zeros(1,N+1);\nG(1:2:end) = F;\nG(2:2:end) = feval(f,x2(2:2:end));\nG = G(:);\n\nif any(isinf(G))\n error('Improper integral: Integrand has a pole between integration limits.')\nend\n\n% Evaluate the Chebyshev polynomial coefficients for\n% approximating the input function 'f'\nM = cos(Nvec(1:2:end-1)'*Nvec/N*pi);\nM(abs(M) tol\n [y,warn] = intcc(f,x2,G,N,p,q,tol,y);\nend\n\n% EOF 'intcc'\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/2905-quadcc/quadcc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6979870300370948}} {"text": "% \u6f14\u793a\u8c03\u7528 LU \u5206\u89e3\u7684\u7d27\u51d1\u65b9\u5f0f\nclear;\nA=[1 2 3; 2 5 2; 3 1 5];\nb=[14;18;20];\n\n% LU\u4e09\u89d2\u5206\u89e3\u6cd5\n[L, U, x] = my_lu(A, b)\n\n% \u5217\u4e3b\u5143LU\u4e09\u89d2\u5206\u89e3\u6cd5\n%[L, U, x] = my_lu_with_column_pivoting(A, b)\n\n% \u76f4\u63a5\u8c03\u7528matlab\u5de6\u9664\u8fd0\u7b97\u7b26\nx_ = A\\b", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/\u7b2c\u516d\u7ae0 \u7ebf\u6027\u65b9\u7a0b\u7ec4\u7684\u76f4\u63a5\u6cd5/demo6_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.7853085884247212, "lm_q1q2_score": 0.6979499181953713}} {"text": "function value = f1sd1 ( x )\n\n%*****************************************************************************80\n%\n%% F1SD1 evaluates the function 1.0D+00/ sqrt ( 1.1 - x**2 ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 January 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the function.\n%\n% Output, real VALUE, the value of the function.\n%\n f1sd1 = 1.0 / sqrt ( 1.1 - x * x );\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/f1sd1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6979499068690774}} {"text": "function [ a_lu, pivot, info ] = r8ge_fa ( n, a )\n\n%*****************************************************************************80\n%\n%% R8GE_FA performs a LINPACK style PLU factorization of an R8GE matrix.\n%\n% Discussion:\n%\n% The R8GE storage format is used for a general M by N matrix. A storage \n% space is made for each logical entry. The two dimensional logical\n% array is mapped to a vector, in which storage is by columns.\n%\n% This is a simplified version of the LINPACK routine DGEFA.\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% Reference:\n%\n% Dongarra, Bunch, Moler, Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be positive.\n%\n% Input, real A(N,N), the matrix to be factored.\n%\n% Output, real A_LU(N,N), an upper triangular matrix and \n% the multipliers used to obtain it. The factorization \n% can be written A = L * U, where L is a product of \n% permutation and unit lower triangular matrices and U \n% is upper triangular.\n%\n% Output, integer PIVOT(N), a vector of pivot indices.\n%\n% Output, integer INFO, singularity flag.\n% 0, no singularity detected.\n% nonzero, the factorization failed on the INFO-th step.\n%\n a_lu(1:n,1:n) = a(1:n,1:n);\n\n info = 0;\n\n for k = 1 : n-1\n%\n% Find L, the index of the pivot row.\n%\n l = k;\n for i = k+1 : n\n if ( abs ( a_lu(l,k) ) < abs ( a_lu(i,k) ) )\n l = i;\n end\n end\n\n pivot(k) = l;\n%\n% If the pivot index is zero, the algorithm has failed.\n%\n if ( a_lu(l,k) == 0.0 )\n info = k;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8GE_FA - Fatal error!\\n' );\n fprintf ( 1, ' Zero pivot on step %d\\n', info );\n return;\n end\n%\n% Interchange rows L and K if necessary.\n%\n if ( l ~= k )\n t = a_lu(l,k);\n a_lu(l,k) = a_lu(k,k);\n a_lu(k,k) = t;\n end\n%\n% Normalize the values that lie below the pivot entry A(K,K).\n%\n a_lu(k+1:n,k) = -a_lu(k+1:n,k) / a_lu(k,k);\n%\n% Row elimination with column indexing.\n%\n for j = k+1 : n\n\n if ( l ~= k )\n t = a_lu(l,j);\n a_lu(l,j) = a_lu(k,j);\n a_lu(k,j) = t;\n end\n\n a_lu(k+1:n,j) = a_lu(k+1:n,j) + a_lu(k+1:n,k) * a_lu(k,j);\n\n end\n end\n\n pivot(n) = n;\n\n if ( a_lu(n,n) == 0.0 )\n info = n;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8GE_FA - Fatal error!\\n' );\n fprintf ( 1, ' Zero pivot on step %d\\n', info );\n return;\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/fem2d_pack/r8ge_fa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6979499067070204}} {"text": "function [M,mv,alpha,unA] = ...\n select_taylor_degree(A,b,m_max,p_max,prec,shift,bal,force_estm)\n%SELECT_TAYLOR_DEGREE Select degree of Taylor approximation.\n% [M,MV,alpha,unA] = SELECT_TAYLOR_DEGREE(A,m_max,p_max) forms a matrix M\n% for use in determining the truncated Taylor series degree in EXPMV\n% and EXPMV_TSPAN, based on parameters m_max and p_max.\n% MV is the number of matrix-vector products with A or A^* computed.\n\n% Reference: A. H. Al-Mohy and N. J. Higham, Computing the action of\n% the matrix exponential, with an application to exponential\n% integrators. MIMS EPrint 2010.30, The University of Manchester, 2010.\n\n% Awad H. Al-Mohy and Nicholas J. Higham, October 26, 2010.\n\nif nargin < 8, force_estm = false; end\nif nargin < 4 || isempty(p_max), p_max = 8; end\nif nargin < 3 || isempty(m_max), m_max = 55; end\n\nif p_max < 2 || m_max > 60 || m_max + 1 < p_max*(p_max - 1)\n error('>>> Invalid p_max or m_max.')\nend\nn = length(A);\nif nargin < 7 || isempty(bal), bal = false; end\nif bal\n [D B] = balance(A);\n if norm(B,1) < norm(A,1), A = B; end\nend\nif nargin < 5 || isempty(prec), prec = class(A); end\nswitch prec\n case 'double'\n load theta_taylor\n case 'single'\n load theta_taylor_single\n case 'half'\n load theta_taylor_half\nend\nif shift\n mu = trace(A)/n;\n A = A-mu*speye(n);\nend\nmv = 0;\nif ~force_estm, normA = norm(A,1); end\n\nif ~force_estm && normA <= 4*theta(m_max)*p_max*(p_max + 3)/(m_max*size(b,2));\n% if true\n % Base choice of m on normA, not the alpha_p.\n unA = 1;\n c = normA;\n alpha = c*ones(p_max-1,1);\nelse\n unA = 0;\n eta = zeros(p_max,1); alpha = zeros(p_max-1,1);\n for p = 1:p_max\n [c,k] = normAm(A,p+1);\n c = c^(1/(p+1));\n mv = mv + k;\n eta(p) = c;\n end\n for p = 1:p_max-1\n alpha(p) = max(eta(p),eta(p+1));\n end\nend\nM = zeros(m_max,p_max-1);\nfor p = 2:p_max\n for m = p*(p-1)-1 : m_max\n M(m,p-1) = alpha(p-1)/theta(m);\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/29576-matrix-exponential-times-a-vector/select_taylor_degree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430353105599, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.6979390404112676}} {"text": "% This program obtains the analytical step response of a parallel RLC \n% circuit. In addition, graphs of the voltage across the parallel \n% combination and branch currents are obtained. \n% H. Saadat, Copyright 1999 \n\nfunction PresponseIR\nwarning('off','MATLAB:dispatcher:InexactMatch')\nRhandle=findobj('Tag','Rtext');\nR=eval(get(Rhandle,'String'));\nKOhandle=findobj('Tag','KOhm');\nKO=get(KOhandle,'Value');\nif KO==1 \n R=1000*R;\nelse, end\nLhandle=findobj('Tag','Ltext');\nL=eval(get(Lhandle,'String'));\nmHhandle=findobj('Tag','mHenry');\nml=get(mHhandle,'Value');\nif ml==1 \n L=L/1000;\nelse, end\nChandle=findobj('Tag','Ctext');\nC=eval(get(Chandle,'String'));\nmicFhandle=findobj('Tag','micFarad');\nmicF=get(micFhandle,'Value');\nif micF==1 \n C=C/1000000;\nelse, end\nRhandle=findobj('Tag','IStext');\nIs=eval(get(Rhandle,'String'));\nRhandle=findobj('Tag','I0text');\nI0=eval(get(Rhandle,'String'));\nRhandle=findobj('Tag','V0text');\nV0=eval(get(Rhandle,'String'));\n% Step Response of a parallel RLC circuit\nif L==inf | C==inf \n plot(0, 0)\n text(-0.8, 0.80, 'Parameters must lie in the following ranges:', 'color', [0 0 0.6275])\n text(-0.8, 0.65, '0 < R \\leq inf, 0 < L < inf, & 0 < C < inf', 'color', [0 0 0.6275])\n text(-0.8, 0.5, 'Enter the correct value and press Solve', 'color', [0 0 0.6275])\n axis([-1 1 -1 1]);return, else\nend\nif R==0 | L==0 | C == 0\nplot(0, 0)\ntitle('Short-circuit across the parallel circuit', 'color', [ 1 0 0])\ntext(-0.8, 0.80, 'Parameters must lie in the following ranges:', 'color', [0 0 0.6275])\ntext(-0.8, 0.65, '0 < R \\leq inf, 0 < L < inf, & 0 < C < inf', 'color', [0 0 0.6275])\ntext(-0.8, 0.5, 'Enter the correct value and press Solve', 'color', [0 0 0.6275])\naxis([-1 1 -1 1]);return, else\nalpha =1/(2*R*C);\nend\nw02 = 1/(L*C); w0 = sqrt(w02); \nif alpha~= 0\n err=(alpha-w0)/alpha;\n if abs(err) <1e-4\n w0=alpha; \n else, end\nelse, end \ndv = Is/C-I0/C-V0/(R*C);\ndi = V0/L;\nif alpha > w0\n % Overdamped response\n s(1) = -alpha + sqrt(alpha^2 - w02);\n s(2) = -alpha - sqrt(alpha^2 - w02);\n A1 = (dv-s(2)*V0)/(s(1)-s(2));\n A2 = (dv-s(1)*V0)/(s(2)-s(1));\n A1i =(di-s(2)*(I0-Is))/(s(1)-s(2));\n A2i =(di-s(1)*(I0-Is))/(s(2)-s(1));\n tf = 6*max(abs(1/s(1)), abs(1/s(2)));\n t=0:tf/100:tf;\n v = A1*exp(s(1)*t)+A2*exp(s(2)*t); \n iL=Is + A1i*exp(s(1)*t)+A2i*exp(s(2)*t); \n iR = v/R;\n iC= Is -iR-iL;\n it=iR+iL+iC;\n plot(t,iR,'erasemode','none','color',[0.9 0 0.8]), grid\n title(['i_R(t) =(', num2str(A1/R), ') e^{(', num2str(s(1)), 't)} + (', num2str(A2/R), ') e^{(', num2str(s(2)), 't)}'],'color',[0.9 0 0.8])\n xlabel(['\\alpha = ',num2str(alpha), ', \\omega_0 = ', num2str(w0), ' (O.D.) t, sec'])\n ylabel('i_R(t), Amps')\n elseif alpha < w0 \n if alpha~=0\n % Underdamped response\n tf = 6/alpha;\n t=0:tf/200:tf;\n wd= sqrt(w02 - alpha^2); \n s(1) = -alpha +j*wd;\n s(2) = -alpha -j*wd;\n B1 = V0; B2 = (dv+alpha*B1)/wd;\n B1i = I0 - Is; B2i = (di+alpha*B1i)/wd;\n v = exp(-alpha*t).*(B1*cos(wd*t)+B2*sin(wd*t));\n iL = Is + exp(-alpha*t).*(B1i*cos(wd*t)+B2i*sin(wd*t));\n iR = v/R;\n iC= Is -iR-iL;\n it=iR+iL+iC;\n plot(t,iR,'erasemode','none','color',[.9 0 0.8]), grid\n title(['i_R(t) = e^{(-', num2str(alpha), 't)}[(', num2str(B1/R), ')cos',num2str(wd),'t + (' , num2str(B2/R), ')sin',num2str(wd),'t]'],'color',[0.9 0 0.8])\n xlabel(['\\alpha = ',num2str(alpha), ', \\omega_0 = ', num2str(w0), ' (U.D.) t, sec'])\n ylabel('i_R(t), Amps')\n else \n % Undamped Response \n tf = 8*pi/w0;\n t=0:tf/200:tf;\n wd= w0; \n B1 = V0; B2 = (dv)/wd;\n B1i = I0 - Is; B2i = (di)/wd;\n iL = Is + B1i*cos(wd*t)+B2i*sin(wd*t);\n v = B1*cos(wd*t)+B2*sin(wd*t);\n iR = v/R;\n iC= Is -iR-iL;\n it=iR+iL+iC;\n plot(t,iR,'erasemode','none','color',[0.9 0 0.80]), grid\n title('i_R(t) = 0')\n xlabel(['\\alpha = ',num2str(alpha), ', \\omega_0 = ', num2str(w0), ' (Undamped) t, sec'])\n ylabel('i_R(t), Amps')\n end\n elseif alpha ==w0 \n % Critically damped response\n s(1)=-alpha; s(2) = s(1);\n D2 = V0; \n D1 = dv+alpha*D2;\n D2i = I0 - Is; D1i = di+alpha*D2i; \n tf = 8/alpha;\n t=0:tf/100:tf;\n iL=Is + exp(-alpha*t).*(D1i*t+D2i); \n v = exp(-alpha*t).*(D1*t+D2); \n iR = v/R;\n iC= Is -iR-iL;\n it=iR+iL+iC;\n plot(t,iR,'erasemode','none','color',[0.9 0 0.8]), grid\n title(['i_R(t) = e^{(-', num2str(alpha), 't)}[(', num2str(D1/R), ')t + (' , num2str(D2/R), ')]'],'color',[0.9 0 0.8])\n xlabel(['\\alpha = ',num2str(alpha), ', \\omega_0 = ', num2str(w0), ' (C.D.) t, sec'])\n ylabel('i_R(t), Amps')\n else, end\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/37711-time-domain-response-of-rlc-circuits-gui/PresponseIR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6979294353582755}} {"text": "function varargout=jdqr(varargin)\n%JDQR computes a partial Schur decomposition of a square matrix or operator. \n% Lambda = JDQR(A) returns the absolute largest eigenvalues in a K vector\n% Lambda. Here K=min(5,N) (unless K has been specified), where N=size(A,1).\n% JDQR(A) (without output argument) displays the K eigenvalues.\n%\n% [X,Lambda] = JDQR(A) returns the eigenvectors in the N by K matrix X and \n% the eigenvalues in the K by K diagonal matrix Lambda. Lambda contains the \n% Jordan structure if there are multiple eigenvalues.\n%\n% [X,Lambda,HISTORY] = JDQR(A) returns also the convergence history\n% (that is, norms of the subsequential residuals).\n%\n% [X,Lambda,Q,S] = JDQR(A) returns also a partial Schur decomposition:\n% S is an K by K upper triangular matrix and Q is an N by K orthonormal matrix \n% such that A*Q = Q*S. The diagonal elements of S are eigenvalues of A.\n%\n% [X,Lambda,Q,S,HISTORY] = JDQR(A) returns also the convergence history.\n%\n% [X,Lambda,HISTORY] = JDQR('Afun')\n% [X,Lambda,HISTORY] = JDQR('Afun',N)\n% The first input argument is either a square matrix (which can be\n% full or sparse, symmetric or nonsymmetric, real or complex), or a\n% string containing the name of an M-file which applies a linear\n% operator to a given column vector. In the latter case, the M-file must \n% return the the order N of the problem with N = Afun([],'dimension') or \n% N must be specified in the list of input arguments.\n% For example, EIGS('fft',...) is much faster than EIGS(F,...)\n% where F is the explicit FFT matrix.\n%\n% The remaining input arguments are optional and can be given in\n% practically any order:\n% ... = JDQR(A,K,SIGMA,OPTIONS) \n% ... = JDQR('Afun',K,SIGMA,OPTIONS)\n% where\n%\n% K An integer, the number of eigenvalues desired.\n% SIGMA A scalar shift or a two letter string.\n% OPTIONS A structure containing additional parameters.\n%\n% With one output argument, S is a vector containing K eigenvalues.\n% With two output arguments, S is a K-by-K upper triangular matrix \n% and Q is a matrix with K columns so that A*Q = Q*S and Q'*Q=I.\n% With three output arguments, HISTORY contains the convergence history.\n%\n% If K is not specified, then K = MIN(N,5) eigenvalues are computed.\n%\n% If SIGMA is not specified, then the K-th eigenvalues largest in magnitude\n% are computed. If SIGMA is zero, then the K-th eigenvalues smallest in\n% magnitude are computed. If SIGMA is a real or complex scalar then the \n% K-th eigenvalues nearest SIGMA are computed. If SIGMA is one of the\n% following strings, then it specifies the desired eigenvalues.\n%\n% SIGMA Location wanted eigenvalues\n%\n% 'LM' Largest Magnitude (the default)\n% 'SM' Smallest Magnitude (same as sigma = 0)\n% 'LR' Largest Real part\n% 'SR' Smallest Real part\n% 'BE' Both Ends. Computes k/2 eigenvalues\n% from each end of the spectrum (one more\n% from the high end if k is odd.)\n%\n%\n% The OPTIONS structure specifies certain parameters in the algorithm.\n%\n% Field name Parameter Default\n%\n% OPTIONS.Tol Convergence tolerance: 1e-8 \n% norm(A*Q-Q*S,1) <= tol * norm(A,1) \n% OPTIONS.jmin minimum dimension search subspace k+5\n% OPTIONS.jmax maximum dimension search subspace jmin+5\n% OPTIONS.MaxIt Maximum number of iterations. 100\n% OPTIONS.v0 Starting space ones+0.1*rand\n% OPTIONS.Schur Gives schur decomposition 'no'\n% also in case of 2 or 3 output \n% arguments (X=Q, Lambda=R).\n%\n% OPTIONS.TestSpace For using harmonic Ritz values 'Standard'\n% If 'TestSpace'='Harmonic' then \n% sigma=0 is the default value for SIGMA\n%\n% OPTIONS.Disp Shows size of intermediate residuals 1\n% and displays the appr. eigenvalues.\n%\n% OPTIONS.LSolver Linear solver 'GMRES'\n% OPTIONS.LS_Tol Residual reduction linear solver 1,0.7,0.7^2,..\n% OPTIONS.LS_MaxIt Maximum number it. linear solver 5\n% OPTIONS.LS_ell ell for BiCGstab(ell) 4\n%\n% OPTIONS.Precond Preconditioner LU=[[],[]].\n%\n% For instance\n%\n% OPTIONS=STRUCT('Tol',1.0e-10,'LSolver','BiCGstab','LS_ell',2,'Precond',M);\n%\n% changes the convergence tolerance to 1.0e-10, takes BiCGstab(2) as linear \n% solver and the preconditioner defined in M.m if M is the string 'M', \n% or M = L*U if M is an n by 2*n matrix: M = [L,U].\n%\n% The preconditoner can be specified in the OPTIONS structure,\n% but also in the argument list:\n% ... = JDQR(A,K,SIGMA,M,OPTIONS) \n% ... = JDQR(A,K,SIGMA,L,U,OPTIONS) \n% ... = JDQR('Afun',K,SIGMA,'M',OPTIONS)\n% ... = JDQR('Afun',K,SIGMA,'L','U',OPTIONS)\n% as an N by N matrix M (then M is the preconditioner), or an N by 2*N \n% matrix M (then L*U is the preconditioner, where M = [L,U]),\n% or as N by N matrices L and U (then L*U is the preconditioner),\n% or as one or two strings containing the name of M-files ('M', or \n% 'L' and 'U') which apply a linear operator to a given column vector.\n%\n% JDQR (without input arguments) lists the options and the defaults.\n\n\n% Gerard Sleijpen.\n% Copyright (c) 98\n%\n%\n\n% This file is part of the Matlab Toolbox for Dimensionality Reduction.\n% The toolbox can be obtained from http://homepage.tudelft.nl/19j49\n% You are free to use, change, or redistribute this code in any way you\n% want for non-commercial purposes. However, it is appreciated if you \n% maintain the name of the original author.\n%\n% (C) Laurens van der Maaten, Delft University of Technology\n\nglobal Qschur Rschur PinvQ Pinv_u Pu nm_operations\n\nif nargin==0, possibilities, return, end\n\n%%% Read/set parameters\n[n,nselect,sigma,SCHUR,...\n jmin,jmax,tol,maxit,V,INTERIOR,SHOW,PAIRS,JDV0,t_tol,...\n lsolver,LSpar] = ReadOptions(varargin{1:nargin});\nLSpar0=LSpar; JDV=0; tol0=tol; LOCK0=~ischar(sigma); \nif nargout>3, SCHUR=0; end\ntau=0; if INTERIOR>=1 & LOCK0, tau=sigma(1); end\nn_tar=size(sigma,1); nt=1; FIG=gcf;\n\n%%% Initiate global variables\nQschur = zeros(n,0); Rschur = []; \nPinvQ = zeros(n,0); Pinv_u = zeros(n,1); Pu = [];\nnm_operations = 0; history = [];\n\n%%% Return if eigenvalueproblem is trivial\nif n<2\n if n==1, Qschur=1; Rschur=MV(1); end\n if nargout == 0, eigenvalue=Rschur, else\n [varargout{1:nargout}]=output(history,Qschur,Rschur); end, \nreturn, end\n\nString = ['\\r#it=%i #MV=%i dim(V)=%i |r_%i|=%6.1e '];\nStrinP = '--- Checking for conjugate pair ---\\n';\ntime = clock;\n\n%%% Initialize V, W:\n%%% V,W orthonormal, A*V=W*R+Qschur*E, R upper triangular\n[V,W,R,E,M]=SetInitialSpaces(V,nselect,tau,jmin,tol); \nj=size(V,2); k=size(Rschur,1);\nnit=0; nlit=0; SOLVED=0;\n\nswitch INTERIOR\n\ncase 0\n\n%%% The JD loop (Standard)\n%%% V orthogonal, V orthogonal to Qschur\n%%% V*V=eye(j), Qschur'*V=0, \n%%% W=A*V, M=V'*W\n%%%\nW=W*R; if tau ~=0; W=W+tau*V; end, M=M'*R; temptarget=sigma(nt,:); \nwhile (k=nselect, break, end, r_KNOWN=0; \n \n\n %%% Expand preconditioned Schur matrix PinvQ\n SOLVED=UpdateMinv(u,SOLVED);\n\n if j==1, \n [V,W,R,E,M]=SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol); \n k=size(Rschur,1); if k>=nselect, break, end\n W=W*R; if tau ~=0; W=W+tau*V; end; M=M'*R; j=size(V,2);\n else,\n J=[2:j]; j=j-1; UR=UR(:,J); \n M=S(J,J); V=V*UR; W=W*UR; \n end\n\n if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u)));\n if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end\n end\n\n if EXPAND, temptarget=conj(theta); if SHOW, fprintf(StrinP), end\n else, nlit=0; nt=min(nt+1,n_tar); temptarget=sigma(nt,:); end\n\n end % nr=jmax\n j=jmin; J=[1:j]; UR=UR(:,J);\n M=S(J,J); V=V*UR; W=W*UR;\n end % if j>=jmax\n \n if r_KNOWN\n %%% Solve correction equation\n v=Solve_pce(theta,u,r,lsolver,LSpar,nlit); SOLVED=1;\n nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1;\n end % if r_KNOWN\n\n if EXPAND\n %%% Expand the subspaces of the interaction matrix \n v=RepGS([Qschur,V],v); \n if size(v,2)>0\n w=MV(v);\n M=[M,V'*w;v'*W,v'*w]; \n V=[V,v]; W=[W,w]; j=j+1; EXPAND=0; tol=tol0;\n else\n tol=2*tol;\n end\n end % if EXPAND\n\nend % while (nit=jmax,jmin);\n y=UR(:,1); theta=T(1,1)'*S(1,1); \n u=V*y; w=W*(R*y); r=w-theta*u; nr=norm(r); r_KNOWN=1; \n if nr=nselect, break, end, r_KNOWN=0; JDV=0;\n\n %%% Expand preconditioned Schur matrix PinvQ\n SOLVED=UpdateMinv(u,SOLVED);\n\n if j==1,\n [V,W,R,E,M]=...\n SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol); \n k=size(Rschur,1); if k>=nselect, break, end, j=size(V,2);\n else\n J=[2:j]; j=j-1; UR=UR(:,J); UL=UL(:,J);\n R=S(J,J); M=T(J,J); V=V*UR; W=W*UL; \n [r,a]=RepGS(u,r,0); E=[E*UR;(T(1,1)'-a/S(1,1))*S(1,J)];\n \n s=(S(1,J)/S(1,1))/R; W=W+r*s; M=M+s'*(r'*V);\n if (nr*norm(s))^2>eps, [W,R0]=qr(W,0); R=R0*R; M=R0'\\M; end\n\n end\n\n if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u)));\n if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end\n end\n\n if EXPAND, if SHOW, fprintf(StrinP), end\n temptarget=[conj(theta)-tau;0];\n else, nlit=0; temptarget=0;\n if nt=jmax\n j=jmin; J=[1:j]; UR=UR(:,J); UL=UL(:,J);\n R=S(J,J); M=T(J,J); V=V*UR; W=W*UL; E=E*UR;\n end % if j>=jmax\n\n if r_KNOWN\n %%% Solve correction equation\n if JDV, disp('Stagnation'),\n LSpar(end-1)=(LSpar(end-1)+15)*2;\n % lsolver='bicgstab'; LSpar=[1.e-2,300,4];\n else\n LSpar=LSpar0; JDV=0; lsolver=lsolver0;\n end\n if nr>0.001 & FIXT, theta=tau; else, FIXT=0; end\n v=Solve_pce(theta,u,r,lsolver,LSpar,nlit);\n nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1; SOLVED=1; JDV=0;\n end\n \n if EXPAND\n %%% Expand the subspaces of the interaction matrix \n [v,zeta]=RepGS([Qschur,V],v);\n if JDV0 & abs(zeta(end,1))/norm(zeta)<0.06, JDV=JDV+1; end\n if size(v,2)>0 \n w=MV(v); if tau ~=0, w=w-tau*v; end\n [w,e]=RepGS(Qschur,w,0); [w,y]=RepGS(W,w); \n R=[[R;zeros(1,j)],y]; M=[M,W'*v;w'*V,w'*v]; E=[E,e];\n V=[V,v]; W=[W,w]; j=j+1; EXPAND=0; tol=tol0;\n else\n tol=2*tol;\n end\n end\n \nend % while (nit=jmax,jmin);\n y=UR(:,1); u=V*y; w=AV*y; theta=u'*w; \n r=w-theta*u; [r,y]=RepGS(Qschur,r,0); nr=norm(r); r_KNOWN=1;\n if nr=nselect, break, end, r_KNOWN=0;\n\n %%% Expand preconditioned Schur matrix PinvQ\n SOLVED=UpdateMinv(u,SOLVED);\n\n if j==1\n [V,W,R,E,M]=SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol); \n k=size(Rschur,1); if k>=nselect, break, end\n AV=W*R; j=size(V,2); \n else\n J=[2:j]; j=j-1; UR=UR(:,J); UL=UL(:,J);\n AV=AV*UR; R=S(J,J); M=T(J,J); V=V*UR; W=W*UL;\n end\n \n if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u)));\n if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end\n end\n\n if EXPAND,if SHOW, fprintf(StrinP), end\n temptarget=[conj(theta)-tau;0];\n else, nlit=0; temptarget=0;\n if nt=jmax\n j=jmin; J=[1:j]; UR=UR(:,J); UL=UL(:,J);\n AV=AV*UR; R=S(J,J); M=T(J,J); V=V*UR; W=W*UL;\n end % if j>=jmax\n\n if r_KNOWN\n %%% Solve correction equation\n v=Solve_pce(theta,u,r,lsolver,LSpar,nlit); SOLVED=1;\n nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1;\n end\n\n if EXPAND\n %%% Expand the subspaces of the interaction matrix \n v=RepGS([Qschur,V],v); \n if size(v,2)>0\n w=MV(v); if tau ~=0, w=w-tau*v;end\n AV=[AV,w]; R=[R,W'*w];\n w=RepGS([Qschur,W],w);\n R=[R;w'*AV]; M=[M,W'*v;w'*V,w'*v]; \n V=[V,v]; W=[W,w]; j=j+1; EXPAND=0; tol=tol0;\n else\n tol=2*tol;\n end\n end\n \nend % while (nit=nselect, break, end, r_KNOWN=0;\n\n %%% Expand preconditioned Schur matrix PinvQ\n SOLVED=UpdateMinv(u,SOLVED);\n\n if j==1\n [V,W,R,E,M]=SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol); \n k=size(Rschur,1); if k>=nselect, break, end\n V=V/R; j=size(V,2); M=M/R; E=E/R;\n else\n J=[2:j]; j=j-1; UR=UR(:,J); M=S(J,J);\n V=V*UR; W=W*UR; [r,a]=RepGS(u,r,0); \n s=u'*V; V=V-u*s; W=W-r*s; M=M-s'*(r'*V)-(W'*u)*s; \n E=[E*UR-y*s;(tau-theta-a)*s];\n \n if (nr*norm(s))^2>eps, [W,R]=qr(W,0); V=V/R; M=(R'\\M)/R; E=E/R; end\n\n end\n\n if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u)));\n if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end\n end\n\n if EXPAND, if SHOW, fprintf(StrinP), end\n temptarget=[1/(conj(theta)-tau);inf];\n else, nlit=0; temptarget='LM';\n if nt=jmax\n j=jmin; J=[1:j]; UR=UR(:,J);\n M=S(J,J); V=V*UR; W=W*UR; E=E*UR;\n end % if j>=jmax\n\n if r_KNOWN\n %%% Solve correction equation\n v=Solve_pce(theta,u,r,lsolver,LSpar,nlit); SOLVED=1;\n nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1;\n end\n\n if EXPAND\n %%% Expand the subspaces of the interaction matrix \n v=RepGS(Qschur,v,0);\n if size(v,2)>0 \n w=MV(v); if tau ~=0, w=w-tau*v; end\n [w,e]=RepGS(Qschur,w,0); [w,y]=RepGS(W,w); \n nrw=y(j+1,1); y=y(1:j,:); \n v=v-V*y; v=v/nrw; e=e-E*y; e=e/nrw;\n M=[M,W'*v;w'*V,w'*v]; \n V=[V,v]; W=[W,w]; j=j+1; E=[E,e];\n\n if 1/cond(M)<10*tol\n [V,W,R,E,M]=SetInitialSpaces(V,nselect,tau,jmin,tol,W,E); \n k=size(Rschur,1); if k>=nselect, break, end\n V=V/R; M=M/R; j=size(V,2);temptarget='LM'; E=E/R;\n end \n\n EXPAND=0; tol=tol0;\n else\n tol=2*tol;\n end\n end \n\nend % while (nit0, [z,Lambda]=Jordan(Rschur); X=Qschur*z; end\n\n%-------------- display results ----------------------------\nif SHOW == 2, MovieTheta, figure(FIG), end\nif SHOW & size(history,1)>0\n\n switch INTERIOR\n case 0\n testspace='V, V orthonormal'; \n case 1\n testspace='A*V-sigma*V, V and W orthonormal'; \n case 1.1\n testspace='A*V-sigma*V, V and W orthonormal, AV'; \n case 1.2\n testspace='A*V-sigma*V, W orthogonal'; \n otherwise \n testspace='Experimental'; \n end\n\n StringT=sprintf('The test subspace W is computed as W = %s.',testspace);\n StringX=sprintf('JDQZ with jmin=%g, jmax=%g, residual tolerance %g.',...\n jmin,jmax,tol); \n StringY=sprintf('Correction equation solved with %s.',lsolver); \n date=fix(clock);\n String=sprintf('\\n%2i-%2i-%2i, %2i:%2i:%2i',date(3:-1:1),date(4:6));\n\n StringL='log_{10} || r_{#it} ||_2';\n for pl=1:SHOW\n subplot(SHOW,1,pl), t=history(:,pl+1);\n plot(t,log10(history(:,1)),'*-',t,log10(tol)+0*t,':')\n legend(StringL), title(StringT)\n StringL='log_{10} || r_{#MV} ||_2'; StringT=StringX; \n end \n if SHOW==2, xlabel([StringY,String])\n else, xlabel([StringX,String]), ylabel(StringY), end\n drawnow\nend\n\nif SHOW\n str1=num2str(abs(k-nselect)); str='s';\n if k>nselect, \n if k==nselect+1, str1='one'; str=''; end\n fprintf('\\n\\nDetected %s additional eigenpair%s.',str1,str)\n end\n if k0, ShowLambda(diag(Rschur)); else, fprintf('\\n'); end\n\n Str='time_needed'; DispResult(Str,eval(Str))\n if (k>0)\n if ~SCHUR\n Str='norm(MV(X)-X*Lambda)'; DispResult(Str,eval(Str))\n end\n Str='norm(MV(Qschur)-Qschur*Rschur)'; DispResult(Str,eval(Str))\n I=eye(k); Str='norm(Qschur''*Qschur-I)'; DispResult(Str,eval(Str)) \n end\n fprintf('\\n\\n')\n\nend\n\nif nargout == 0, if ~SHOW, eigenvalues=diag(Rschur), end, return, end\n[varargout{1:nargout}]=output(history,X,Lambda);\n\nreturn\n\n%===========================================================================\n%======= PREPROCESSING =====================================================\n%===========================================================================\n\n%======= INITIALIZE SUBSPACE ===============================================\nfunction [V,W,R,E,M]=SetInitialSpaces(V,nselect,tau,jmin,tol,W,E);\n%[V,W,R,E,M]=SetInitialSpaces(VV,nselect,tau,jmin,tol);\n% Output: V(:,1:SIZE(VV,2))=ORTH(VV),\n% V'*V=W'*W=EYE(JMIN), M=W'*V;\n% such that A*V-tau*V=W*R+Qschur*E, \n% with R upper triangular, and E=Qschur'*(A*V-tau*V).\n%\n%[V,W,R,E,M]=SetInitialSpaces(VV,nselect,tau,jmin,tol,AV,EE);\n% Input such that\n% A*VV-tau*VV=AV+Qschur*EE, EE=Qschur'*(A*VV-tau*VV);\n%\n% Output: V(:,1:SIZE(VV,2))=ORTH(VV),\n% V'*V=W'*W=EYE(JMIN), M=W'*V;\n% such that A*V-tau*V=W*R+Qschur*E, \n% with R upper triangular, and E=Qschur'*(A*V-tau*V).\n\nglobal Qschur Rschur\n\n[n,j]=size(V); k=size(Qschur,2);\n\nif j>1, \n [V,R]=qr(V,0);\n if nargin <6, \n W=MV(V); R=eye(j); if tau~=0, W=W-tau*V; end\n if k>0, E=Qschur'*W; W=W-Qschur*E; else, E=zeros(0,j); end\n end\n [V,W,R,E,M]=CheckForNullSpace(V,nselect,tau,tol,W,E,R);\n l=size(Qschur,2); j=size(V,2);\n if l>=nselect, if size(V,2)==0; R=1; M=1; return, end, end\n if l>k, UpdateMinv(Qschur(:,k+1:l),0); end, k=l;\nend\nif j==0, nr=0;\n while nr==0\n V = ones(n,1)+0.1*rand(n,1); V=RepGS(Qschur,V); nr=norm(V);\n end, j=1;\nend\nif j==1\n [V,H,E]=Arnoldi(V,tau,jmin,nselect,tol); \n l=size(Qschur,2); j=max(size(H,2),1);\n if l>=nselect, W=V; R=eye(j); M=R; return, end\n if l>k, UpdateMinv(Qschur(:,k+1:l),0); end\n [Q,R]=qr(full(H),0);\n W=V*Q; V(:,j+1)=[]; M=Q(1:j,:)';\n %% W=V*Q; V=V(:,1:j)/R; E=E/R; R=eye(j); M=Q(1:j,:)'/R;\n %% W=V*H; V(:,j+1)=[];R=R'*R; M=H(1:j,:)';\nend\n\nreturn\n%%%======== ARNOLDI (for initializing spaces) ===============================\nfunction [V,H,E]=Arnoldi(v,tau,jmin,nselect,tol)\n%\n%[V,AV,H,nMV,tau]=ARNOLDI(A,V0,TAU,JMIN,NSELECT,TOL)\n% ARNOLDI computes the Arnoldi factorization of dimenison JMIN+1:\n% (A-tau)*V(:,1:JMIN)=V*H where V is n by JMIN+1 orthonormal with\n% first column a multiple of V0, and H is JMIN+1 by JMIN Hessenberg.\n%\n% If an eigenvalue if H(1:j,1:j) is an eigenvalue of A\n% within the required tolerance TOL then the Schurform\n% A*Qschur=Qschur*Rschur is expanded and the Arnoldi factorization\n% (A-tau)*V(:,1:j)=V(:,1:j+1)*H(1:j+1,1:j) is deflated.\n% Returns if size(Qschur,2) = NSELECT or size(V,2) = JMIN+1\n\n% (A-tau)*V(:,1:JMIN)=V*H+Qschur*E, Qschur'*V=0\n\n% Coded November 5, 1998, G. Sleijpen\n\nglobal Qschur Rschur\n\nk=size(Qschur,2); [n,j]=size(v);\n\nif ischar(tau), tau=0; end\n\nH=zeros(1,0); V=zeros(n,0); E=[];\nj=0; nr=norm(v);\n\nwhile j=tol\n v=v/nr; V=[V,v]; j=j+1;\n Av=MV(v);\n end\n if j==0 \n H=zeros(1,0); j=1;\n nr=0; while nr==0, v=RepGS(Qschur,rand(n,1)); nr=norm(v); end\n v=v/nr; V=v; Av=MV(v);\n end\n if tau~=0; Av=Av-tau*v; end, [v,e] = RepGS(Qschur,Av,0);\n if k==0, E=zeros(0,j); else, E = [E,e(1:k,1)]; end\n [v,y] = RepGS(V,v,0); H = [H,y(1:j,1)];\n nr = norm(v); H = [H;zeros(1,j-1),nr];\n [Q,U,H1] = DeflateHess(full(H),tol); \n j=size(U,2); l=size(Q,2);\n if l>0 %--- expand Schur form ------\n Qschur=[Qschur,V*Q]; \n Rschur=[Rschur,E*Q; zeros(l,k),H1(1:l,1:l)+tau*eye(l)]; k=k+l;\n E=[E*U;H1(1:l,l+1:l+j)];\n if j>0, V=V*U; H=H1(l+1:l+j+1,l+1:l+j);\n else, V=zeros(n,0); H=zeros(1,0); end\n end\nend % while\n\nif nr>=tol\n v=v/nr; V=[V,v]; \nend\n\nreturn\n%----------------------------------------------------------------------\nfunction [Q,U,H]=DeflateHess(H,tol)\n% H_in*[Q,U]=[Q,U]*H_out such that H_out(K,K) upper triangular\n% where K=1:SIZE(Q,2) and ABS(Q(end,2)*H_in(j+1,j))=nselect, return, end\n\n CHECK=1; l=k;\n\n [S,T,Z,Q]=qz(R,M); Z=Z';\n while CHECK \n I=SortEigPairVar(S,T,2); [Q,Z,S,T]=SwapQZ(Q,Z,S,T,I(1)); \n s=abs(S(1,1)); t=min(abs(T(1,1)),1); CHECK=(s*sqrt(1-t*t)=tol,\n W=W+r*s; M=M+s'*(r'*V); \n if nrs^2>eps, [W,R0]=qr(W,0); R=R0*R; M=R0'\\M; end\n end\n\n S=R; T=M;\n\n CHECK=(k0);\n end\n end\n\nreturn\n\n\n%===========================================================================\n%======= POSTPROCESSING ====================================================\n%===========================================================================\nfunction Refine(V,gamma);\n\nif gamma==0, return, end\n\nglobal Qschur Rschur\n\n J=1:size(Rschur,1); \n\n if gamma==1, \n [V,R]=qr(V(:,J),0); W=MV(V); M=V'*W;\n [U,Rschur]=schur(M);\n [U,Rschur]=rsf2csf(U,Rschur); Qschur=V*U;\n return \n elseif gamma==2\n [V,R]=qr(V,0); W=MV(V); M=V'*W;\n [U,S]=schur(M); [U,S]=rsf2csf(U,S); \n R=R*U; F=R'*R-S'*S;\n [X,Lambda]=Jordan(S); \n % Xinv=inv(X); D=sqrt(diag(Xinv*Xinv')); X=X*diag(D);\n [d,I]=sort(abs(diag(X'*F*X)));\n [U,S]=SwapSchur(U,S,I(J));\n Qschur=V*U(:,J); Rschur=S(J,J);\n end\n\nreturn\n\n%===========================================================================\nfunction CheckSortSchur(sigma)\nglobal Qschur Rschur\n\nk=size(Rschur,1); if k==0, return, end\n\nI=SortEig(diag(Rschur),sigma);\n\nif ~min((1:k)'==I)\n [U,Rschur]=SwapSchur(eye(k),Rschur,I);\n Qschur=Qschur*U;\nend\n\nreturn\n\n%%%=========== COMPUTE SORTED JORDAN FORM ==================================\nfunction [X,Jordan]=Jordan(S)\n% [X,J]=JORDAN(S)\n% For S k by k upper triangular matrix with ordered diagonal elements,\n% JORDAN computes the Jordan decomposition.\n% X is a k by k matrix of vectors spanning invariant spaces.\n% If J(i,i)=J(i+1,i+1) then X(:,i)'*X(:,i+1)=0.\n% J is a k by k matrix, J is Jordan such that S*X=X*J.\n% diag(J)=diag(S) are the eigenvalues\n\n% coded by Gerard Sleijpen, Januari 14, 1998\n\nk=size(S,1); X=zeros(k); \nif k==0, Jordan=[]; return, end\n\n%%% accepted separation between eigenvalues:\ndelta=2*sqrt(eps)*norm(S,inf); delta=max(delta,10*eps);\n\nT=eye(k); s=diag(S); Jordan=diag(s);\nfor i=1:k\n I=[1:i]; e=zeros(i,1); e(i,1)=1;\n C=S(I,I)-s(i,1)*T(I,I); C(i,i)=1;\n j=i-1; q=[]; jj=0; \n while j>0\n if abs(C(j,j)) 2, varargout{nargout}=history; end\nif nargout > 3, varargout{3} = Qschur; varargout{4} = Rschur; end\nif nargout < 4 & size(X,2)<2\n varargout{1}=Qschur; varargout{2}=Rschur; return\nelse\n varargout{1}=X; varargout{2}=Lambda;\nend\n\nreturn\n\n%===========================================================================\n%===== UPDATE PRECONDITIONED SCHUR VECTORS =================================\n%===========================================================================\nfunction solved=UpdateMinv(u,solved)\n\nglobal Qschur PinvQ Pinv_u Pu L_precond\n\n if ~isempty(L_precond)\n if ~solved, Pinv_u=SolvePrecond(u); end\n Pu=[[Pu;u'*PinvQ],Qschur'*Pinv_u]; \n PinvQ=[PinvQ,Pinv_u]; \n solved=0;\n end\n\nreturn\n%===========================================================================\n%===== SOLVE CORRECTION EQUATION ===========================================\n%===========================================================================\nfunction t=Solve_pce(theta,u,r,lsolver,par,nit)\n\nglobal Qschur PinvQ Pinv_u Pu L_precond\n\n switch lsolver\n case 'exact'\n t = exact(theta,[Qschur,u],r);\n\n case 'iluexact'\n t = iluexact(theta,[Qschur,u],r);\n\n case {'gmres','bicgstab','olsen'}\n if isempty(L_precond) %%% no preconditioning\n\n t = feval(lsolver,theta,...\n [Qschur,u],[Qschur,u],1,r,spar(par,nit));\n\n else %%% solve left preconditioned system\n \n %%% compute vectors and matrices for skew projection\n Pinv_u=SolvePrecond(u); \n mu=[Pu,Qschur'*Pinv_u;u'*PinvQ,u'*Pinv_u];\n\n %%% precondion and project r\n r=SolvePrecond(r);\n r=SkewProj([Qschur,u],[PinvQ,Pinv_u],mu,r);\n\n %%% solve preconditioned system\n t = feval(lsolver,theta,...\n [Qschur,u],[PinvQ,Pinv_u],mu,r,spar(par,nit));\n end\n\n case {'cg','minres','symmlq'}\n if isempty(L_precond) %%% no preconditioning\n\n t = feval(lsolver,theta,...\n [Qschur,u],[Qschur,u],1,r,spar(par,nit));\n\n else %%% solve two-sided expl. precond. system\n\n %%% compute vectors and matrices for skew projection\n Pinv_u=SolvePrecond(u,'L'); \n mu=[Pu,Qschur'*Pinv_u;u'*PinvQ,u'*Pinv_u];\n\n %%% precondion and project r\n r=SolvePrecond(r,'L');\n r=SkewProj([Qschur,u],[PinvQ,Pinv_u],mu,r);\n\n %%% solve preconditioned system\n t = feval(lsolver,theta,...\n [Qschur,u],[PinvQ,Pinv_u],mu,r,spar(par,nit));\n\n %%% \"unprecondition\" solution\n t=SkewProj([PinvQ,Pinv_u],[Qschur,u],mu,t);\n t=SolvePrecond(t,'U');\n end\n \n end\n \nreturn\n%=======================================================================\n%======= LINEAR SOLVERS ================================================\n%=======================================================================\nfunction x = exact(theta,Q,r)\n\nglobal A_operator\n\n [n,k]=size(Q); [n,l]=size(r);\n\n if ischar(A_operator)\n [x,xtol]=bicgstab(theta,Q,Q,1,r,[5.0e-14/norm(r),200,4]);\n return\n end\n\n x = [A_operator-theta*speye(n,n),Q;Q',zeros(k,k)]\\[r;zeros(k,l)];\n x = x(1:n,1:l); \n\nreturn\n%----------------------------------------------------------------------\nfunction x = iluexact(theta,Q,r)\n\nglobal L_precond U_precond\n\n [n,k]=size(Q); [n,l]=size(r);\n\n y = L_precond\\[r,Q]; \n x = [U_precond,y(:,l+1:k+1);Q',zeros(k,k)]\\[y(:,1:l);zeros(k,l)]; \n x = x(1:n,1:l); \n \nreturn\n%----------------------------------------------------------------------\nfunction r = olsen(theta,Q,Z,M,r,par)\nreturn\n%\n%======= Iterative methods =============================================\n%\nfunction x = bicgstab(theta,Q,Z,M,r,par)\n% BiCGstab(ell)\n% [x,rnrm] = bicgstab(theta,Q,Z,M,r,par)\n% Computes iteratively an approximation to the solution \n% of the linear system Q'*x = 0 and Atilde*x=r \n% where Atilde=(I-Z*M^(-1)*Q')*(U\\L\\(A-theta)).\n%\n% This function is specialized for use in JDQZ.\n% integer nmv: number of matrix multiplications\n% rnrm: relative residual norm\n%\n% par=[tol,mxmv,ell] where \n% integer m: max number of iteration steps\n% real tol: residual reduction\n%\n% nmv: number of MV with Atilde\n% rnrm: obtained residual reduction\n%\n% -- References: ETNA\n\n% Gerard Sleijpen (sleijpen@math.uu.nl)\n% Copyright (c) 1998, Gerard Sleijpen\n\n% -- Initialization --\n%\n\ntol=par(1); max_it=par(2); l=par(3); n=size(r,1);\nrnrm=1; nmv=0;\n \nif max_it==0 | tol>=1, x=r; return, end\n\nrnrm=norm(r); snrm=rnrm; tol=tol*rnrm;\n\nsigma=1; omega=1; \nx=zeros(n,1); u=zeros(n,1); tr=r;\n% hist=rnrm;\n% -- Iteration loop\nwhile (rnrm > tol) & (nmv <= max_it)\n\n sigma=-omega*sigma;\n for j = 1:l,\n rho=tr'*r(:,j); bet=rho/sigma;\n u=r-bet*u;\n %%%%%% u(:,j+1)=Atilde*u(:,j)\n u(:,j+1)=mvp(theta,Q,Z,M,u(:,j)); \n sigma=tr'*u(:,j+1); alp=rho/sigma;\n x=x+alp*u(:,1);\n r=r-alp*u(:,2:j+1);\n %%%%%% r(:,j+1)=Atilde*r(:,j)\n r(:,j+1)=mvp(theta,Q,Z,M,r(:,j));\n end\n\n gamma=r(:,2:l+1)\\r(:,1); omega=gamma(l,1);\n x=x+r*[gamma;0]; u=u*[1;-gamma]; r=r*[1;-gamma];\n\n rnrm = norm(r); nmv = nmv+2*l;\n % hist=[hist,rnrm];\nend\n % figure(3),\n % plot([0:length(hist)-1]*2*l,log10(hist/snrm),'-*'),\n % drawnow, \n\nrnrm = rnrm/snrm;\n\nreturn\n%----------------------------------------------------------------------\nfunction v = gmres(theta,Q,Z,M,v,par)\n% GMRES\n% [x,rnrm] = gmres(theta,Q,Z,M,b,par)\n% Computes iteratively an approximation to the solution \n% of the linear system Q'*x = 0 and Atilde*x=b \n% where Atilde=(I-Z*M^(-1)*Q')*(U\\L\\(A-theta)).\n%\n% par=[tol,m] where\n% integer m: degree of the minimal residual polynomial\n% real tol: residual reduction\n%\n% nmv: number of MV with Atilde\n% rnrm: obtained residual reduction\n%\n% -- References: Saad\n\n% Gerard Sleijpen (sleijpen@math.uu.nl)\n% Copyright (c) 1998, Gerard Sleijpen\n\n% -- Initialization\n\ntol=par(1); n = size(v,1); max_it=min(par(2),n);\nrnrm = 1; nmv=0; \n\nif max_it==0 | tol>=1, return, end\n \nH = zeros(max_it +1,max_it); Rot=[ones(1,max_it);zeros(1,max_it)];\n\nrnrm = norm(v); v = v/rnrm; V = [v];\ntol = tol * rnrm; snrm = rnrm;\ny = [ rnrm ; zeros(max_it,1) ];\nj=0; % hist=rnrm;\nwhile (nmv < max_it) & (rnrm > tol),\n j=j+1; nmv=nmv+1;\n v=mvp(theta,Q,Z,M,v); \n % [v, H(1:j+1,j)] = RepGS(V,v); \n [v,h] = RepGS(V,v); H(1:size(h,1),j)=h; \n V = [V, v]; \n for i = 1:j-1,\n a = Rot(:,i);\n H(i:i+1,j) = [a'; -a(2) a(1)]*H(i:i+1,j);\n end\n J=[j, j+1];\n a=H(J,j);\n if a(2) ~= 0\n cs = norm(a); \n a = a/cs; Rot(:,j) = a;\n H(J,j) = [cs; 0];\n y(J) = [a'; -a(2) a(1)]*y(J);\n end \n rnrm = abs(y(j+1)); \n % hist=[hist,rnrm];\nend\n % figure(3)\n % plot([0:length(hist)-1],log10(hist/snrm),'-*')\n % drawnow, pause\n\nJ=[1:j];\nv = V(:,J)*(H(J,J)\\y(J));\nrnrm = rnrm/snrm;\n\nreturn\n%======================================================================\n%========== BASIC OPERATIONS ==========================================\n%======================================================================\nfunction v=MV(v)\n\nglobal A_operator nm_operations\n\nif ischar(A_operator)\n v = feval(A_operator,v);\nelse\n v = A_operator*v;\nend\n\nnm_operations = nm_operations+1;\n\nreturn\n%----------------------------------------------------------------------\nfunction v=mvp(theta,Q,Z,M,v)\n% v=Atilde*v\n\n v = MV(v) - theta*v;\n v = SolvePrecond(v);\n v = SkewProj(Q,Z,M,v);\n \nreturn\n%----------------------------------------------------------------------\nfunction u=SolvePrecond(u,flag);\n\nglobal L_precond U_precond\n\nif isempty(L_precond), return, end\n\nif nargin<2\n\n if ischar(L_precond)\n if ischar(U_precond)\n u=feval(L_precond,u,U_precond); \n elseif isempty(U_precond)\n u=feval(L_precond,u); \n else\n u=feval(L_precond,u,'L'); u=feval(L_precond,u,'U'); \n end\n else\n u=U_precond\\(L_precond\\u); \n end\n\nelse\n\n switch flag\n case 'U'\n if ischar(L_precond), u=feval(L_precond,u,'U'); else, u=U_precond\\u; end\n\n case 'L'\n if ischar(L_precond), u=feval(L_precond,u,'L'); else, u=L_precond\\u; end\n\n end\nend\n\nreturn\n%----------------------------------------------------------------------\nfunction r=SkewProj(Q,Z,M,r);\n\n if ~isempty(Q), \n r=r-Z*(M\\(Q'*r));\n end \n\nreturn\n%----------------------------------------------------------------------\nfunction ppar=spar(par,nit)\n% Changes par=[tol(:),max_it,ell] to\n% ppap=[TOL,max_it,ell] where \n% if lenght(tol)==1\n% TOL=tol\n% else\n% red=tol(end)/told(end-1); tole=tol(end);\n% tol=[tol,red*tole,red^2*tole,red^3*tole,...]\n% TOL=tol(nit);\n% end\n\nk=size(par,2)-2;\nppar=par(1,k:k+2);\n\nif k>1\n if nit>k\n ppar(1,1)=par(1,k)*((par(1,k)/par(1,k-1))^(nit-k));\n else\n ppar(1,1)=par(1,max(nit,1));\n end\nend\n\nppar(1,1)=max(ppar(1,1),1.0e-8);\n\nreturn\n%\n%======= Iterative methods for symmetric systems =======================\n%\nfunction x = cg(theta,Q,Z,M,r,par)\n% CG\n% [x,rnrm] = cg(theta,Q,Z,M,b,par)\n% Computes iteratively an approximation to the solution \n% of the linear system Q'*x = 0 and Atilde*x=b \n% where Atilde=(I-Z*M^(-1)*Q')*(U\\L\\(A-theta)).\n%\n% par=[tol,m] where\n% integer m: degree of the minimal residual polynomial\n% real tol: residual reduction\n%\n% nmv: number of MV with Atilde\n% rnrm: obtained residual reduction\n%\n% -- References: Hestenes and Stiefel\n\n% Gerard Sleijpen (sleijpen@math.uu.nl)\n% Copyright (c) 1998, Gerard Sleijpen\n\n% -- Initialization\n\n\ntol=par(1); max_it=par(2); n = size(r,1);\nrnrm = 1; nmv=0; \n\n b=r;\n\nif max_it ==0 | tol>=1, x=r; return, end\n \nx= zeros(n,1); u=zeros(n,1);\n\nrho = norm(r); snrm = rho; rho = rho*rho; \ntol = tol*tol*rho; \nsigma=1;\n\nwhile ( rho > tol & nmv < max_it )\n\n beta=rho/sigma; \n u=r-beta*u;\n y=smvp(theta,Q,Z,M,u); nmv=nmv+1; \n sigma=y'*r; alpha=rho/sigma; \n x=x+alpha*u; \n r=r-alpha*y; sigma=-rho; rho=r'*r; \n\nend % while\n\nrnrm=sqrt(rho)/snrm;\n\nreturn\n%----------------------------------------------------------------------\nfunction x = minres(theta,Q,Z,M,r,par)\n% MINRES\n% [x,rnrm] = minres(theta,Q,Z,M,b,par)\n% Computes iteratively an approximation to the solution \n% of the linear system Q'*x = 0 and Atilde*x=b \n% where Atilde=(I-Z*M^(-1)*Q')*(U\\L\\(A-theta)).\n%\n% par=[tol,m] where\n% integer m: degree of the minimal residual polynomial\n% real tol: residual reduction\n%\n% nmv: number of MV with Atilde\n% rnrm: obtained residual reduction\n%\n% -- References: Paige and Saunders\n\n% Gerard Sleijpen (sleijpen@math.uu.nl)\n% Copyright (c) 1998, Gerard Sleijpen\n\n% -- Initialization\n\n\ntol=par(1); max_it=par(2); n = size(r,1);\nrnrm = 1; nmv=0; \n\nif max_it ==0 | tol>=1, x=r; return, end\n\nx=zeros(n,1); rho = norm(r); v = r/rho; snrm=rho;\nbeta = 0; v_old = zeros(n,1); \nbeta_t = 0; c = -1; s = 0;\nw = zeros(n,1); www = v;\n\ntol=tol*rho;\n\nwhile ( nmv < max_it & abs(rho) > tol )\n\n wv =smvp(theta,Q,Z,M,v)-beta*v_old; nmv=nmv+1; \n alpha = v'*wv; wv = wv-alpha*v;\n beta = norm(wv); v_old = v; v = wv/beta;\n\n l1 = s*alpha - c*beta_t; l2 = s*beta;\n\n alpha_t = -s*beta_t - c*alpha; beta_t = c*beta;\n l0 = sqrt(alpha_t*alpha_t+beta*beta); \n c = alpha_t/l0; s = beta/l0;\n\n ww = www - l1*w; www = v - l2*w; w = ww/l0;\n\n x = x + (rho*c)*w; rho = s*rho; \n\nend % while\n\nrnrm=abs(rho)/snrm;\n\nreturn\n\n%----------------------------------------------------------------------\nfunction x = symmlq(theta,Q,Z,M,r,par)\n% SYMMLQ\n% [x,rnrm] = symmlq(theta,Q,Z,M,b,par)\n% Computes iteratively an approximation to the solution \n% of the linear system Q'*x = 0 and Atilde*x=b \n% where Atilde=(I-Z*M^(-1)*Q')*(U\\L\\(A-theta)).\n%\n% par=[tol,m] where\n% integer m: degree of the minimal residual polynomial\n% real tol: residual reduction\n%\n% nmv: number of MV with Atilde\n% rnrm: obtained residual reduction\n%\n% -- References: Paige and Saunders\n\n% Gerard Sleijpen (sleijpen@math.uu.nl)\n% Copyright (c) 1998, Gerard Sleijpen\n\n% -- Initialization\n\n\ntol=par(1); max_it=par(2); n = size(r,1);\nrnrm = 1; nmv=0; \n\nif max_it ==0 | tol>=1, x=r; return, end\n\nx=zeros(n,1); rho = norm(r); v = r/rho; snrm=rho;\nbeta = 0; beta_t = 0; c = -1; s = 0;\nv_old = zeros(n,1); w = v; gtt = rho; g = 0;\n \ntol=tol*rho;\n \nwhile ( nmv < max_it & rho > tol )\n\n wv = smvp(theta,Q,Z,M,v) - beta*v_old; nmv=nmv+1;\n alpha = v'*wv; wv = wv - alpha*v;\n beta = norm(wv); v_old = v; v = wv/beta;\n\n l1 = s*alpha - c*beta_t; l2 = s*beta; \n \n alpha_t = -s*beta_t - c*alpha; beta_t = c*beta;\n l0 = sqrt(alpha_t*alpha_t+beta*beta); \n c = alpha_t/l0; s = beta/l0;\n\n gt = gtt - l1*g; gtt = -l2*g; g = gt/l0;\n\n rho = sqrt(gt*gt+gtt*gtt); \n\n x = x + (g*c)*w + (g*s)*v;\n w = s*w - c*v; \n \nend % while\n\nrnrm=rho/snrm; \n\nreturn\n\n%----------------------------------------------------------------------\nfunction v=smvp(theta,Q,Z,M,v)\n% v=Atilde*v\n\n v = SkewProj(Z,Q,M,v);\n v = SolvePrecond(v,'U');\n v = MV(v) - theta*v; \n v = SolvePrecond(v,'L');\n v = SkewProj(Q,Z,M,v);\n \nreturn\n%=======================================================================\n%========== Orthogonalisation ==========================================\n%=======================================================================\nfunction [v,y]=RepGS(V,v,gamma)\n% [v,y]=REP_GS(V,w)\n% If V orthonormal then [V,v] orthonormal and w=[V,v]*y;\n% If size(V,2)=size(V,1) then w=V*y;\n%\n% The orthonormalisation uses repeated Gram-Schmidt\n% with the Daniel-Gragg-Kaufman-Stewart (DGKS) criterion.\n%\n% [v,y]=REP_GS(V,w,GAMMA)\n% GAMMA=1 (default) same as [v,y]=REP_GS(V,w)\n% GAMMA=0, V'*v=zeros(size(V,2)) and w = V*y+v (v is not normalized).\n\n \n% coded by Gerard Sleijpen, August 28, 1998\n\nif nargin < 3, gamma=1; end\n\n[n,d]=size(V);\n\nif size(v,2)==0, y=zeros(d,0); return, end\n\nnr_o=norm(v); nr=eps*nr_o; y=zeros(d,1);\nif d==0\n if gamma, v=v/nr_o; y=nr_o; else, y=zeros(0,1); end, return\nend\n\ny=V'*v; v=v-V*y; nr_n=norm(v); ort=0;\n\nwhile (nr_n<0.5*nr_o & nr_n > nr)\n s=V'*v; v=v-V*s; y=y+s; \n nr_o=nr_n; nr_n=norm(v); ort=ort+1; \nend\n\nif nr_n <= nr, if ort>2, disp(' dependence! '), end\n if gamma % and size allows, expand with a random vector\n if d0, [Q,S]=rsf2csf(Q,S); end\n\n%%%------ find order eigenvalues ---------------\n I = SortEig(diag(S),sigma); \n\n%%%------ reorder schur form ----------------\n [Q,S] = SwapSchur(Q,S,I(1:kk)); \n\nreturn\n%----------------------------------------------------------------------\nfunction I=SortEig(t,sigma);\n%I=SortEig(T,SIGMA) sorts the indices of T.\n%\n% T is a vector of scalars, \n% SIGMA is a string or a vector of scalars.\n% I is a permutation of (1:LENGTH(T))' such that:\n% if SIGMA is a vector of scalars then\n% for K=1,2,...,LENGTH(T) with KK = MIN(K,SIZE(SIGMA,1))\n% ABS( T(I(K))-SIGMA(KK) ) <= ABS( T(I(J))-SIGMA(KK) ) \n% SIGMA(kk)=INF: ABS( T(I(K)) ) >= ABS( T(I(J)) ) \n% for all J >= K\n\nif ischar(sigma)\n switch sigma\n case 'LM'\n [s,I]=sort(-abs(t));\n case 'SM'\n [s,I]=sort(abs(t));\n case 'LR';\n [s,I]=sort(-real(t));\n case 'SR';\n [s,I]=sort(real(t));\n case 'BE';\n [s,I]=sort(real(t)); I=twistdim(I,1);\n end\nelse\n\n [s,I]=sort(abs(t-sigma(1,1))); \n ll=min(size(sigma,1),size(t,1)-1);\n for j=2:ll\n if sigma(j,1)==inf\n [s,J]=sort(abs(t(I(j:end)))); J=flipdim(J,1);\n else\n [s,J]=sort(abs(t(I(j:end))-sigma(j,1)));\n end\n I=[I(1:j-1);I(J+j-1)];\n end \n\nend\n\nreturn\n%----------------------------------------------------------------------\nfunction t=twistdim(t,k)\n\n d=size(t,k); J=1:d; J0=zeros(1,2*d);\n J0(1,2*J)=J; J0(1,2*J-1)=flipdim(J,2); I=J0(1,J);\n if k==1, t=t(I,:); else, t=t(:,I); end\n\nreturn\n%----------------------------------------------------------------------\nfunction [Q,S]=SwapSchur(Q,S,I)\n% [Q,S]=SwapSchur(QQ,SS,P)\n% QQ and SS are square matrices of size K by K\n% P is the first part of a permutation of (1:K)'.\n%\n% If M = QQ*SS*QQ' and QQ'*QQ = EYE(K), SS upper triangular\n% then M*Q = Q*S with Q'*Q = EYE(K), S upper triangular\n% and D(1:LENGTH(P))=DD(P) where D=diag(S), DD=diag(SS)\n%\n% Computations uses Givens rotations.\n\n kk=min(length(I),size(S,1)-1);\n j=1; while (j<=kk & j==I(j)), j=j+1; end; \n while j<=kk\n i=I(j);\n for k=i-1:-1:j\n q = [S(k,k)-S(k+1,k+1),S(k,k+1)];\n if q(1) ~= 0\n q = q/norm(q);\n G = [[q(2);-q(1)],q'];\n J = [k,k+1];\n Q(:,J) = Q(:,J)*G;\n S(:,J) = S(:,J)*G;\n S(J,:) = G'*S(J,:);\n end\n S(k+1,k) = 0;\n end\n I=I+(I=0,\n% scale B by a scalar G such that NORM(G*B)=1 and G*B(2)>=0,\n% then D(A,B)=ABS((F*A)*RROT(G*B)) where RROT(alpha,beta)=(beta,-alpha)\n\n\n% coded by Gerard Sleijpen, version Januari 14, 1998\n\nn=sign(t); n=n+(n==0); t=abs(t./n); s=s./n; \n\nif ischar(sigma)\n switch sigma\n case {'LM','SM'}\n case {'LR','SR','BE'}\n s=real(s);\n end\n [s,I]=sort((-t./sqrt(s.*conj(s)+t.*t)));\n switch sigma\n case {'LM','LR'}\n I=flipdim(I,1);\n case {'SM','SR'}\n case 'BE'\n I=twistdim(I,1); \n end\nelse\n\n n=sqrt(sigma.*conj(sigma)+1); ll=size(sigma,1); \n tau=[ones(ll,1)./n,-sigma./n]; tau=tau.';\n\n n=sqrt(s.*conj(s)+t.*t); s=[s./n,t./n];\n\n [t,I]=sort(abs(s*tau(:,1))); \n ll = min(ll,size(I,1)-1); \n for j=2:ll\n [t,J]=sort(abs(s(I(j:end),:)*tau(:,j))); \n I=[I(1:j-1);I(J+j-1)];\n end \n\nend\n\nreturn\n\n%----------------------------------------------------------------------\nfunction [Q,Z,S,T]=SwapQZ(Q,Z,S,T,I)\n% [Q,Z,S,T]=SwapQZ(QQ,ZZ,SS,TT,P)\n% QQ and ZZ are K by K unitary, SS and TT are K by K uper triangular.\n% P is the first part of a permutation of (1:K)'.\n%\n% Then Q and Z are K by K unitary, S and T are K by K upper triangular,\n% such that, for A = ZZ*SS*QQ' and B = ZZ*T*QQ', we have \n% A*Q = Z*S, B*Q = Z*T and LAMBDA(1:LENGTH(P))=LLAMBDA(P) where \n% LAMBDA=DIAG(S)./DIAGg(T) and LLAMBDA=DIAG(SS)./DIAG(TT).\n%\n% Computation uses Givens rotations. \n%\n\n% coded by Gerard Sleijpen, version October 12, 1998\n \n\n kk=min(length(I),size(S,1)-1);\n j=1; while (j<=kk & j==I(j)), j=j+1; end\n while j<=kk\n i=I(j);\n for k = i-1:-1:j, \n %%% i>j, move ith eigenvalue to position j \n J = [k,k+1]; \n q = T(k+1,k+1)*S(k,J) - S(k+1,k+1)*T(k,J);\n if q(1) ~= 0 \n q = q/norm(q);\n G = [[q(2);-q(1)],q'];\n Q(:,J) = Q(:,J)*G; \n S(:,J) = S(:,J)*G; T(:,J) = T(:,J)*G;\n end \n if abs(S(k+1,k)) 0)\n if n==-1\n n=s; eval('v=feval(A_operator,zeros(n,0));','n=-1;')\n if n>-1, J=[J,jj]; end\n end\n else\n if isempty(sigma), sigma=s; \n elseif ischar(sigma) & isempty(L_precond)\n ok=1; eval('v=feval(sigma0,zeros(n,1));','ok=0')\n if ok, L_precond=sigma0; sigma=s; end\n end, J=[J,jj]; \n end \nend\nvarg(J)=[];\n\nif n==-1,\n msg1=sprintf(' Cannot find the dimension of ''%s''. \\n',A_operator);\n msg2=sprintf(' Put the dimension n in the parameter list: \\n like');\n msg3=sprintf('\\t\\n\\n\\t jdqr(''%s'',n,..), \\n\\n',A_operator);\n msg4=sprintf(' or let\\n\\n\\t n = %s(',A_operator);\n msg5=sprintf('[],''dimension'')\\n\\n give n.');\n msg=[msg1,msg2,msg3,msg4,msg5];\n errordlg(msg,'MATRIX')\nend\n\nnselect=[]; \nif n<2, return, end\n\nif length(varg) == 1\n nselect=min(n,varg);\nelseif length(varg)>1\n if isempty(sigma), sigma=varg(end); varg(end)=[]; end\n nselect=min(n,min(varg));\nend\n\nfopts = []; if ~isempty(options), fopts=fields(options); end\n\nif isempty(L_precond) \n if strmatch('Precond',fopts) \n L_precond = options.Precond;\n elseif strmatch('L_Precond',fopts)\n L_precond = options.L_Precond;\n end\nend\n\nif isempty(U_precond) & strmatch('U_Precond',fopts)\n U_precond = options.U_Precond;\nend\n\nif isempty(L_precond), ls_tol = [0.7,0.49]; end\nif ~isempty(L_precond) & ischar(L_precond)\n if exist(L_precond) ~=2\n msg=sprintf(' Can not find the M-file ''%s.m'' ',L_precond); n=-1;\n elseif ~isempty(U_precond) & ~ischar(U_precond) & n>0\n msg=sprintf(' L and U should both be strings or matrices'); n=-1;\n elseif strcmp(L_precond,U_precond)\n eval('v=feval(L_precond,zeros(n,1),''L'');','n=-1;')\n eval('v=feval(L_precond,zeros(n,1),''U'');','n=-1;')\n if n<0\n msg='L and U use the same M-file';\n msg1=sprintf(' %s.m \\n',L_precond);\n msg2='Therefore L and U are called';\n msg3=sprintf(' as\\n\\n\\tw=%s(v,''L'')',L_precond); \n msg4=sprintf(' \\n\\tw=%s(v,''U'')\\n\\n',L_precond); \n msg5=sprintf('Check the dimensions and/or\\n');\n msg6=sprintf('put this \"switch\" in %s.m.',L_precond);\n msg=[msg,msg1,msg2,msg3,msg4,msg5,msg6];\n else\n U_precond=0;\n end \n elseif ischar(A_operator) & strcmp(A_operator,L_precond) \n U_precond='preconditioner';\n eval('v=feval(L_precond,zeros(n,1),U_precond);','n=-1;')\n if n<0\n msg='Preconditioner and matrix use the same M-file';\n msg1=sprintf(' %s. \\n',L_precond);\n msg2='Therefore the preconditioner is called';\n msg3=sprintf(' as\\n\\n\\tw=%s(v,''preconditioner'')\\n\\n',L_precond); \n msg4='Put this \"switch\" in the M-file.';\n msg=[msg,msg1,msg2,msg3,msg4];\n end \n else\n eval('v=feval(L_precond,zeros(n,1));','n=-1')\n if n<0\n msg=sprintf('''%s'' should produce %i-vectors',L_precond,n); \n end\n end\nend\n\nUd=1;\nif ~isempty(L_precond) & ~ischar(L_precond) & n>0\n if ~isempty(U_precond) & ischar(U_precond)\n msg=sprintf(' L and U should both be strings or matrices'); n=-1;\n elseif ~isempty(U_precond)\n if ~min([n,n]==size(L_precond) & [n,n]==size(U_precond))\n msg=sprintf('Both L and U should be %iX%i.',n,n); n=-1; \n end\n elseif min([n,n]==size(L_precond))\n U_precond=speye(n); Ud=0;\n elseif min([n,2*n]==size(L_precond)) \n U_precond=L_precond(:,n+1:2*n); L_precond=L_precond(:,1:n);\n else \n msg=sprintf('The preconditioning matrix\\n');\n msg2=sprintf('should be %iX%i or %ix%i ([L,U]).\\n',n,n,n,2*n); \n msg=[msg,msg2]; n=-1;\n end\nend\nif n<0, errordlg(msg,'PRECONDITIONER'), return, end\n\nls_tol0=ls_tol;\nif strmatch('Tol',fopts), tol = options.Tol; end\n\nif isempty(nselect), nselect=min(n,5); end\n\nif strmatch('jmin',fopts), jmin=min(n,options.jmin); end \nif strmatch('jmax',fopts)\n jmax=min(n,options.jmax);\n if jmin<0, jmin=max(1,jmax-p1); end\nelse\n if jmin<0, jmin=min(n,nselect+p0); end\n jmax=min(n,jmin+p1); \nend \n\nif strmatch('MaxIt',fopts), maxit = abs(options.MaxIt); end\n\nif strmatch('v0',fopts);\n V = options.v0; \n [m,d]=size(V); \n if m~=n | d==0 \n if m>n, V = V(1:n,:); end\n nrV=norm(V); if nrV>0, V=V/nrV; end\n d=max(d,1);\n V = [V; ones(n-m,d) +0.1*rand(n-m,d)]; \n end\nelse\n V = ones(n,1) +0.1*rand(n,1); d=1;\nend\n\nif strmatch('TestSpace',fopts), INTERIOR = boolean(options.TestSpace,...\n [INTERIOR,0,1,1.1,1.2],strvcat('standard','harmonic'));\nend\n\nif isempty(sigma)\n if INTERIOR, sigma=0; else, sigma = 'LM'; end\nelseif ischar(sigma)\n switch sigma\n case {'LM','LR','SR','BE'}\n case {'SM'}\n sigma=0;\n otherwise\n if INTERIOR, sigma=0; else, sigma='LM'; end\n end\nend\n\nif strmatch('Schur',fopts), SCHUR = boolean(options.Schur,SCHUR); end\nif strmatch('Disp',fopts), SHOW = boolean(options.Disp,[SHOW,2]); end\nif strmatch('Pairs',fopts), PAIRS = boolean(options.Pairs,PAIRS); end\nif strmatch('AvoidStag',fopts),JDV = boolean(options.AvoidStag,JDV); end\nif strmatch('Track',fopts)\n OLD = boolean(options.Track,[OLD,0,OLD,inf],strvcat('no','yes')); end \nOLD=max(abs(OLD),10*tol);\n\nif strmatch('LSolver',fopts), lsolver = lower(options.LSolver); end\n\nswitch lsolver\n case {'exact'}\n L_precond=[]; \n if ischar(A_operator)\n msg=sprintf('The operator must be a matrix for ''exact''.');\n msg=[msg,sprintf('\\nDo you want to solve the correction equation')];\n msg=[msg,sprintf('\\naccurately with an iterative solver (BiCGstab)?')];\n button=questdlg(msg,'Solving exactly','Yes','No','Yes');\n if strcmp(button,'No'), n=-1; return, end\n end\n case {'iluexact'}\n if ischar(L_precond)\n msg=sprintf('The preconditioner must be matrices for ''iluexact''.');\n errordlg(msg,'Solving with ''iluexact''')\n n=-1; return\n end\n case {'olsen'}\n case {'cg','minres','symmlq'}\n ls_tol=1.0e-12;\n case 'gmres'\n ls_maxit=5;\n case 'bicgstab'\n ls_tol=1.0e-10;\n otherwise\n error(['Unknown method ''' lsolver '''.']);\nend\n\nif strmatch('LS_MaxIt',fopts), ls_maxit=abs(options.LS_MaxIt); end\nif strmatch('LS_Tol',fopts), ls_tol=abs(options.LS_Tol); end\nif strmatch('LS_ell',fopts), ell=round(abs(options.LS_ell)); end\n\npar=[ls_tol,ls_maxit,ell];\n\nif SHOW\n\n fprintf('\\n'),fprintf('PROBLEM\\n')\n if ischar(A_operator)\n fprintf(' A: ''%s''\\n',A_operator);\n elseif issparse(A_operator)\n fprintf(' A: [%ix%i sparse]\\n',n,n);\n else\n fprintf(' A: [%ix%i double]\\n',n,n);\n end\n fprintf(' dimension: %i\\n',n);\n fprintf(' nselect: %i\\n\\n',nselect);\n\n fprintf('TARGET\\n')\n if ischar(sigma)\n fprintf(' sigma: ''%s''',sigma)\n else \n Str=ShowLambda(sigma);\n fprintf(' sigma: %s',Str)\n end\n fprintf('\\n\\n')\n\n fprintf('OPTIONS\\n');\n fprintf(' Schur: %i\\n',SCHUR);\n fprintf(' Tol: %g\\n',tol);\n fprintf(' Disp: %i\\n',SHOW);\n fprintf(' jmin: %i\\n',jmin);\n fprintf(' jmax: %i\\n',jmax);\n fprintf(' MaxIt: %i\\n',maxit);\n fprintf(' v0: [%ix%i double]\\n',size(V));\n fprintf(' TestSpace: %g\\n',INTERIOR);\n fprintf(' Pairs: %i\\n',PAIRS);\n fprintf(' AvoidStag: %i\\n',JDV);\n fprintf(' Track: %g\\n',OLD);\n\n fprintf(' LSolver: ''%s''\\n',lsolver);\n\n\n switch lsolver\n case {'exact','iluexact','olsen'}\n case {'cg','minres','symmlq','gmres','bicgstab'}\n if length(ls_tol)>1\n fprintf(' LS_Tol: ['); fprintf(' %g',ls_tol); fprintf(' ]\\n');\n else\n fprintf(' LS_Tol: %g\\n',ls_tol); \n end\n fprintf(' LS_MaxIt: %i\\n',ls_maxit);\n end\n if strcmp(lsolver,'bicgstab')\n fprintf(' LS_ell: %i\\n',ell);\n end\n\n if isempty(L_precond)\n fprintf(' Precond: []\\n');\n else\n StrL='Precond'; StrU='U precond'; Us='double'; Ls=Us; ok=0;\n if issparse(L_precond), Ls='sparse'; end\n if ~isempty(U_precond) & Ud, StrL='L precond'; ok=1;\n if issparse(U_precond), Us='sparse'; end\n end\n if ischar(L_precond)\n fprintf('%13s: ''%s''\\n',StrL,L_precond);\n if ok \n if U_precond~=0 & ~strcmp(U_precond,'preconditioner')\n fprintf('%13s: ''%s''\\n',StrU,U_precond);\n else\n fprintf('%13s: ''%s''\\n',StrU,L_precond);\n end\n end\n else\n fprintf('%13s: [%ix%i %s]\\n',StrL,n,n,Ls);\n if ok & Ud, fprintf('%13s: [%ix%i %s]\\n',StrU,n,n,Us); end\n end \n end \n fprintf('\\n')\n\n string1='%13s: ''%s'''; string2='\\n\\t %s';\n switch INTERIOR\n case 0\n fprintf(string1,'TestSpace','Standard, W = V ')\n fprintf(string2,'V W: V orthogonal')\n fprintf(string2,'W=A*V')\n case 1\n fprintf(string1,'TestSpace','Harmonic, W = A*V - sigma*V')\n fprintf(string2,'V W: V and W orthogonal')\n fprintf(string2,'AV-Q*E=W*R where AV=A*V-sigma*V and E=Q''*AV')\n case 1.1\n fprintf(string1,'TestSpace','Harmonic, W = A*V - sigma*V')\n fprintf(string2,'V W AV: V and W orthogonal')\n fprintf(string2,'AV=A*V-sigma*V, AV-Q*Q''*AV=W*R')\n case 1.2\n fprintf(string1,'TestSpace','Harmonic, W = A*V - sigma*V')\n fprintf(string2,'V W: W orthogonal')\n fprintf(string2,'W=AV-Q*E where AV=A*V-sigma*V and E=Q''*AV')\n otherwise\n fprintf(string1,'TestSpace','Experimental')\n end % switch INTERIOR\n fprintf('\\n\\n')\nend % if SHOW\n\nif ischar(sigma) & INTERIOR >=1\n msg1=sprintf('\\n The choice sigma = ''%s'' does not match',sigma);\n msg2=sprintf('\\n the search for INTERIOR eigenvalues.');\n msg3=sprintf('\\n Specify a numerical value for sigma');\n msg4=sprintf(',\\n for instance, a value that is ');\n switch sigma\n case {'LM'}\n % sigma='SM';\n msg5=sprintf('absolute large.\\n');\n msg4=[msg4,msg5];\n case {'LR'}\n % sigma='SP'; % smallest positive real\n msg5=sprintf('positive large.\\n');\n msg4=[msg4,msg5];\n case {'SR'}\n % sigma='LN'; % largest negative real\n msg5=sprintf('negative and absolute large.\\n');\n msg4=[msg4,msg5];\n case {'BE'}\n % sigma='AS'; % alternating smallest pos., largest neg\n msg4=sprintf('.\\n');\n end\n msg=[msg1,msg2,msg3,msg4];\n msg5=sprintf(' Do you want to continue with sigma=0?');\n msg=[msg,msg5];\n button=questdlg(msg,'Finding Interior Eigenvalues','Yes','No','Yes');\n if strcmp(button,'Yes'), sigma=0, else, n=-1; end\nend\n\nreturn\n\n%-------------------------------------------------------------------\nfunction x = boolean(x,gamma,string)\n%Y = BOOLEAN(X,GAMMA,STRING)\n% GAMMA(1) is the default. \n% If GAMMA is not specified, GAMMA = 0.\n% STRING is a matrix of accepted strings. \n% If STRING is not specified STRING = ['no ';'yes']\n% STRING(I,:) and GAMMA(I) are accepted expressions for X \n% If X=GAMMA(I) then Y=X. If X=STRING(I,:), then Y=GAMMA(I+1).\n% For other values of X, Y=GAMMA(1);\n\nif nargin < 2, gamma=0; end\nif nargin < 3, string=strvcat('no','yes'); gamma=[gamma,0,1]; end\n\nif ischar(x)\n i=strmatch(lower(x),string,'exact'); \n if isempty(i),i=1; else, i=i+1; end, x=gamma(i);\nelseif max((gamma-x)==0)\nelseif gamma(end) == inf\nelse, x=gamma(1);\nend\n \nreturn\n%-------------------------------------------------------------------\nfunction possibilities\n fprintf('\\n')\n fprintf('PROBLEM\\n')\n fprintf(' A: [ square matrix | string ]\\n');\n fprintf(' nselect: [ positive integer {5} ]\\n\\n');\n fprintf('TARGET\\n')\n fprintf(' sigma: [ scalar | vector of scalars |\\n');\n fprintf(' ''LM'' | {''SM''} | ''LR'' | ''SR'' | ''BE'' ]\\n\\n');\n\n fprintf('OPTIONS\\n');\n fprintf(' Schur: [ yes | {no} ]\\n');\n fprintf(' Tol: [ positive scalar {1e-8} ]\\n');\n fprintf(' Disp: [ yes | {no} | 2 ]\\n');\n fprintf(' jmin: [ positive integer {nselect+5} ]\\n');\n fprintf(' jmax: [ positive integer {jmin+5} ]\\n');\n fprintf(' MaxIt: [ positive integer {200} ]\\n');\n fprintf(' v0: [ size(A,1) by p vector of scalars {rand(size(A,1),1)} ]\\n');\n fprintf(' TestSpace: [ Standard | {Harmonic} ]\\n');\n fprintf(' Pairs: [ yes | {no} ]\\n');\n fprintf(' AvoidStag: [ yes | {no} ]\\n');\n fprintf(' Track: [ {yes} | no | non-negative scalar {1e-4} ]\\n');\n fprintf(' LSolver: [ {gmres} | bicgstab ]\\n');\n fprintf(' LS_Tol: [ row of positive scalars {[1,0.7]} ]\\n');\n fprintf(' LS_MaxIt: [ positive integer {5} ]\\n');\n fprintf(' LS_ell: [ positive integer {4} ]\\n');\n fprintf(' Precond: [ n by 2n matrix | string {identity} ]\\n');\n fprintf('\\n')\n\nreturn\n%===========================================================================\n%============= OUTPUT FUNCTIONS ============================================\n%===========================================================================\nfunction varargout=ShowLambda(lambda,kk)\n\nfor k=1:size(lambda,1);\n if k>1, Str=[Str,sprintf('\\n%15s','')]; else, Str=[]; end\n rlambda=real(lambda(k,1)); ilambda=imag(lambda(k,1));\n Str=[Str,sprintf(' %+11.4e',rlambda)]; \n if abs(ilambda)>100*eps*abs(rlambda) \n if ilambda>0 \n Str=[Str,sprintf(' + %10.4ei',ilambda)];\n else\n Str=[Str,sprintf(' - %10.4ei',-ilambda)];\n end\n end\nend\n\nif nargout == 0\n if nargin == 2\n Str=[sprintf('\\nlambda(%i) =',kk),Str];\n else\n Str=[sprintf('\\nDetected eigenvalues:\\n\\n%15s',''),Str];\n end\n fprintf('%s\\n',Str)\nelse\n varargout{1}=Str;\nend\n\nreturn\n%===========================================================================\nfunction DispResult(s,nr,gamma)\n\n if nargin<3, gamma=0; end\n\n extra='';\n if nr > 100*eps & gamma\n extra=' norm > 100*eps !!! ';\n end\n\n if gamma<2 | nr>100*eps\n fprintf('\\n %35s: %0.5g\\t%s',s,nr,extra)\n end\n\nreturn\n%===========================================================================\nfunction STATUS0=MovieTheta(n,nit,Lambda,jmin,tau,LOCKED,SHRINK)\n% MovieTheta(n,nit,Lambda,jmin,tau,nr0, axis(MovieAxis), end, hold on\npls='bo'; if SHRINK, pls='mo'; end\n%plot(real(Lambda(jmin+1:end)),imag(Lambda(jmin+1:end)),pls)\n%plot(real(EigMATLAB),imag(EigMATLAB),'cp'); \nTHETA=diag(Rschur); %plot(real(THETA),imag(THETA),'k*');\n\nx=real(Lambda(1)); y=imag(Lambda(1));\n%plot(x,y,'kd'), pls='ks';\nif LOCKED, plot(x,y,'ks'), pls='ms'; end\n\nif ischar(tau), tau=0; end\ndelta=Lambda([1,jmin])-tau; \nif length(CIRCLE)~=2, delta=abs(delta); \n% plot(real(tau),imag(tau),pls)\nelse, delta=real(delta); end\nfor i=1:1+SHRINK, \n zeta=delta(i)*CIRCLE+tau;\n% plot(real(zeta),imag(zeta),'r:'), \nend\n\nif nit==0\n buttons(f,-1); hold off, zoom on\nend\ntitle('legend see figure(255)')\nif SHRINK, STATUS0=buttons(f,2); if STATUS0, return, end, end\nSTATUS0=buttons(f,1); drawnow, hold off\n\nreturn\n\n%=============================================================\nfunction Explanation(E,f)\n\n %if gcf~=f, figure(f), end\n\n HL=plot(0,0,'kh',0,0,'bo'); hold on\n StrL=str2mat('Detected eigenvalues','Approximate eigenvalues');\n if E\n HL=[HL;plot(0,0,'cp')];\n StrL=str2mat(StrL,'Exact eigenvenvalues');\n end\n HL=[HL;plot(0,0,'kd',0,0,'ks',0,0,'r:')];\n % StrL=str2mat(StrL,'Tracked app. eig.','target',...\n % 'inner/outer bounds for restart');\n StrL=str2mat(StrL,'Selected approximate eigenvalue','target',...\n 'inner/outer bounds for restart');\n\n legend(HL,StrL), hold on, drawnow, hold off\n title('legend for figure(256)')\n\nreturn\n\n%=============================================================\nfunction STATUS0=buttons(f,push)\n% push=0: do nothing\n% push>0: check status buttons,\n% STATUS0=1 if break else STATUS0=0.\n% push=-1: make buttons for pause and break\n% push=-2: remove buttons\n\nglobal M_STATUS MovieAxis\n\n if push>0 % check status buttons\n\n ud = get(f,'UserData'); \n if ud.pause ==1, M_STATUS=1; end \n if ud.break ==1, STATUS0=1;\n ud.pause=0; ud.break=0; set(f,'UserData',ud); return, \n else, STATUS0=0; end \n\n if push>1\n ud.pause=0; set(f,'UserData',ud); \n while M_STATUS\n ud = get(f,'UserData'); pause(0.1) \n if ud.pause, M_STATUS=0; end\n if ud.break, M_STATUS=0; STATUS0=1; end\n MovieAxis=axis; \n end\n ud.pause=0; ud.break=0; set(f,'UserData',ud);\n end\n\n\n elseif push==0, STATUS0=0; return\n elseif push==-1 % make buttons\n\n ud = [];\n h = findobj(f,'Tag','pause');\n if isempty(h)\n ud.pause = 0;\n pos = get(0,'DefaultUicontrolPosition');\n pos(1) = pos(1) - 15;\n pos(2) = pos(2) - 15;\n str = 'ud=get(gcf,''UserData''); ud.pause=1; set(gcf,''UserData'',ud);';\n uicontrol( ...\n 'Style','push', ...\n 'String','Pause', ...\n 'Position',pos, ...\n 'Callback',str, ...\n 'Tag','pause');\n else\n set(h,'Visible','on'); % make sure it's visible\n if ishold\n oud = get(f,'UserData');\n ud.pause = oud.pause; % don't change old ud.pause status\n else\n ud.pause = 0;\n end\n end\n h = findobj(f,'Tag','break');\n if isempty(h)\n ud.break = 0;\n pos = get(0,'DefaultUicontrolPosition');\n pos(1) = pos(1) + 50;\n pos(2) = pos(2) - 15;\n str = 'ud=get(gcf,''UserData''); ud.break=1; set(gcf,''UserData'',ud);';\n uicontrol( ...\n 'Style','push', ...\n 'String','Break', ...\n 'Position',pos, ...\n 'Callback',str, ...\n 'Tag','break');\n else\n set(h,'Visible','on'); % make sure it's visible\n if ishold\n oud = get(f,'UserData');\n ud.break = oud.break; % don't change old ud.break status\n else\n ud.break = 0;\n end\n end\n set(f,'UserData',ud); M_STATUS=0;\n\n STATUS0=0; hold off, zoom on\n\n MA=axis; nl=MA/10;\n MovieAxis = MA-max(nl([2,4])-nl([1,3]))*[1,-1,1,-1];\n\n else % remove buttons\n\n set(findobj(f,'Tag','pause'),'Visible','off');\n set(findobj(f,'Tag','break'),'Visible','off');\n STATUS0=0; return, refresh\n\n end\nreturn\n", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/dr/drtoolbox/techniques/jdqr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6979294285937754}} {"text": "% realproba() - compute the effective probability of the value \n% in the sample.\n%\n% Usage: \n% >> [probaMap, probaDist ] = realproba( data, discret);\n%\n% Inputs:\n% data - the data onto which compute the probability\n% discret - discretisation factor (default: (size of data)/5)\n% if 0 base the computation on a Gaussian \n% approximation of the data \n%\n% Outputs:\n% probaMap - the probabilities associated with the values\n% probaDist - the probabilities distribution \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 [ probaMap, sortbox ] = realproba( data, bins );\n\nif nargin < 1\n\thelp realproba;\n\treturn;\nend;\nif nargin < 2\n\tbins = round(size(data,1)*size(data,2)/5);\nend;\t\n\nif bins > 0\n\t% COMPUTE THE DENSITY FUNCTION\n\t% ----------------------------\n\tSIZE = size(data,1)*size(data,2);\n\tsortbox = zeros(1,bins);\n\tminimum = min(data(:));\n\tmaximum = max(data(:));\n\tdata = floor((data - minimum )/(maximum - minimum)*(bins-1))+1;\n if any(any(isnan(data))), warning('Binning failed - could be due to zeroed out channel'); end;\n\tfor index=1:SIZE\n\t\tsortbox(data(index)) = sortbox(data(index))+1;\n\tend;\n\tprobaMap = sortbox(data) / SIZE;\n\tsortbox = sortbox / SIZE;\nelse\n\t% BASE OVER ERROR FUNCTION\n\t% ------------------------\n\tdata = (data-mean(data(:)))./std(data(:));\n\tprobaMap = exp(-0.5*( data.*data ))/(2*pi);\n\tprobaMap = probaMap/sum(probaMap); % because the total surface under a normalized Gaussian is 2\n\tsortbox = probaMap/sum(probaMap);\nend;\nreturn;\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/realproba.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6979294266047931}} {"text": "function vwap = getVWAP(price, volume, dates)\n%GETVWAP: calculate the Volume Weighted Average Price at the end of each\n%day, given intra daily data of the closing price and volume.\n%\n% VWAP = GETVWAP(price, volume, dates) returns the Volume Weighted\n% Average Price (VWAP) at the end of the day. The input consists of the\n% intra-daily price, volume and dates (in formatted form).\n%\n% vwap: is a vector of the VWAP prices at the end of each\n% unique day, conditional on the dates.\n%\n% $Date: 04/10/2012$\n%\n% -------------------------------------------------------------------------\n\n% Not all securities publish their volume shares, i.e. sometimes the volume\n% vector is empty.\nif sum(volume) == 0, error('getVWAP:InvalidInput','No historical intra-daily data of volume'); end\nif size(price,2) > 1 || size(volume,2) > 1 || size(dates,2) > 1, error('getVWAP:InvalidInput','Price, volume and dates should be a row vector'); end\n\n\n% FIND THE UNIQUE DAYS. TWO OPTIONS ARE POSSIBLE:\n% -- 1 -- make use of the included GETUNIQUEDAYELEMENTS code (general \n% framework, adaptable for multi purposes, external)\n\nuniqueDays = getUniqueDayElements(dates);\nk = size(unique(day(dates)),1);\nvwap = zeros(1, k );\n\n% -- 2 -- get rid of the [EXTERNAL] GETUNIQUEDAYELEMENTS code and use the\n% following [INTERNAL] method:\n\n % k = size(unique(day(dates)),1);\n % vwap = zeros(1, k );\n % uniqueDays = zeros(1, k ); iter = 1; uniqueDays(iter) = day(dates(1));\n % \n % % find the unique days\n % for i = 2:size(dates,1);\n % if uniqueDays(iter) ~= day(dates(i));\n % iter = iter + 1;\n % uniqueDays(iter) = day(dates(i));\n % end\n % end\n\n% calculate vwap\nfor i = 1:size(uniqueDays,2)\n dayi = day(dates)==uniqueDays(i);\n vwap(i) = sum( volume(dayi) ...\n .*price( dayi ) ) / sum( volume( dayi ) );\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/36115-volume-weighted-average-price-from-intra-daily-data/getVWAP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6979294218292752}} {"text": "function result = RMS_amplitude(data)\n\nif size(data,1) < size(data,2)\n data = data';\nend\nresult = sqrt((data'*data)/(length(data)));\n\n\n", "meta": {"author": "alexandrebarachant", "repo": "kaggle-seizure-prediction-challenge-2016", "sha": "00f937cc7710977dc812d9fc675864e2b8288658", "save_path": "github-repos/MATLAB/alexandrebarachant-kaggle-seizure-prediction-challenge-2016", "path": "github-repos/MATLAB/alexandrebarachant-kaggle-seizure-prediction-challenge-2016/kaggle-seizure-prediction-challenge-2016-00f937cc7710977dc812d9fc675864e2b8288658/Andriy/code/RMS_amplitude.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465044347828, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6978984989538018}} {"text": "function KLD = prtRvUtilWishartKld(q,Q,p,P)\n% WISHARTKLD Kulback Liebler Divergence between two Wishart densities\n% KLD(Q||P)\n%\n% KL-Divergence of Normal, Gamma, Dirichlet and Wishart densities\n% Penny, 2001\n%\n% Syntax: KLD = wishartKLD(aQ,BQ,aP,BP)\n%\n% Inputs:\n% aQ - The strength parameter of the Q distribution\n% BQ - The mean parameter of the Q distribution\n% aP - The strength parameter of the P distribution\n% BP - The mean parameter of the P distribution\n%\n% Outputs:\n% KLD - The KLD for the Wishart distributions\n\n\n\n\n\nd = size(Q,1);\n\ndims = 1:d;\n\nKLD = p/2*(prtUtilLogDet(Q) - prtUtilLogDet(P)) + q/2*(trace(inv(Q)*P) - d) + prtRvUtilGeneralizedGammaLn(p/2,d) - prtRvUtilGeneralizedGammaLn(q/2,d) + (q/2 - p/2)*sum(psi((q+1-dims)/2));\n\nif KLD < 0\n KLD = 0; % This only happens in the range of 0;\nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/rv/util/prtRvUtilWishartKld.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6978984963632032}} {"text": "%% Autoregressive Conditional Mean, Variance and Kurtosis\n% Allows the estimation of the Autoregressive Conditional Kurtosis Model\n% presented in Brooks, C., Burke, S., P., and Persand, G., (2005), \n% \"Autoregressive Conditional Kurtosis Model\", Journal of Financial \n% Econometrics, 3(3),339-421.\n%\n%% *_Mean Models_* \n%\n% $$ARMAX(AR, MA, X): r_t = a_0 + {\\sum_{i=1}^n}{a_1}{r_{t-i}} + {\\sum_{j=1}^k}{a_2}{\\varepsilon}_{t-j} + {\\sum_{l=1}^m}{a_3}{X_l} + {\\varepsilon}_t$\n%\n%% *_Variance Models_*\n%\n% $$GARCH(P,Q,Y): {\\sigma}_t^2 = b_0 + {\\sum_{i=1}^p}b_{1,i}{\\varepsilon}_{t-i}^2 + {\\sum_{j=1}^q}b_{2,j}{\\sigma}_{t-q}^2 + {\\sum_{l=1}^m}{b_3}{Y_l}$\n% $$GJR-GARCH(P,Q,Y): {\\sigma}_t^2 = b_0 + {\\sum_{i=1}^p}b_{1,i}{\\varepsilon}_{t-i}^2 + {\\sum_{j=1}^q}b_{2,j}{\\sigma}_{t-j}^2 + {\\sum_{i=1}^p}b_{3,i}{\\varepsilon}_{t-i}^2*I_{t-i} + {\\sum_{l=1}^m}{b_3}{Y_l}$\n% $$AGARCH(P,Q,Y): {\\sigma}_t^2 = b_0 + {\\sum_{i=1}^p}b_{1,i}({\\varepsilon}_{t-i} + {\\gamma_{t-p}}))^2 + {\\sum_{j=1}^q}b_{2,j}{\\sigma}_{t-j} + {\\sum_{l=1}^m}{b_3}{Y_l}$\n% $$NAGARCH(P,Q,Y): {\\sigma}_t^2 = b_0 + {\\sum_{i=1}^p}b_{1,i}({\\varepsilon}(t-i)/{\\sqrt{{\\sigma}_{t-i}^2}} + {\\sum_{i=1}^p}{\\gamma_{t-i}}^2 + {\\sum_{j=1}^q}b_{2,j}{\\sigma}_{t-j}^2 + {\\sum_{l=1}^m}{b_3}{Y_l}$\n%\n%% *_Kurtosis Models_*\n% $$GARCH-K(P,Q): k_t = d_0 + {\\sum_{i=1}^p}d_{1,i}{\\varepsilon}_{t-i}^4/{\\sigma}_{t-i}^2 +{\\sum_{j=1}^q}d_{2,j}k_{t-q}$\n%\n%% *_Distribution_*\n%\n% $$f(x) = \\frac{{\\Gamma}\\left(\\frac{{\\nu_t}+1}{2} \\right)}{\\sqrt{{\\nu_t}{\\pi}}{\\Gamma} \\left( \\frac{{\\nu_t}}{2} \\right)}\\left(1+\\frac{\\epsilon_t^2}{\\nu_t} \\right)^{-\\frac{\\nu_t+1}{2}}$\n%\n% where the degrees of freedom can be expressed as a function of conditional kurtosis\n%\n% $$\\nu_t = \\frac{4k_t - 6}{k_t - 3}$\n%\n% <..\\readme\\readme.html Return to Main>", "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/32882-armax-garch-k-toolbox-estimation-forecasting-simulation-and-value-at-risk-applications/readme_armax_garch_k.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.697898495117332}} {"text": "function TwoDimEllipsoid(Location,Square_Dispersion,Scale,PlotEigVectors,PlotSquare)\n% this function computes the location-dispersion ellipsoid \n% see \"Risk and Asset Allocation\"-Springer (2005), by A. Meucci\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% compute the ellipsoid in the r plane, solution to ((R-Location)' * Dispersion^-1 * (R-Location) ) = Scale^2 \n[EigenVectors,EigenValues] = eig(Square_Dispersion);\nEigenValues=diag(EigenValues);\nCentered_Ellipse=[]; \nAngle = [0 : pi/500 : 2*pi];\nNumSteps=length(Angle);\nfor i=1:NumSteps\n y=[cos(Angle(i)) % normalized variables (parametric representation of the ellipsoid)\n sin(Angle(i))];\n Centered_Ellipse=[Centered_Ellipse EigenVectors*diag(sqrt(EigenValues))*y]; \nend\nR= Location*ones(1,NumSteps) + Scale*Centered_Ellipse;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%draw plots\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% plot the ellipsoid\nhold on\nh=plot(R(1,:),R(2,:));\nset(h,'color','r','linewidth',2)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% plot a rectangle centered in Location with semisides of lengths Dispersion(1) and Dispersion(2), respectively\nif PlotSquare\n Dispersion=sqrt(diag(Square_Dispersion));\n Vertex_LowRight_A=Location(1)+Scale*Dispersion(1); Vertex_LowRight_B=Location(2)-Scale*Dispersion(2);\n Vertex_LowLeft_A=Location(1)-Scale*Dispersion(1); Vertex_LowLeft_B=Location(2)-Scale*Dispersion(2);\n Vertex_UpRight_A=Location(1)+Scale*Dispersion(1); Vertex_UpRight_B=Location(2)+Scale*Dispersion(2);\n Vertex_UpLeft_A=Location(1)-Scale*Dispersion(1); Vertex_UpLeft_B=Location(2)+Scale*Dispersion(2);\n \n Square=[Vertex_LowRight_A Vertex_LowRight_B \n Vertex_LowLeft_A Vertex_LowLeft_B \n Vertex_UpLeft_A Vertex_UpLeft_B\n Vertex_UpRight_A Vertex_UpRight_B\n Vertex_LowRight_A Vertex_LowRight_B];\n hold on;\n h=plot(Square(:,1),Square(:,2));\n set(h,'color','r','linewidth',2)\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% plot eigenvectors in the r plane (centered in Location) of length the\n% square root of the eigenvalues (rescaled)\nif PlotEigVectors\n L_1=Scale*sqrt(EigenValues(1));\n L_2=Scale*sqrt(EigenValues(2));\n \n % deal with reflection: matlab chooses the wrong one\n Sign= sign(EigenVectors(1,1));\n Start_A=Location(1); % eigenvector 1\n End_A= Location(1) + Sign*(EigenVectors(1,1)) * L_1;\n Start_B=Location(2);\n End_B= Location(2) + Sign*(EigenVectors(1,2)) * L_1;\n hold on\n h=plot([Start_A End_A],[Start_B End_B]);\n set(h,'color','r','linewidth',2)\n axis equal;\n \n Start_A=Location(1); % eigenvector 2\n End_A= Location(1) + (EigenVectors(2,1)* L_2);\n Start_B=Location(2);\n End_B= Location(2) + (EigenVectors(2,2)* L_2);\n hold on;\n h=plot([Start_A End_A],[Start_B End_B]);\n set(h,'color','r','linewidth',2)\nend\n\ngrid on\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/23554-review-of-discrete-and-continuous-processes-in-finance/Matlab/04VolatilityClustering/Empirical/TwoDimEllipsoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939024825960626, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6978532206298419}} {"text": "function normals = vertexNormal(vertices, faces)\n%VERTEXNORMAL Compute normals to a mesh vertices\n%\n% N = vertexNormal(V, F)\n% Computes vertex normals of the mesh given by vertices V and F. \n% V is a vertex array with 3 columns, F is either a NF-by-3 or NF-by-4\n% index array, or a cell array with NF elements.\n%\n% Example\n% % Draw the vertex normals of a sphere\n% s = [10 20 30 40];\n% [v f] = sphereMesh(s);\n% drawMesh(v, f);\n% view(3);axis equal; light; lighting gouraud;\n% normals = vertexNormal(v, f);\n% drawVector3d(v, normals);\n%\n% See also\n% meshes3d, faceNormal, triangulateFaces\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2011-12-19, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n\nnv = size(vertices, 1);\nnf = size(faces, 1);\n\n% unit normals to the faces\nfaceNormals = normalizeVector3d(faceNormal(vertices, faces));\n\n% compute normal of each vertex: sum of normals to each face\nnormals = zeros(nv, 3);\nif isnumeric(faces)\n for i = 1:nf\n face = faces(i, :);\n for j = 1:length(face)\n v = face(j);\n normals(v, :) = normals(v,:) + faceNormals(i,:);\n end\n end\nelse\n for i = 1:nf\n face = faces{i};\n for j = 1:length(face)\n v = face(j);\n normals(v, :) = normals(v,:) + faceNormals(i,:);\n end\n end\nend\n\n% normalize vertex normals to unit vectors\nnormals = normalizeVector3d(normals);\n\n\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/meshes3d/vertexNormal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.6978219608964012}} {"text": " function [out weight] = ir_patch_avg(patches, idx, dim, varargin)\n%function [out weight] = ir_patch_avg(patches, idx, dim, varargin)\n%|\n%| average 2D overlapping patches to form image\n%| each output pixel value is average of corresponding pixel values\n%| from all patches that contain that pixel, i.e, that overlapping it\n%|\n%| in\n%|\tpatches\t[*patch_size npatch]\n%|\tidx\t[npatch]\t\tfrom ir_im2col\n%|\n%| option\n%|\tpatch_size\t[2]\t\tpatch size (default: [8 8])\n%|\tmeans\t[npatch]\t\tpatch means (if need subtracted)\n%|\t\t\t\t\t\tdefault: empty\n%|\tnchunk\tscalar\t\t\t# of patches to due in block processing\n%|\t\t\t\t\t\tdefault: 10000\n%|\n%| out\n%|\tout\t[dim]\t image formed by averaging overlapping patches\n%|\n%| based on code from Sai Ravishankar\n%| 2016-03-03, Jeff Fessler, University of Michigan\n\nif nargin < 1, ir_usage, end\nif nargin == 1 && streq(patches, 'test'), ir_patch_avg_test, return, end\n\narg.patch_size = [8 8];\narg.means = [];\narg.nchunk = 10000; % how many blocks of patches to do jointly\narg = vararg_pair(arg, varargin);\n\nnpatch = size(patches, 2);\n\nif numel(arg.patch_size) ~= 2 || (prod(arg.patch_size) ~= size(patches,1))\n\tfail 'bad patch_size'\nend\n\nb1 = arg.patch_size(1);\nb2 = arg.patch_size(2);\n\n[rows, cols] = ind2sub(dim - [b1 b2] + 1, idx);\n\nif ~isempty(arg.means)\n\tif numel(arg.means) ~= npatch, fail 'bad arg.means', end\n\tpatches = patches + repmat(arg.means, [b1*b2 1]);\nend\n\nout = zeros(dim);\nweight = zeros(dim);\n\nfor jj = 1:arg.nchunk:npatch\n\tjumpSize = min(jj+arg.nchunk-1, npatch);\n\tzz = patches(:, jj:jumpSize);\n\tfor ii = jj:jumpSize\n\t\tcol = cols(ii); row = rows(ii);\n\t\tblock = reshape(zz(:, ii-jj+1), [b1 b2]);\n\t\ti1 = row:(row+b1-1);\n\t\ti2 = col:(col+b2-1);\n\t\tout(i1, i2) = out(i1, i2) + block; % +=\n\t\tweight(i1, i2) = weight(i1, i2) + 1;\n\tend\nend\n\nif any(weight(:) == 0)\n\tfail 'bug'\nend\nout = out ./ weight; % average\n\n\n% ir_patch_avg_test\nfunction ir_patch_avg_test\n\nnx = 2^8 - 8*7*0; ny = 2^8;\nxtrue = shepplogan(nx, ny, 1);\n%xtrue = rand(nx, ny);\nxtrue(end) = 5; % stress ends\nxtrue(nx) = 4; % stress ends\nbsize = [8 6];\nstride = 3;\nstride = 1;\n[patches idx] = ir_im2col(xtrue, bsize, stride);\nim plc 2 2\nim(1, xtrue)\n[xhat weight] = ir_patch_avg(patches, idx, [nx ny], 'patch_size', bsize);\nim(2, xhat)\nim(3, weight)\nim(4, xhat - xtrue)\nequivs(xhat, xtrue)\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/utilities/ir_patch_avg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.697821960226391}} {"text": "function nd = lagrange_interp_nd_size2 ( m, ind )\n\n%*****************************************************************************80\n%\n%% LAGRANGE_INTERP_ND_SIZE2 sizes an M-dimensional Lagrange interpolant.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 September 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer IND(M), the index or level of the 1D rule \n% to be used in each dimension.\n%\n% Output, integer ND, the number of points in the product grid.\n%\n nd = 1;\n for i = 1 : m\n n = order_from_level_135 ( ind(i) );\n nd = nd * 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_interp_nd/lagrange_interp_nd_size2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.6978219526726339}} {"text": "function minVal=minOverDimIdx(C,selDim,selIdx)\n%%MINOVERDIMIDX Given an S-dimensional matrix C, find the minimum value in\n% the matrix when the index in dimension selDim is fixed to selIdx.\n% For example, if C is 5 dimensional and selDim=4this function\n% evaluates the equivalent of min(vec(C(:,:,:,selIdx,:))). This\n% function can be useful when the dimensionality of the matrix in\n% question can vary.\n%\n%INPUTS: C An S-dimensional hypermatrix.\n% selDim The dimension of the hypermatrix that is selected.\n% selIdx The index in the selected dimension that is fixed.\n%\n%OUTPUTS: minVal The minimum value in the matrix when the specified\n% dimension is fixed to the specified index.\n%\n%For an arbitrary-dimensional matrix, the dimensions before the selected\n%dimension can be collapsed into a single dimension and those after the\n%selected dimension can also be collapsed into a single dimension. Thus,\n%the problem reduces to the minimum of a 3D matrix where the middle index\n%is fixed. In the even that one selects the first or last dimension, then\n%the problem is the minimum of a 2D matrix where the first or last\n%dimension is fixed.\n%\n%EXAMPLE:\n%One will see that both of the value obtained by minOverDimIdx in this\n%example is the same as the direct Matlab expression.\n% C=randn(12,26,36,12,18);\n% selDim=3;\n% selIdx=8;\n% minVal=minOverDimIdx(C,selDim,selIdx)\n% min(vec(C(:,:,selIdx,:,:)))\n%\n%November 2020 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnDims=size(C);\nS=length(nDims);\n\nif(S==1)\n %The special case of an array.\n minVal=C(selIdx);\nelseif(selDim==1)\n startDim=nDims(1);\n endDim=prod(nDims(2:S));\n \n C=reshape(C,[startDim,endDim]);\n minVal=min(C(selIdx,:));\nelseif(selDim==S)\n startDim=prod(nDims(1:(S-1)));\n endDim=nDims(S);\n \n C=reshape(C,[startDim,endDim]);\n minVal=min(C(:,selIdx));\nelse\n startDim=prod(nDims(1:(selDim-1)));\n endDim=prod(nDims((selDim+1):S));\n C=reshape(C,[startDim,nDims(selDim),endDim]);\n minVal=min(vec(C(:,selIdx,:)));\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/Basic_Matrix_Operations/minOverDimIdx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.6978219521366263}} {"text": "function vGlobal=getGlobalVectors(vLocal,uList)\n%%GETGLOBALVECTORS Change a collection of local vectors into global\n% vectors using the local coordinate axes. This multiplies\n% the components of the vectors by the corresponding\n% coordinate axis vectors.\n%\n%INPUTS: vLocal A numDimsXN matrix of N local vectors that are to be\n% converted. \n% uList A numDimsXnumDimsXN matrix of orthonormal unit coordinate\n% axes that are associated with the local coordinate system\n% in which the vectors are expressed. If all N vectors use\n% the same local coordinate system, then a numDimsxnumDimsx1\n% matrix can be passed instead.\n%\n%OUTPUTS: vGlobal The vectors in the global coordinate system.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n numVel=size(vLocal,2);\n \n if(size(uList,3)==1)\n uList=repmat(uList,[1,1,numVel]);\n end\n \n numDims=size(vLocal,1);\n vGlobal=zeros(numDims,numVel);\n for curVel=1:numVel\n for curDim=1:numDims\n vGlobal(:,curVel)=vGlobal(:,curVel)+vLocal(curDim,curVel)*uList(:,curDim,curVel);\n end\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/Coordinate_Systems/getGlobalVectors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.6978219374678466}} {"text": "function quadrule_test40 ( )\n\n%*****************************************************************************80\n%\n%% QUADRULE_TEST40 tests NCO_COMPUTE and SUM_SUB.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 14 October 2005\n%\n% Author:\n%\n% John Burkardt\n%\n order_max = 9;\n\n nfunc = func_set ( 'COUNT', 'DUMMY' );\n\n a = 0.0;\n b = 1.0;\n\n nsub = 1;\n xlo = -1.0;\n xhi = +1.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'QUADRULE_TEST40\\n' );\n fprintf ( 1, ' NCO_COMPUTE sets up an open Newton-Cotes rule;\\n' );\n fprintf ( 1, ' SUM_SUB carries it out.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Integration interval is [%f, %f]\\n', a, b );\n fprintf ( 1, ' Number of subintervals is %d\\n', nsub );\n fprintf ( 1, ' Quadrature order will vary.\\n' );\n fprintf ( 1, ' Integrand will vary.\\n' );\n fprintf ( 1, '\\n' );\n\n for ilo = 1 : 5 : nfunc\n\n ihi = min ( ilo + 4, nfunc );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ' );\n for i = ilo : ihi\n fprintf ( '%14s', fname(i) );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, '\\n' );\n\n for n = 1 : order_max\n\n if ( n == 8 )\n continue\n end\n\n fprintf ( 1, ' %2d', n );\n\n for i = ilo : ihi\n\n func_set ( 'SET', i );\n\n [ x, w ] = nco_compute ( n );\n\n result(i) = sum_sub ( @func, a, b, nsub, n, xlo, xhi, x, w );\n\n fprintf ( 1, ' %12f', result(i) );\n\n end\n\n fprintf ( 1, '\\n' );\n\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/quadrule/quadrule_test40.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346598, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6978189050223711}} {"text": "classdef MPDMP < PROBLEM\n% \n% The multi-point distance minimization problem\n% lower --- -100 --- Lower bound of decision variables\n% upper --- 100 --- Upper bound of decision variables\n\n%------------------------------- Reference --------------------------------\n% M. Koppen and K. Yoshida, Substitute distance assignments in NSGA-II for\n% handling many-objective optimization problems, Proceedings of the\n% International Conference on Evolutionary Multi-Criterion Optimization,\n% 2007, 727-741.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n properties(Access = private)\n Points; % Vertexes\n end\n methods\n %% Default settings of the problem\n function Setting(obj)\n % Parameter setting\n [lower,upper] = obj.ParameterSet(-100,100);\n if isempty(obj.M); obj.M = 10; end\n obj.M = max(obj.M,3);\n obj.D = 2;\n obj.lower = zeros(1,2) + lower;\n obj.upper = zeros(1,2) + upper;\n obj.encoding = ones(1,obj.D);\n % Generate vertexes\n if mod(obj.M,2) == 0\n Angle = (2.*(1:obj.M)-3).*pi./obj.M;\n else\n Angle = (2.*(1:obj.M)-2).*pi./obj.M;\n end\n obj.Points = [sin(Angle)',cos(Angle)'];\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,PopDec)\n PopObj = pdist2(PopDec,obj.Points);\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n [X,Y] = ndgrid(linspace(-1,1,ceil(sqrt(N))));\n ND = inpolygon(X(:),Y(:),obj.Points(:,1),obj.Points(:,2));\n R = pdist2([X(ND),Y(ND)],obj.Points);\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n if obj.M == 3\n [X,Y] = ndgrid(linspace(-1,1,40));\n R = pdist2([X(:),Y(:)],obj.Points);\n ND = inpolygon(X(:),Y(:),obj.Points(:,1),obj.Points(:,2));\n R(~ND,:) = nan;\n R = {reshape(R(:,1),size(X)),reshape(R(:,2),size(X)),reshape(R(:,3),size(X))};\n else\n R = [];\n end\n end\n %% Display a population in the decision space\n function DrawDec(obj,Population)\n Draw(obj.Points([1:end,1],:),'-k','LineWidth',1.5,{'\\it x\\rm_1','\\it x\\rm_2',[]});\n Draw(obj.Points,'o','MarkerSize',6,'Marker','o','Markerfacecolor',[1 1 1],'Markeredgecolor',[.4 .4 .4]);\n Draw(Population.decs);\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/Real-world MOPs/MPDMP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.697818902294411}} {"text": "function g = estimate_time_constant(y, p, sn, lags, fudge_factor)\n%% Estimate noise standard deviation and AR coefficients if they are not present\n\n%% inputs:\n% y: N X T matrix, fluorescence trace\n% p: positive integer, order of AR system\n% sn: scalar, noise standard deviation, estimated if not provided\n% lags: positive integer, number of additional lags where he autocovariance is computed\n% fudge_factor: float (0< fudge_factor <= 1) shrinkage factor to reduce bias\n\n%% outputs\n% g: 1 x p vector, AR coefficient\n\n%% Authors: Pengcheng Zhou, Carnegie Mellon University, 2016\n% adapted from the MATLAB implemention by Eftychios Pnevmatikakis and the\n% Python implementation from Johannes Friedrich\n\n%% References\n% Pnevmatikakis E. et.al., Neuron 2016, Simultaneous Denoising, Deconvolution, and Demixing of Calcium Imaging Data\n\n%% input arguments\nif ~exist('p', 'var') || isempty(p)\n p = 2;\nend\nif ~exist('sn', 'var') || isempty(sn)\n sn = GetSn(y);\nend\nif ~exist('lags', 'var') || isempty(lags)\n lags = 5;\nend\nif ~exist('fudge_factor', 'var') || isempty(fudge_factor)\n fudge_factor = 1;\nend\n\n%% estimate time constants \nlags = lags + p;\nif ~isempty(which('xcov')) %signal processing toolbox\n xc = xcov(y,lags,'biased');\nelse\n ynormed = (y - mean(y));\n xc = nan(lags + 1, 1);\n for k = 0:lags\n xc(k + 1) = ynormed(1 + k:end)' * ynormed(1:end - k);\n end\n xc = [flipud(xc(2:end)); xc] / numel(y);\nend\nxc = xc(:);\nA = toeplitz(xc(lags+(1:lags)),xc(lags+(1:p))) - sn^2*eye(lags,p);\ng = pinv(A)*xc(lags+2:end);\n\n% while max(abs(roots([1,-g(:)']))>1) && p < 3\n% warning('No stable AR(%i) model found. Checking for AR(%i) model \\n',p,p+1);\n% p = p + 1;\n% g = estimate_time_constants(y,p,sn,lags);\n% end\n% if p == 5\n% g = 0;\n% end\n\n% re-adjust time constant values\nrg = roots([1;-g(:)]);\nif ~isreal(rg); rg = real(rg) + .001*randn(size(rg)); end\nrg(rg>1) = 0.95 + 0.001*randn(size(rg(rg>1)));\nrg(rg<0) = 0.15 + 0.001*randn(size(rg(rg<0)));\npg = poly(fudge_factor*rg);\ng = -pg(2:end);\n\n", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/deconvolution/functions/estimate_time_constant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6978189016103504}} {"text": "function [yi, xi] = downsample_scnlab(y, orig_samprate, new_samprate, varargin)\n% Uses linear interpolation to resample a vector from one sampling\n% rate to another\n%\n% :Usage:\n% ::\n%\n% [yi, xi] = downsample_scnlab(y, orig_samprate, new_samprate, [doplot])\n%\n% :Inputs:\n%\n% **orig_samprate:**\n% sampling rate in Hz\n%\n% **new_samprate:**\n% desired sampling rate in Hz\n%\n% ..\n% I prefer this to matlab's downsample.m because linear interpolation is\n% robust and does fewer weird things to the data.\n%\n% Tor Wager, June 2009\n% ..\n%\n% :Example:\n% ::\n%\n% % Downsample a 100 Hz signal to a scanning TR of 2 sec\n% % signal at 100 Hz, sample to low-freq TR of 0.5 hz (2 sec TR)\n% % every 100 / TR = 100/.5 = 200 samples\n%\n% [yi, xi] = downsample_scnlab(y, 100, .5)\n%\n\ndoplot = 0;\nif length(varargin) > 0, doplot = varargin{1}; end\n\ndownsamplerate = orig_samprate ./ new_samprate;\n\nnobs = length(y);\n\n\n% observations in resampled output\nnobs_out = round(nobs ./ downsamplerate);\n\n\nx = 1:nobs;\n\nxi = linspace(0, nobs, nobs_out);\n\n\nyi = interp1(x, y, xi, 'linear', 'extrap');\n\nif doplot\n\n create_figure('Downsample plot');\n plot(y)\n hold on; plot(xi, yi, 'r')\n\nend\n\nend\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Data_processing_tools/downsample_scnlab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6978188982010904}} {"text": "function [ph_out,ph_out_low]=wrap_filt(ph,n_win,alpha,n_pad,low_flag)\n%WRAP_FILT Goldstein adaptive and lowpass filtering\n% [ph_out]=wrap_filt(ph,n_win,alpha,n_pad)\n%\n% Andy Hooper, June 2006\n% \n% Change Log:\n% 07/2006 AH: Added zero padding \n% 02/2012 AH: Set magnitude to original values\n\nif nargin<4 | isempty(n_pad)\n n_pad=round(n_win*0.25);\nend\n\nif nargin<5\n low_flag='n';\nend\n \n[n_i,n_j]=size(ph);\nn_inc=floor(n_win/2);\nn_win_i=ceil(n_i/n_inc)-1;\nn_win_j=ceil(n_j/n_inc)-1;\n\nph_out=zeros(size(ph));\nif strcmpi(low_flag,'y')\n ph_out_low=ph_out;\nelse\n ph_out_low=[];\nend\nx=[1:n_win/2];\n[X,Y]=meshgrid(x,x);\nX=X+Y;\nwind_func=[X,fliplr(X)];\nwind_func=[wind_func;flipud(wind_func)];\n\n\nph(isnan(ph))=0;\nB=gausswin(7)*gausswin(7)';\nph_bit=zeros(n_win+n_pad);\n\nL=ifftshift(gausswin(n_win+n_pad,16)*gausswin(n_win+n_pad,16)');\n\nfor ix1=1:n_win_i\n wf=wind_func;\n i1=(ix1-1)*n_inc+1;\n i2=i1+n_win-1;\n if i2>n_i\n i_shift=i2-n_i;\n i2=n_i;\n i1=n_i-n_win+1;\n wf=[zeros(i_shift,n_win);wf(1:n_win-i_shift,:)];\n end\n for ix2=1:n_win_j\n wf2=wf;\n j1=(ix2-1)*n_inc+1;\n j2=j1+n_win-1;\n if j2>n_j\n j_shift=j2-n_j;\n j2=n_j;\n j1=n_j-n_win+1;\n wf2=[zeros(n_win,j_shift),wf2(:,1:n_win-j_shift)];\n end\n ph_bit(1:n_win,1:n_win)=ph(i1:i2,j1:j2);\n ph_fft=fft2(ph_bit);\n H=abs(ph_fft);\n H=ifftshift(filter2(B,fftshift(H))); % smooth response\n meanH=median(H(:));\n if meanH~=0\n H=H/meanH;\n end\n H=H.^alpha;\n ph_filt=ifft2(ph_fft.*H);\n ph_filt=ph_filt(1:n_win,1:n_win).*wf2;\n if strcmpi(low_flag,'y')\n ph_filt_low=ifft2(ph_fft.*L);\n ph_filt_low=ph_filt_low(1:n_win,1:n_win).*wf2;\n end\n if isnan(ph_filt(1,1))\n disp('filtered phase contains NaNs in goldstein_filt')\n keyboard\n end\n ph_out(i1:i2,j1:j2)=ph_out(i1:i2,j1:j2)+ph_filt;\n if strcmpi(low_flag,'y')\n ph_out_low(i1:i2,j1:j2)=ph_out_low(i1:i2,j1:j2)+ph_filt_low;\n end\n end\nend\n\nph_out=abs(ph).*exp(j*angle(ph_out)); % reset magnitude\nif strcmpi(low_flag,'y')\n ph_out_low=abs(ph).*exp(j*angle(ph_out_low)); % reset magnitude\nend\n\n\n", "meta": {"author": "dbekaert", "repo": "StaMPS", "sha": "c159eb81b16c446e0e8fdef7dd435eb22e0240ed", "save_path": "github-repos/MATLAB/dbekaert-StaMPS", "path": "github-repos/MATLAB/dbekaert-StaMPS/StaMPS-c159eb81b16c446e0e8fdef7dd435eb22e0240ed/matlab/wrap_filt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.6978166664111856}} {"text": "function [membership,means,rms] = kmeansML(k,data,varargin)\n% [membership,means,rms] = kmeansML(k,data,...)\n%\n% Multi-level kmeans. \n% Tries very hard to always return k clusters.\n%\n% INPUT\n%\tk\t\tNumber of clusters\n% \tdata\t\tdxn matrix of data points\n%\t'maxiter'\tMax number of iterations. [30]\n%\t'dtol'\t\tMin change in center locations. [0]\n%\t'etol'\t\tMin percent change in RMS error. [0]\n%\t'ml'\t\tMulti-level? [true]\n%\t'verbose'\tVerbose level. [0]\n%\t\t\t 0 = none\n%\t\t\t 1 = textual\n%\t\t\t 2 = visual\n%\n% OUTPUT\n% \tmembership\t1xn cluster membership vector\n% \tmeans\t\tdxk matrix of cluster centroids\n%\trms\t\tRMS error of model\n%\n% October 2002\n% David R. Martin \n\n% process options\nmaxIter = 30;\ndtol = 0;\netol = 0;\nml = true;\nverbose = 0;\nfor i = 1:2:numel(varargin),\n opt = varargin{i};\n if ~ischar(opt), error('option names not a string'); end\n if i==numel(varargin), error(sprintf('option ''%s'' has no value',opt)); end\n val = varargin{i+1};\n switch opt,\n case 'maxiter', maxIter = max(1,val);\n case 'dtol', dtol = max(0,val);\n case 'etol', etol = max(0,val);\n case 'ml', ml = val;\n case 'verbose', verbose = val;\n otherwise, error(sprintf('invalid option ''%s''',opt));\n end\nend\n\n[membership,means,rms] = ...\n kmeansInternal(k,data,maxIter,dtol,etol,ml,verbose,1);\n\nfunction [membership,means,rms] = kmeansInternal(...\n k,data,maxIter,dtol,etol,ml,verbose,retry)\n\n[d,n] = size(data);\nperm = randperm(n);\n\n% compute initial means\nrate = 3;\nminN = 50;\ncoarseN = round(n/rate);\nif ~ml | coarseN < k | coarseN < minN,\n % pick random points as means\n means = data(:,perm(1:k));\nelse\n % recurse on random subsample to get means\n coarseData = data(:,perm(1:coarseN));\n [coarseMem,means] = ...\n kmeansInternal(k,coarseData,maxIter,dtol,etol,ml,verbose,0);\nend\n\n% Iterate.\niter = 0;\nrms = inf;\nif verbose>0, fwrite(2,sprintf('kmeansML: n=%d d=%d k=%d [',n,d,k)); end\nwhile iter < maxIter,\n if verbose>0, fwrite(2,'.'); end\n iter = iter + 1;\n % Compute cluster membership and RMS error.\n rmsPrev = rms;\n [membership,rms] = computeMembership(data,means);\n % Compute new means and cluster counts.\n prevMeans = means;\n [means,counts] = computeMeans(k,data,membership);\n % The error should always decrease.\n if rms > rmsPrev, error('bug: rms > rmsPrev'); end\n % Check for convergence.\n rmsPctChange = 2 * (rmsPrev - rms) / (rmsPrev + rms + eps);\n maxMoved = sqrt(max(sum((prevMeans-means).^2)));\n if rmsPctChange <= etol & maxMoved <= dtol, break; end\n % Visualize.\n if verbose>1, kmeansVis(data,membership,means); end\nend\n[membership,rms] = computeMembership(data,means);\nif verbose>0, fwrite(2,sprintf('] rms=%.3g\\n',rms)); end\n\n% If there's an empty cluster, then re-run kmeans.\n% Retry a fixed number of times.\nmaxRetries = 3;\nif find(counts==0), \n if retry < maxRetries,\n disp('Warning: Re-runing kmeans due to empty cluster.');\n [membership,means] = kmeansInternal( ...\n k,data,maxIter,dtol,etol,ml,verbose,retry+1);\n else\n disp('Warning: There is an empty cluster.');\n end\nend\n\nfunction [membership,rms] = computeMembership(data,means)\nz = distSqr(data,means);\n[d2,membership] = min(z,[],2);\nrms = sqrt(mean(d2));\n\nfunction [means,counts] = computeMeans(k,data,membership)\n[d,n] = size(data);\nmeans = zeros(d,k);\ncounts = zeros(1,k);\nfor i = 1:k,\n ind = find(membership==i);\n counts(i) = length(ind);\n means(:,i) = sum(data(:,ind),2) / max(1,counts(i));\nend\n \n% for i = 1:n,\n% j = membership(i);\n% means(:,j) = means(:,j) + data(:,i);\n% counts(j) = counts(j) + 1;\n% end\n% for j = 1:k,\n% means(:,j) = means(:,j) / max(1,counts(j));\n% end\n\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/external/segbench/lib/matlab/kmeansML.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6978166640327138}} {"text": "function L = evaluate_log_posterior(this, uv)\n%EVALUATE_LOG_POSTERIOR computes the log-posterior (negative energy) of the\n% flow fields UV \n% Actually only proportional to the log posterior since the variance of neither the\n% spatial nor the data terms is considered\n%\n% This is a member function of the class 'alt_ba_optical_flow'. \n%\n% Authors: Deqing Sun, Department of Computer Science, Brown University\n% Contact: dqsun@cs.brown.edu\n% $Date: 2009 $\n% $Revision: $\n%\n% Copyright 2009-2010, Brown University, Providence, RI. USA\n% \n% All Rights Reserved\n% \n% All commercial use of this software, whether direct or indirect, is\n% strictly prohibited including, without limitation, incorporation into in\n% a commercial product, use in a commercial service, or production of other\n% artifacts for commercial purposes. \n%\n% Permission to use, copy, modify, and distribute this software and its\n% documentation for research purposes is hereby granted without fee,\n% provided that the above copyright notice appears in all copies and that\n% both that copyright notice and this permission notice appear in\n% supporting documentation, and that the name of the author and Brown\n% University not be used in advertising or publicity pertaining to\n% distribution of the software without specific, written prior permission. \n%\n% For commercial uses contact the Technology Venture Office of Brown University\n% \n% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO\n% THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n% FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR OR\n% BROWN UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n% DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\n% PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\n% ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n% THIS SOFTWARE. \n\n% spatial term\nS = this.spatial_filters;\np = 0;\n\nfor i = 1:length(S)\n\n u_ = conv2(uv(:,:,1), S{i}, 'valid');\n v_ = conv2(uv(:,:,2), S{i}, 'valid');\n\n if isa(this.rho_spatial_u{i}, 'robust_function')\n \n p = p - sum(evaluate(this.rho_spatial_u{i}, u_(:)))...\n - sum(evaluate(this.rho_spatial_v{i}, v_(:)));\n \n elseif isa(this.rho_spatial_u{i}, 'gsm_density')\n \n p = p + sum(evaluate_log(this.rho_spatial_u{i}, u_(:)'))...\n + sum(evaluate_log(this.rho_spatial_v{i}, v_(:)'));\n \n else\n error('evaluate_log_posterior: unknown rho function!');\n end;\nend;\n\n% likelihood\nIt = partial_deriv(this.images, uv, this.interpolation_method); \n \nif isa(this.rho_data, 'robust_function')\n\n l = -sum(evaluate(this.rho_data, It(:)));\n \nelseif isa(this.rho_data, 'gsm_density')\n \n l = sum(evaluate_log(this.rho_data, It(:)'));\n \nelse\n error('evaluate_log_posterior: unknown rho function!');\nend;\n\nL = this.lambda*p + l;\n\nif this.display\n fprintf('spatial\\t%3.2e\\tdata\\t%3.2e\\n', this.lambda*p, l);\nend;\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/spaceTime/optflow_deqing/@alt_ba_optical_flow/evaluate_log_posterior.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.787931185683219, "lm_q1q2_score": 0.6978166548654696}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Spherical Harmonic Modeling and Analysis Toolkit (SPHARM-MAT) is a 3D \n% shape modeling and analysis toolkit. \n% It is a software package developed at Shenlab in Center for Neuroimaging, \n% Indiana University (SpharmMat@gmail.com, http://www.iupui.edu/~shenlab/)\n% It is available to the scientific community as copyright freeware \n% under the terms of the GNU General Public Licence.\n% \n% Copyright 2009, 2010, ShenLab, Center for Neuroimaging, Indiana University\n% \n% This file is part of SPHARM-MAT.\n% \n% SPHARM-MAT 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% SPHARM-MAT 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 SPHARM-MAT. If not, see .\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% ============================================\n%\n% Goal: Create canonical spherical harmonic bases\n%\n% Li Shen \n% 04/11/2002 - create\n% 10/15/2002 - rename and modify\n% 11/03/2008 - renamed by Sungeun Kim.\n\nfunction Z = calculate_SPHARM_basis(vs, degree)\n\n[PHI,THETA] = cart2sph(vs(:,1),vs(:,2),vs(:,3));\nind = find(PHI<0);\nPHI(ind) = PHI(ind)+2*pi;\nTHETA = pi/2-THETA;\nvertnum = size(THETA,1);\n\nZ = spharm_basis(degree,THETA,PHI); \n\nreturn;\n\n\nfunction Z = spharm_basis(max_degree,theta,phi)\n\nZ = []; vnum = size(theta,1);\n\n% save calculations for efficiency\nfor k = 0:(2*max_degree)\n fact(k+1) = factorial(k);\nend\nfor m = 0:max_degree\n exp_i_m_phi(:,m+1) = exp(i*m*phi);\n sign_m(m+1) = (-1)^(m);\nend\n\nfor n = 0:max_degree\n\n\t% P = legendre(n,X) computes the associated Legendre functions of degree n and \n\t% order m = 0,1,...,n, evaluated at X. Argument n must be a scalar integer \n\t% less than 256, and X must contain real values in the domain -1<=x<=1.\n\t% The returned array P has one more dimension than X, and each element\n\t% P(m+1,d1,d2...) contains the associated Legendre function of degree n and order\n\t% m evaluated at X(d1,d2...).\n\n Pn = legendre(n,cos(theta'))';\n \n posi_Y = [];\n nega_Y = [];\n \n m= 0:n;\n v = sqrt(((2*n+1)/(4*pi))*(fact(n-m+1)./fact(n+m+1)));\n v = v(ones(1,vnum),:).*Pn(:,m+1).*exp_i_m_phi(:,m+1);\n posi_Y(:,m+1) = v; % positive order;\n nega_Y(:,n-m+1) = sign_m(ones(1,vnum),m+1).*conj(v); % negative order\n \n Z(:,end+1:end+n) = nega_Y(:,1:n);\n Z(:,end+1:end+n+1) = posi_Y(:,1:(n+1));\nend\n\nreturn;\n\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/SpharmToolbox/code/calculate_SPHARM_basis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6977958992483321}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% [alpha, beta, gamma] = rot2euler(R, convention)\n% Returns the Euler angles alpha, beta and gamma that yield a given matrix\n% R. The convention specifies the order and axes of rotations.\n% Currently, only the XYZ convention is supported. \n%\n% In particular, the function computes the angles alpha, beta and gamma that\n% allow to compute R as.\n%\n% R = Rot(alpha,'x')*Rot(beta,'y')*Rot(gamma,'z')\n%\n% Author: Arturo Gil. Universidad Miguel Hernandez de Elche. email:\n% arturo.gil@umh.es date: 11/11/2020\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser 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% ARTE 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 Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction [sol1, sol2] = rot2euler(R, convention)\n\n\nif convention=='XYZ'\n [sol1, sol2]=conventionXYZ(R);\nelseif convention=='ZYX'\n [sol1, sol2]=conventionZYX(R); \nelse\n 'Unknown convention. Only XYZ and ZYX are supported'\nend\n\n\n\nfunction [sol1, sol2] = conventionXYZ(R)\n%'R(1,3)=sen(beta)=1??'\nif abs(R(1,3)) == 1\n % degenerate case in which sen(beta)=+-1 and cos(beta)=0\n alpha1 = 0; % arbitrarily set alpha to zero\n alpha2 = pi; % arbitrarily set alpha to pi\n beta1 = asin(R(1,3));\n beta2 = pi-beta1;\n if sin(beta1) > 0\n gamma1 = atan2(R(2,1), -R(3,1)); \n gamma2 = atan2(R(2,1), -R(3,1)) - alpha2; \n else\n gamma1 = atan2(R(2,1), R(3,1));\n gamma2 = atan2(R(2,1), R(3,1))+alpha2; \n end\nelse\n beta1 = asin(R(1,3));\n beta2 = pi-beta1;\n \n % standard way to compute alpha beta and gamma\n alpha1 = -atan2(R(2,3)/cos(beta1), R(3,3)/cos(beta1));\n alpha2 = -atan2(R(2,3)/cos(beta2), R(3,3)/cos(beta2));\n gamma1 = -atan2(R(1,2)/cos(beta1), R(1,1)/cos(beta1));\n gamma2 = -atan2(R(1,2)/cos(beta2), R(1,1)/cos(beta2));\nend\n% Normalize all angles to -pi, pi \nsol1 = [alpha1, beta1, gamma1];\nsol2 = [alpha2, beta2, gamma2];\nsol1 = normalize_angles(sol1);\nsol2 = normalize_angles(sol2);\n\n\nfunction [sol1, sol2] = conventionZYX(R)\n%R(3,1)=sin(beta)=+-1?? --> degenerate case\n% degenerate case in which sen(beta)=+-1 and cos(beta)=0\nif abs(R(3,1)) == 1 \n alpha1 = 0; % arbitrarily set alpha to zero\n alpha2 = pi;%arbitrarily set to pi \n beta1 = asin(-R(3,1));\n beta2 = pi-beta1; \n if sin(beta1) > 0\n gamma1 = atan2(R(1,2), R(2,2)); \n gamma2 = atan2(R(1,2), R(2,2)) + alpha2;\n else\n gamma1 = atan2(-R(1,2), R(2,2)); \n gamma2 = atan2(-R(1,2), R(2,2)) - alpha2;\n end\nelse\n % standard way to compute alpha beta and gamma outside of the gimbal\n % lock\n beta1 = asin(-R(3,1));\n beta2 = pi-beta1;\n \n alpha1 = atan2(R(2,1)/cos(beta1), R(1,1)/cos(beta1));\n alpha2 = atan2(R(2,1)/cos(beta2), R(1,1)/cos(beta2));\n gamma1 = atan2(R(3,2)/cos(beta1), R(3,3)/cos(beta1));\n gamma2 = atan2(R(3,2)/cos(beta2), R(3,3)/cos(beta2));\nend\n% Normalize all angles to -pi, pi \nsol1 = [alpha1, beta1, gamma1];\nsol2 = [alpha2, beta2, gamma2];\nsol1 = normalize_angles(sol1);\nsol2 = normalize_angles(sol2);\n\nfunction sol_norm = normalize_angles(sol)\nsol_norm = [0 0 0];\nfor i=1:3\n sol_norm(i) = atan2(sin(sol(i)), cos(sol(i)));\nend\n \n\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/lib/rot2euler.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6977958973540631}} {"text": "function [p, f, t] = spm_mmtspec (x,Fs, freqs,timeres, timestep, NW)\n% Moving multitaper based spectrogram\n% FORMAT [p, f, t] = spm_mmtspec (x,Fs,freqs,timeres)\n%\n% x input time series\n% Fs sampling frequency of input time series\n% freqs desired vector of frequencies for spectrogram eg. [6:1:30]\n% timeres desired time resolution for spectrogram, default T/16\n% where T is duration of x\n%\n% p p(f, t) is estimate of power at freq f and time t\n% \n% Time series is split into a series of overlapping windows with 5% overlap. \n% Desired frequency resolution is attained by zero padding \n% as/if necessary. The taper approach is applied to each padded sample.\n% \n% Plot spectrogram using imagesc(t,f,p); axis xy\n%___________________________________________________________________________\n% Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging\n\n% Partha Mitra, Ken Harris and Will Penny\n% $Id: spm_mmtspec.m 4021 2010-07-28 12:43:16Z vladimir $\n\nnChannels = size(x, 2);\nnSamples = size(x,1);\n\nif (nargin<4 || isempty(timeres)) \n timeres = nSamples/(16*Fs);\nend\n\nif (nargin<5 || isempty(timestep))\n percent_overlap=0.05;\nelse\n percent_overlap= 1-timestep/timeres;\nend\n\nif (nargin<6 || isempty(NW))\n NW=3;\nend\n\nif length(unique(diff(freqs))) > 1\n error('Varying frequency resolution is not supported.');\nend\n\ndf=freqs(2)-freqs(1);\nnFFT=round(Fs/df);\n\nWinLength=round(Fs*timeres);\nnOverlap=ceil(percent_overlap*WinLength); \n\nnTapers = 2*NW -1; \n\n% Now do some computations that are common to all spectrogram functions\n\nwinstep = WinLength - nOverlap;\n\n\n% check for column vector input\nif nSamples == 1 \n x = x';\n nSamples = size(x,1);\n nChannels = 1;\nend;\n\nif nSamples < WinLength\n disp('Error in spm_mmtspec: win length must be less than number of samples');\n return;\nend\n\n% calculate number of FFTChunks per channel\nnFFTChunks = round(((nSamples-WinLength)/winstep));\n% turn this into time, using the sample frequency\nt = winstep*(0:(nFFTChunks-1))'/Fs;\n\n% set up f and t arrays\nif ~any(any(imag(x))) % x purely real\n if rem(nFFT,2), % nfft odd\n select = [1:(nFFT+1)/2];\n else\n select = [1:nFFT/2+1];\n end\n nFreqBins = length(select);\nelse\n select = 1:nFFT;\nend\nf = (select - 1)'*Fs/nFFT;\n\n\n% allocate memory now to avoid nasty surprises later\ny=complex(zeros(nFreqBins, nFFTChunks, nChannels, nChannels)); % output array\nPeriodogram = complex(zeros(nFreqBins, nTapers, nChannels, nFFTChunks)); % intermediate FFTs\nTemp1 = complex(zeros(nFFT, nTapers, nFFTChunks));\nTemp2 = complex(zeros(nFFT, nTapers, nFFTChunks));\nTemp3 = complex(zeros(nFFT, nTapers, nFFTChunks));\neJ = complex(zeros(nFFT, nFFTChunks));\n\n% calculate Slepian sequences. \n%Tapers=spm_dpss(WinLength,NW);\nTapers=spm_dpss(max(nFFT,WinLength),NW);\nTapers=Tapers(:,1:nTapers);\n\n% Vectorized alogrithm for computing tapered periodogram with FFT \nTaperingArray = repmat(Tapers, [1 1 nChannels]);\nfor j=1:nFFTChunks\n Segment = x((j-1)*winstep+[1:WinLength], :);\n \n if WinLength=(freqs(1)-0.1) & f <=(freqs(end)+0.1));\nf=f(ind);\np= p(ind,:, :);\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/spectral/spm_mmtspec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6977958973208025}} {"text": "function [mean_err_rate, err_rates] = classif_mean_err_rate(labels,test_set,truth)\n\n% Usage\n% [mean_err_rate,err_rates] = classif_mean_err(labels,test_set,truth)\n%\n% Input\n% labels (int): The labels attributed to the testing instances.\n% test_set (int): The object indices of the testing instances.\n% truth: the actual labels of the testing instances\n%\n% Output\n% mean_err_rate (real): The mean error rate\n% recog_rate(real): array containing the individual error rates of\n% each class.\n%\n% Description\n% This function computes the mean of the error rates of all the classes\n% which are present in the dataset. We have mean_err_rate = 1 - mean_recog_rate\n% where mean_recog_rate is the mean of all the recognition rate of all the \n% classes which are present in the dataset and \n% is a widely used measure of the performance of the classifier when the\n% data set is highly unbalanced.\n%\n% See also\n% SVM_TEST, CLASSIF_ERR, CLASSIF_RECOG\n \nif isstruct(truth)\n src = truth;\n truth = [src.objects.class];\nend\n\n% Normally, the test_set contains samples of all classes\nrecog_rates = zeros(1,max(truth));\ngdTruth = truth(:,test_set);\n\n\nparfor k = 1:max(truth)\n \n mask = k == gdTruth;\n good_elts = find(labels==k & mask);\n \n mask1 = numel(find(mask==1));\n recog_rates(k)=numel(good_elts)/mask1;\n \nend\n\nerr_rates = 1 - recog_rates;\nmean_err_rate = 1 - mean(recog_rates);\n \nend", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/classification/classif_mean_err_rate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7690802264851918, "lm_q1q2_score": 0.6977958886968112}} {"text": "function [out_img, criterion] = TVdenoising(img, method, num_steps, lambda, clear_img, alpha, showfigs)\n\n[H, W] = size(img);\nN = H * W;\n\n%% method aspects\nswitch method\n case 'ROFalg1'\n alg = 1;\n Lone = 0;\n huber = 0;\n case 'ROFalg2'\n alg = 2;\n Lone = 0;\n huber = 0;\n case 'TVL1ROFalg1'\n alg = 1;\n Lone = 1;\n huber = 0;\n case 'HuberROFalg3'\n alg = 3;\n Lone = 0;\n huber = 1;\n case 'HuberL1ROFalg1'\n alg = 1;\n Lone = 1;\n huber = 1;\n otherwise\n disp(['Unknown method: ' method]);\n return;\nend\n\n\n%% parameters\nL = sqrt(8);\n\nswitch alg\n case 0 % Arrow-Hurwics version of Alg 2 (AHMOD)\n tau = 1/L;\n sigma = 1/L;\n gamma = 0.35 * lambda;\n theta = 0;\n case 1\n tau = 0.01;\n sigma = 1/(tau * L * L);\n theta = 1;\n case 2\n tau = 1/L;\n sigma = 1/L;\n gamma = 0.35*lambda;\n case 3\n gamma = lambda;\n delta = alpha;\n mu = 2 * sqrt(gamma * delta) / L;\n theta = 1/(1+mu);\n tau = mu / (2 * gamma);\n sigma = mu / (2 * delta);\nend\n\n\n%% initial solution\n% primal task variables\nu = img(:);\nubar = u;\n\n% dual task variable\np = zeros(N * 2, 1);\n\n%% precomputed\nnabla = make_derivatives_mine(H, W);\ndivop = nabla';\n% divop = make_divop(H, W);\ndenom = 1 + tau * lambda;\n\n%% initial criterion value\nif (Lone)\n lambda_denom = 1;\nelse\n lambda_denom = 2;\nend\n\ncriterion = zeros(1, num_steps+1);\ncriterion(1) = Fval(u, img, alpha, huber) + lambda / lambda_denom * Gval(u, img, Lone);\n\n\n%% plot the initial state\nif showfigs\n fh1 = sfigure;\n \n imshow([img reshape(u, H, W)]);\n \n fh2 = sfigure;\n plot(0, criterion(1), 'b-');\n xlabel('step');\n ylabel('J(u)');\nend\n\n%% main loop\nfor step = 1:num_steps\n disp(['step: ' num2str(step)]);\n \n % ------ update p^n+1 ------\n p = p + sigma * nabla * ubar;\n \n if huber\n p = p / (1 + sigma * alpha);\n end\n \n % projection of p onto L2 ball\n p_len = sqrt(p(1:N).^2 + p(N+1:end).^2);\n p_len = max(1, p_len);\n p = p ./ repmat(p_len, 2, 1);\n \n % ----- update u^n+1 ------\n divp = divop * p;\n u_tilde = u - tau * divp;\n\n if Lone\n dif = u_tilde - img(:);\n idx1 = dif > tau * lambda;\n idx2 = dif < -tau * lambda;\n idx3 = abs(dif) <= tau * lambda;\n u_new = zeros(size(u));\n u_new(idx1) = u_tilde(idx1) - tau * lambda;\n u_new(idx2) = u_tilde(idx2) + tau * lambda;\n u_new(idx3) = img(idx3);\n else\n if alg == 2 || alg == 0\n denom = 1 + tau * lambda;\n end\n u_new = (u_tilde + tau * lambda * img(:)) / denom;\n end\n\n % ----- update tau and sigma -----\n if alg == 2\n theta = 1/(sqrt(1+2*gamma*tau));\n tau = tau * theta;\n sigma = sigma / theta;\n end\n if alg == 0\n theta_tmp = 1/(sqrt(1+2*gamma*tau));\n tau = tau * theta_tmp;\n sigma = sigma / theta_tmp;\n end\n\n \n % update ubar^n+1\n ubar = u_new + theta * (u_new - u);\n \n u = u_new;\n \n % compute the criterion function value\n criterion(step+1) = Fval(u, clear_img, alpha, huber) + lambda / lambda_denom * Gval(u, img, Lone);\n \n % plot current result\n if showfigs\n sfigure(fh1);\n imshow([img reshape(u, H, W)]);\n drawnow;\n \n sfigure(fh2);\n plot(0:step, criterion(1:step+1), 'b-');\n xlabel('step');\n ylabel('J(u)');\n drawnow;\n end\nend\n\nout_img = u;\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u53bb\u566a\u7b97\u6cd5/TVdenoising-master/TVdenoising.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183444, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6977784276834793}} {"text": "function COFMEn = COFMEn(data, m, r,fs)\n%******************************************************\n% $ This function is usded for calcualting the cofficient of fuzzy measure entropy (COFMEn) for physiological signal time sequence. \n% $ Using COFMEn aims to improve the performance of COSEn. \n%\n% $ Reference: Liu C Y, Li K, Zhao L N, Liu F, Zheng D C, Liu C C and Liu S\n% T. Analysis of heart rate variability using fuzzy measure entropy.\n% Computers in Biology and Medicine, 2013, 43(2): 100-108\n%\n% $ Variable declaration: \n% data is RR time series\n% m is embedding dimension (usually m=1)\n% r is threshold value (usually r=30 ms)\n% local threshold r_l=0.2, global threshold r_g=0.2, \n% local weight of sequence segments' similarity n_l=2\n% global weight of sequence segments' similarity n_g=2\n%\n% $ Author: Chengyu Liu (bestlcy@sdu.edu.cn) \n% Institute of Biomedical Engineering,\n% Shandong University\n% $Last updated: 2015.10.15\n%\n% LICENSE: \n% This software is offered freely and without warranty under \n% the GNU (v3 or later) public license. See license file for\n% more information\n\n% data=[108,108,109,109,108,108,110,107,109,109,109,109,108,109,108,108,108,108,107,108,108,108,108,107,109,107,108,107,108,108,108,108,108,108,108,109,108,109,108,108,109,108,108,108,109,107,108,107,107,108,108,108,109,107,108,108,108,108,108,108]*4;\n% data=[109,108,108,109,109,109,108,109,108,108,109,108,108,109,108,108,108,109,108,109,109,109,108,108,109,108,108,109,109,109]*4;\n% m=1;\n% r=30;\n\nN=length(data);\nfor i=1:N-m\n x1(i,:)=data(i:i+m-1);\n x2(i,:)=data(i:i+m);\nend\n\nratio=0.4;\nif N>20\n% Thr=ratio*N;\n Thr=5;\nelse\n Thr=5;\nend\n\n\nMin_numerator=0;\nkk=0;\nwhile Min_numerator20\n if N<20\n r=r-1;\n else\n r=r-1000/fs;\n end\nend\n\nif Min_numerator==N-m\n while Min_numerator>=Thr\n [Min_numerator,r]=ReGet_min_numerator2(x1,x2,N,m,r,fs);\n end\n if r<0\n r=r+2;\n else \n r=r+1;\n end\nend\n\nx=data;\nr_l = r;\nr_g = r;\nn_l = 2;\nn_g = 2;\n%% m=2\nD_l = zeros(N-m,1); % initiate the mean local distance vector\nD_g = zeros(N-m,1); % initiate the mean global distance vector\nfor i = 1:N-m\n distance_l = zeros(N-m,1); % initiate the local distance vector for the ith vector\n distance_g = zeros(N-m,1); % initiate the global distance vector for the ith vector\n for j = 1:N-m\n if j==i\n d_l = 0;\n d_g = 0;\n else\n d_l = max(abs(x(i:i+m-1)-mean(x(i:i+m-1))-x(j:j+m-1)+mean(x(j:j+m-1))));\n d_g = max(abs(x(i:i+m-1)-x(j:j+m-1)));\n end\n distance_l(j) = exp(-(d_l.^n_l/r_l));\n distance_g(j) = exp(-(d_g.^n_g/r_g));\n end\n D_l(i) = sum(distance_l)/(N-m-1);\n D_g(i) = sum(distance_g)/(N-m-1);\nend\nBm_l = mean(D_l);\nBm_g = mean(D_g);\n\n%% m=m+1\nm=m+1;\nD_l = zeros(N-m,1);\nD_g = zeros(N-m,1);\nfor i = 1:N-m\n distance_l = zeros(N-m,1);\n distance_g = zeros(N-m,1);\n for j = 1:N-m\n if j==i\n d_l = 0;\n d_g = 0;\n else\n d_l = max(abs(x(i:i+m-1)-mean(x(i:i+m-1))-x(j:j+m-1)+mean(x(j:j+m-1))));\n d_g = max(abs(x(i:i+m-1)-x(j:j+m-1)));\n end\n distance_l(j) = exp(-(d_l.^n_l/r_l));\n distance_g(j) = exp(-(d_g.^n_g/r_g));\n end\n D_l(i) = sum(distance_l)/(N-m-1);\n D_g(i) = sum(distance_g)/(N-m-1);\nend\nAm_l = mean(D_l);\nAm_g = mean(D_g);\n\n%% Calculate local and global fuzzy measure entropy\nFuzzyLMEn = -log(Am_l/Bm_l); % local fuzzy measure entropy\nFuzzyGMEn = -log(Am_g/Bm_g); % global fuzzy measure entropy\n%% Generate fuzzy measure entropy\nCOFMEn = FuzzyLMEn+FuzzyGMEn+2*log(2*r/1000)-2*log(mean(data)/1000);", "meta": {"author": "cliffordlab", "repo": "PhysioNet-Cardiovascular-Signal-Toolbox", "sha": "eec46e75e0b95c379ecb68cb0ebee0c4c9f54605", "save_path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox", "path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox/PhysioNet-Cardiovascular-Signal-Toolbox-eec46e75e0b95c379ecb68cb0ebee0c4c9f54605/Tools/ECG_Analysis_Tools/AF Feature Calculation/COFMEn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.697746873413283}} {"text": "function [ nxy, bxy, fxy ] = pce_legendre_linear_assemble ( n, p )\n\n%*****************************************************************************80\n%\n%% PCE_LEGENDRE_LINEAR_ASSEMBLE assembles a particular stochastic Galerkin matrix.\n%\n% Discussion:\n%\n% We wish to analyze a stochastic PDE of the form:\n%\n% -div A(X,Y) grad U(X,Y) = F(X)\n%\n% where \n%\n% U is an unknown scalar function, \n% A is a given diffusion function,\n% F is a given right hand side function,\n% X represents dependence on spatial variables,\n% Y represents dependence on stochastic variables. \n%\n% We let X be a space of finite element functions generated by piecewise linear\n% functions associated with a particular triangular dissection of the unit square.\n%\n% We let Y be the space of polynomials over R^N with total degree at most P.\n%\n% We seek solutions U in X cross Y using a polynomial chaos expansion approach.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 May 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of factors in the probability space.\n%\n% Input, integer P, the maximum degree of the basis functions for the \n% probability space.\n%\n% Output, integer NXY, the order of the matrix BXY. NXY = NX * NY.\n%\n% Output, real sparse BXY(NXY,NXY), the matrix.\n%\n% Output, real FXY(NXY), the right hand side.\n%\n% Local Parameters:\n%\n% Local, real AREA_X, the area of the current element.\n%\n% Local, integer BASIS_X_NUM, the number of finite element basis functions (3).\n%\n% Local, integer BASIS_Y_DEGREE(1:N), describes a particular basis function \n% in Y, in terms of the degrees of its components.\n%\n% Local, integer BASIS_Y_H(*), auxilliary \"external\" memory needed by \n% SUBCOMP_NEXT.\n%\n% Local, logical BASIS_Y_MORE, is set FALSE before the first call to \n% SUBCOMP_NEXT. SUBCOMP_NEXT returns the next subcomposition, and sets the \n% value of BASIS_Y_MORE to TRUE if there are even more subpositions that can \n% be produced, or FALSE if there are no more.\n%\n% Local, integer BASIS_Y_T(*), auxilliary \"external\" memory needed by \n% SUBCOMP_NEXT.\n%\n% Local, real BVEC(1:N,1:POINT_X_NUM), stores the KL expansion coefficients \n% of orders 1 through N at the spatial points POINT_X_P(1:2,1:POINT_X_NUM).\n%\n% Local, real BZERO(1:POINT_X_NUM), stores the KL expansion coefficients \n% of order 0 at the spatial points POINT_X_P(1:2,1:POINT_X_NUM).\n%\n% Local, real CLK(1:QUAD_X_NUM), contains the integral of the KL expansion \n% function for given values of the L-th probability basis function and the\n% K-th probability test function evaluated at the quadrature points in an \n% element.\n%\n% Local, integer ELEMENT_X, the element being considered.\n%\n% Local, integer ELEMENT_X_NUM, the number of elements in the finite element\n% problem.\n%\n% Local, integer ELEMENT_X_NODE(1:3,1:ELEMENT_X_NUM);\n% ELEMENT_X_NODE(I,J) is the global index of local node I in element J.\n%\n% Local, integer ELEMENT_X1_NUM, the number of (pairs) of elements in the \n% first spatial dimension in the finite element problem.\n%\n% Local, integer ELEMENT_X2_NUM, the number of (pairs) of elements in the \n% second spatial dimension in the finite element problem.\n%\n% Local, real FVEC(1:QUAD_X_NUM), stores the values of the function F which\n% is the right hand side of the PDE, at the quadrature points in an element.\n%\n% Local, integer I, the index of the finite element test function \n% PHI(1:NX)(X).\n%\n% Local, integer J, the index of the finite element basis function \n% PHI(1:NX)(X).\n%\n% Local, integer K, the index of the probability space test function \n% PSI(1:NY)(Y).\n%\n% Local, integer L, the index of the probability space basis function \n% PSI(1:NY)(Y).\n%\n% Local, integer NODE_X_NUM, the number of nodes.\n%\n% Local, real NODE_X_P(1:2,1:NODE_X_NUM), the coordinates of nodes.\n%\n% Local, integer NODE_X1_NUM, the number of nodes in the first space \n% direction.\n%\n% Local, integer NODE_X2_NUM, the number of nodes in the second space \n% direction.\n%\n% Local, integer NX, the dimension of the finite element space.\n% NX = NODE_X_NUM for a finite element problem involving a scalar variable U.\n%\n% Local, integer NY, = ( N + P)! / N! / P! = the dimension of the space Y, \n% the space of polynomials over R^N of total degree at most P.\n%\n% Local, real PHI(1:BASIS_X_NUM,1:QUAD_X_NUM), the finite element basis \n% functions, evaluated at all the quadrature points in a particular element.\n%\n% Local, real PHI_DX1(1:BASIS_X_NUM,1:QUAD_X_NUM), the derivative of the \n% finite element basis functions with respect to the first spatial variable, \n% evaluated at all the quadrature points in a particular element.\n%\n% Local, real PHI_DX2(1:BASIS_X_NUM,1:QUAD_X_NUM), the derivative of the \n% finite element basis functions with respect to the second spatial variable, \n% evaluated at all the quadrature points in a particular element.\n%\n% Local, real PHYS_X_P(1:2,1:QUAD_X_NUM), the \"physical\" coordinates of the \n% quadrature points in the current element.\n%\n% Local, integer QUAD_X, the index of the current X quadrature point.\n%\n% Local, integer QUAD_X_NUM, the order of the X quadrature rule.\n%\n% Local, real QUAD_X_P(1:2,1:QUAD_X_NUM), the points for the X quadrature \n% rule.\n%\n% Local, real QUAD_X_W(1:QUAD_X_NUM), the weights for the X quadrature rule.\n%\n% Local, real T3(1:2,1:3), the coordinates of the nodes that define the \n% current element.\n%\n% Local, real TABLE(1:P+1,1:P+1), a table of the values of integrals of the \n% 1D basis functions in Z. TABLE(D1+1,D2+1) \n% = Integral ( -1 <= Z <= +1 ) Z * PSI(D1)(Z) * PSI(D2)(Z) dZ.\n% \n% Local, integer TEST_X_NUM, the number of finite element test functions (3).\n%\n% Local, integer TEST_Y_DEGREE(1:N), describes a particular test function in \n% Y, in terms of the degrees of its components.\n%\n% Local, integer TEST_Y_H(*), auxilliary \"external\" memory needed by \n% SUBCOMP_NEXT.\n%\n% Local, logical TEST_Y_MORE, is set FALSE before the first call to \n% SUBCOMP_NEXT. SUBCOMP_NEXT returns the next subcomposition, and sets the \n% value of TESST_Y_MORE to TRUE if there are even more subpositions that can \n% be produced, or FALSE if there are no more.\n%\n% Local, integer TEST_Y_T(*), auxilliary \"external\" memory needed by \n% SUBCOMP_NEXT.\n%\n FALSE = 0;\n%\n% Some setup for the finite element calculation.\n%\n basis_x_num = 3;\n test_x_num = 3;\n node_x1_num = 11;\n node_x2_num = 11;\n node_x_num = node_x1_num * node_x2_num;\n nx = node_x_num;\n\n node_x_p = grid_nodes_01 ( node_x1_num, node_x2_num );\n\n element_x1_num = node_x1_num - 1;\n element_x2_num = node_x2_num - 1;\n element_x_num = 2 * element_x1_num * element_x2_num;\n element_x_node = grid_t3_element ( element_x1_num, element_x2_num );\n\n quad_x_num = 13;\n [ quad_x_p, quad_x_w ] = triangle_rule_13 ( );\n%\n% Some setup for the probability space.\n%\n ny = i4_choose ( n + p, n );\n\n e = 1;\n table = legendre_linear_product ( p, e );\n\n for i = 1 : p + 1\n for j = 1 : p + 1\n if ( abs ( table(i,j) ) < 10000 * eps )\n table(i,j) = 0.0;\n end\n end\n end\n%\n% Define the order of the matrix BXY,\n% Define BXY as a sparse matrix;\n% Define FXY as a column vector.\n%\n nxy = nx * ny;\n bxy = sparse ( [], [], [], nxy, nxy );\n fxy(1:nxy,1) = 0.0;\n%\n% LOOP L:\n% Generate the L-th basis function PSI(D,Y) in Y space. \n%\n basis_y_degree(1:n) = 0;\n basis_y_more = FALSE;\n basis_y_h = [];\n basis_y_t = [];\n basis_y_n2 = [];\n basis_y_more2 = [];\n l = 0;\n\n while ( 1 )\n\n l = l + 1;\n\n [ basis_y_degree, basis_y_more, basis_y_h, basis_y_t, basis_y_n2, basis_y_more2 ] = ...\n subcomp_next ( p, n, basis_y_degree, basis_y_more, basis_y_h, basis_y_t, basis_y_n2, ...\n basis_y_more2 ); \n%\n% LOOP K:\n% Generate the K-th test function PSI(D,Y) in Y space.\n%\n test_y_degree(1:n) = 0;\n test_y_more = FALSE;\n test_y_h = [];\n test_y_t = [];\n test_y_n2 = [];\n test_y_more2 = [];\n k = 0;\n\n while ( 1 )\n\n k = k + 1;\n\n [ test_y_degree, test_y_more, test_y_h, test_y_t, test_y_n2, test_y_more2 ] = ...\n subcomp_next ( p, n, test_y_degree, test_y_more, test_y_h, test_y_t, test_y_n2, ...\n test_y_more2 ); \n\n for element_x = 1 : element_x_num\n%\n% For ALL the quadrature points in this element, evaluate:\n% * PHI the basis functions;\n% * PHI_DX1 and PHI_DX2, basis function derivatives;\n% * PHYS_X_P, the physical coordinates of the quadrature points;\n% * BZERO and BVEC, the coefficient functions in the KL expansion for CLK;\n% * CLK, the KL function integrated against the probability basis and test functions;\n% * FVEC, the right hand side of the PDE.\n%\n t3(1:2,1:3) = node_x_p(1:2,element_x_node(1:3,element_x));\n\n area_x = abs ( triangle_area_2d ( t3 ) );\n\n [ phi, phi_dx1, phi_dx2 ] = basis_mn_t3 ( t3, quad_x_num, quad_x_p );\n\n phys_x_p(1:2,1:quad_x_num) = reference_to_physical_t3 ( t3, quad_x_num, quad_x_p );\n\n [ bzero, bvec ] = b_evaluator ( n, quad_x_num, phys_x_p );\n\n if ( l == k )\n clk(1:quad_x_num) = bzero(1:quad_x_num);\n else\n clk(1:quad_x_num) = 0.0;\n end\n\n for i2 = 1 : n\n\n factor = 1.0;\n for i3 = 1 : n\n if ( i3 ~= i2 )\n if ( basis_y_degree(i3) ~= test_y_degree(i3) )\n factor = 0.0;\n end\n end\n end\n\n clk(1:quad_x_num) = clk(1:quad_x_num) ...\n + bvec(i2,1:quad_x_num) * table(basis_y_degree(i2)+1,test_y_degree(i2)+1)...\n * factor;\n\n end\n\n fvec = f_evaluator ( quad_x_num, phys_x_p );\n%\n% Integrate over the finite element space X.\n%\n for quad_x = 1 : quad_x_num\n%\n% LOOP J:\n% All finite element basis functions J.\n% But we actually only look at those which are nonzero in this element.\n%\n for basis_x = 1 : basis_x_num\n \n j = element_x_node(basis_x,element_x);\n%\n% LOOP I:\n% Finite element test function I.\n% But we actually only look at those which are nonzero in this element.\n%\n for test_x = 1 : test_x_num\n\n i = element_x_node(test_x,element_x);\n\n ik = ( k - 1 ) * node_x_num + i;\n jl = ( l - 1 ) * node_x_num + j;\n%\n% If I is a boundary node, the equation associated with its test function\n% is replaced by a simple equation that enforces a zero Dirichlet condition.\n% \n if ( i <= node_x1_num || ...\n node_x1_num * ( node_x2_num - 1) + 1 <= i || ...\n mod ( i, node_x1_num ) == 1 || ...\n mod ( i, node_x1_num ) == 0 )\n\n if ( ik == jl )\n bxy(ik,jl) = 1.0;\n fxy(ik) = 0.0;\n end\n%\n% If I is not a boundary node, the equation associated with its test function\n% generates a finite element equation.\n%\n else\n\n bxy(ik,jl) = bxy(ik,jl) + quad_x_w(quad_x) * area_x ...\n * clk(quad_x) ...\n * ( phi_dx1(test_x,quad_x) * phi_dx1(basis_x,quad_x) ...\n + phi_dx2(test_x,quad_x) * phi_dx2(basis_x,quad_x) );\n%\n% The only nonzero result for the right hand side FXY occurs when K = 1,\n% since this is the single test function in Y which is the product of N \n% copies of the constant Legendre polynomial. \n%\n% (This is true as long as there is no Y dependence in F(), and\n% assuming we are using Legendre polynomials.)\n%\n if ( k == 1 )\n psi0_integral = 1 / sqrt ( 2^n );\n fxy(ik) = fxy(ik) + quad_x_w(quad_x) * area_x ...\n * fvec(quad_x) * phi(test_x,quad_x) * psi0_integral;\n end\n\n end\n\n end\n end \n end\n\n end\n\n if ( test_y_more == FALSE )\n break\n end\n\n end\n\n if ( basis_y_more == FALSE )\n break\n end\n\n end\n\n return\nend\nfunction [ bzero, bvec ] = b_evaluator ( n, nx, x )\n\n%*****************************************************************************80\n%\n%% B_EVALUATOR evaluates KL expansion coefficients for the diffusion coefficient.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 May 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of factors in the probability space.\n%\n% Input, integer NX, the number of points.\n%\n% Input, real X(1:2,1:NX), the point coordinates.\n%\n% Output, real BZERO(1:NX), the zero-th order coefficient evaluated at X.\n%\n% Output, real BVEC(1:N,1:NX), the coefficients of orders 1 to N, \n% evaluated at X.\n%\n bzero(1:nx) = 1.0;\n bvec = zeros ( n, nx );\n for i = 1 : n\n bvec(i,1:nx) = sin ( i * x(1,1:nx) );\n end\n\n return\nend\nfunction [ phi, dphidx, dphidy ] = basis_mn_t3 ( t, n, p )\n\n%*****************************************************************************80\n%\n%% BASIS_MN_T3: all bases functions at N points for a T3 element.\n%\n% Discussion:\n%\n% The routine is given the coordinates of the vertices of a triangle.\n% It works directly with these coordinates, and does not refer to a \n% reference element.\n%\n% The sides of the triangle DO NOT have to lie along a coordinate\n% axis.\n%\n% The routine evaluates the basis functions associated with each vertex,\n% and their derivatives with respect to X and Y.\n%\n% Physical Element T3:\n%\n% 3\n% / \\\n% / \\\n% / \\\n% / \\\n% 1---------2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T(2,3), the vertices of the triangle. It is common to list \n% these points in counter clockwise order.\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real P(2,N), the coordinates of the evaluation points.\n%\n% Output, real PHI(3,N), the basis functions at the evaluation points.\n%\n% Output, real DPHIDX(3,N), DPHIDY(3,N), the basis derivatives \n% at the evaluation points.\n%\n% Local parameters:\n%\n% Local, real AREA, is (twice) the area of the triangle.\n%\n area = t(1,1) * ( t(2,2) - t(2,3) ) ...\n + t(1,2) * ( t(2,3) - t(2,1) ) ...\n + t(1,3) * ( t(2,1) - t(2,2) );\n\n phi(1,1:n) = ( ( t(1,3) - t(1,2) ) * ( p(2,1:n) - t(2,2) ) ...\n - ( t(2,3) - t(2,2) ) * ( p(1,1:n) - t(1,2) ) );\n dphidx(1,1:n) = - ( t(2,3) - t(2,2) );\n dphidy(1,1:n) = ( t(1,3) - t(1,2) );\n\n phi(2,1:n) = ( ( t(1,1) - t(1,3) ) * ( p(2,1:n) - t(2,3) ) ...\n - ( t(2,1) - t(2,3) ) * ( p(1,1:n) - t(1,3) ) );\n dphidx(2,1:n) = - ( t(2,1) - t(2,3) );\n dphidy(2,1:n) = ( t(1,1) - t(1,3) );\n\n phi(3,1:n) = ( ( t(1,2) - t(1,1) ) * ( p(2,1:n) - t(2,1) ) ...\n - ( t(2,2) - t(2,1) ) * ( p(1,1:n) - t(1,1) ) );\n dphidx(3,1:n) = - ( t(2,2) - t(2,1) );\n dphidy(3,1:n) = ( t(1,2) - t(1,1) );\n%\n% Normalize.\n%\n phi(1:3,1:n) = phi(1:3,1:n) / area;\n dphidx(1:3,1:n) = dphidx(1:3,1:n) / area;\n dphidy(1:3,1:n) = dphidy(1:3,1:n) / area;\n\n return\nend\nfunction [ a, more, h, t ] = comp_next ( n, k, a, more, h, t )\n\n%*****************************************************************************80\n%\n%% COMP_NEXT computes the 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 routine computes one composition on each call until there are no more.\n% For instance, one composition of 6 into 3 parts is\n% 3+2+1, another would be 6+0+0.\n%\n% On the first call to this routine, set MORE = FALSE. The routine\n% will compute the first element in the sequence of compositions, and\n% return it, as well as setting MORE = TRUE. If more compositions\n% are desired, call again, and again. Each time, the routine will\n% return with a new composition.\n%\n% However, when the LAST composition in the sequence is computed \n% and returned, the routine will reset MORE to FALSE, signaling that\n% the end of the sequence has been reached.\n%\n% This routine originally used a SAVE statement to maintain the\n% variables H and T. I have decided (based on wasting an\n% entire morning trying to track down a problem) that it is safer\n% to pass these variables as arguments, even though the user should\n% never alter them. This allows this routine to safely shuffle\n% between several ongoing calculations.\n%\n% Example:\n%\n% The 28 compositions of 6 into three parts are:\n%\n% 6 0 0,\n% 5 1 0,\n% 5 0 1,\n% 4 2 0,\n% 4 1 1,\n% 4 0 2,\n% 3 3 0,\n% 3 2 1,\n% 3 1 2,\n% 3 0 3,\n% 2 4 0,\n% 2 3 1,\n% 2 2 2,\n% 2 1 3,\n% 2 0 4,\n% 1 5 0,\n% 1 4 1,\n% 1 3 2,\n% 1 2 3,\n% 1 1 4,\n% 1 0 5,\n% 0 6 0,\n% 0 5 1,\n% 0 4 2,\n% 0 3 3,\n% 0 2 4,\n% 0 1 5,\n% 0 0 6.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 July 2007\n%\n% Author:\n%\n% Original FORTRAN77 version by Albert Nijenhuis and Herbert Wilf\n% MATLAB version by 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% Input, integer A(K), the previous composition. On the first call,\n% with MORE = FALSE, set A = []. Thereafter, A should be the \n% value of A output from the previous call.\n%\n% Input, logical MORE. The input value of MORE on the first\n% call should be FALSE, which tells the program to initialize.\n% On subsequent calls, MORE should be TRUE, or simply the\n% output value of MORE from the previous call.\n%\n% Input, integer H, T, two internal parameters needed for the\n% computation. The user may need to initialize these before the\n% very first call, but these initial values are not important.\n% The user should not alter these parameters once the computation\n% begins.\n%\n% Output, integer A(K), the next composition.\n%\n% Output, logical MORE, will be TRUE unless the composition \n% that is being returned is the final one in the sequence.\n%\n% Output, integer H, T, the updated values of the two internal \n% parameters.\n%\n if ( ~more )\n\n t = n;\n h = 0;\n a(1) = n;\n a(2:k) = 0;\n\n else\n \n if ( 1 < t )\n h = 0;\n end\n\n h = h + 1;\n t = a(h);\n a(h) = 0;\n a(1) = t - 1;\n a(h+1) = a(h+1) + 1;\n\n end\n\n more = ( a(k) ~= n );\n\n return\nend\nfunction fvec = f_evaluator ( n, x )\n\n%*****************************************************************************80\n%\n%% F_EVALUATOR evaluates the finite element right hand side function F.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 May 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of point.\n%\n% Input, real X(2,N), the point coordinates.\n%\n% Output, real FVEC(N), the value of F at the points.\n%\n fvec(1:n) = sin ( pi * x(1,1:n) ) .* sin ( pi * x(2,1:n) );\n\n return\nend\nfunction node_xy = grid_nodes_01 ( x_num, y_num )\n\n%*****************************************************************************80\n%\n%% GRID_NODES_01 returns an equally spaced grid of nodes in the unit square.\n%\n% Example:\n%\n% X_NUM = 5\n% Y_NUM = 3\n%\n% NODE_XY = \n% ( 0, 0.25, 0.5, 0.75, 1, 0, 0.25, 0.5, 0.75, 1, 0, 0.25, 0.5, 0.75, 1;\n% 0, 0, 0, 0, 0, 0.5, 0.5, 0.5, 0.5, 0.5, 1, 1.0, 1.0, 1.0, 1 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 May 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer X_NUM, Y_NUM, the number of nodes in the X and Y directions.\n%\n% Output, real NODE_XY(2,X_NUM*Y_NUM), the coordinates of the nodes.\n%\n node_num = x_num * y_num;\n\n node_xy(1:2,1:node_num) = 0.0;\n\n for i = 1 : x_num\n node_xy(1,i:x_num:i+(y_num-1)*x_num) = ( i - 1 ) / ( x_num - 1 );\n end\n\n for j = 1 : y_num\n node_xy(2,1+(j-1)*x_num:j*x_num) = ( j - 1 ) / ( y_num - 1 );\n end\n\n return\nend\nfunction [ element_node ] = grid_t3_element ( nelemx, nelemy )\n\n%*****************************************************************************80\n%\n%% GRID_T3_ELEMENT produces a grid of pairs of 3 node triangles.\n%\n% Example:\n%\n% Input:\n%\n% NELEMX = 3, NELEMY = 2\n%\n% Output:\n%\n% ELEMENT_NODE =\n% 1, 2, 5;\n% 6, 5, 2;\n% 2, 3, 6;\n% 7, 6, 3;\n% 3, 4, 7;\n% 8, 7, 4;\n% 5, 6, 9;\n% 10, 9, 6;\n% 6, 7, 10;\n% 11, 10, 7;\n% 7, 8, 11;\n% 12, 11, 8.\n%\n% Grid:\n%\n% 9---10---11---12\n% |\\ 8 |\\10 |\\12 |\n% | \\ | \\ | \\ |\n% | \\ | \\ | \\ |\n% | 7\\| 9\\| 11\\|\n% 5----6----7----8\n% |\\ 2 |\\ 4 |\\ 6 |\n% | \\ | \\ | \\ |\n% | \\ | \\ | \\ |\n% | 1\\| 3\\| 5\\|\n% 1----2----3----4\n%\n% Reference Element T3:\n%\n% |\n% 1 3\n% | |\\\n% | | \\\n% S | \\\n% | | \\\n% | | \\\n% 0 1-----2\n% |\n% +--0--R--1-->\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NELEMX, NELEMY, the number of elements along the\n% X and Y directions. The number of elements generated will be\n% 2 * NELEMX * NELEMY.\n%\n% Output, integer ELEMENT_NODE(3,2*NELEMX*NELEMY), the nodes that form\n% each element.\n%\n\n%\n% Node labeling:\n%\n% NW--NE\n% |\\ |\n% | \\|\n% SW--SE\n%\n element = 0;\n element_node = zeros ( 3, 2 * nelemx * nelemy );\n for j = 1 : nelemy\n for i = 1 : nelemx\n\n sw = i + ( j - 1 ) * ( nelemx + 1 );\n se = i + 1 + ( j - 1 ) * ( nelemx + 1 );\n nw = i + j * ( nelemx + 1 );\n ne = i + 1 + j * ( nelemx + 1 );\n\n element = element + 1;\n\n element_node(1,element) = sw;\n element_node(2,element) = se;\n element_node(3,element) = nw;\n\n element = element + 1;\n\n element_node(1,element) = ne;\n element_node(2,element) = nw;\n element_node(3,element) = se;\n\n end\n end\n\n return\nend\nfunction value = i4_choose ( n, k )\n\n%*****************************************************************************80\n%\n%% I4_CHOOSE computes the binomial coefficient C(N,K).\n%\n% Discussion:\n%\n% The value is calculated in such a way as to avoid overflow and\n% roundoff. The calculation is done in integer arithmetic.\n%\n% The formula used is:\n%\n% C(N,K) = N! / ( K! * (N-K)! )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 June 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% ML Wolfson, HV Wright,\n% Algorithm 160:\n% Combinatorial of M Things Taken N at a Time,\n% Communications of the ACM,\n% Volume 6, Number 4, April 1963, page 161.\n%\n% Parameters:\n%\n% Input, integer N, K, are the values of N and K.\n%\n% Output, integer VALUE, the number of combinations of N\n% things taken K at a time.\n%\n mn = min ( k, n - k );\n\n if ( mn < 0 )\n\n value = 0;\n\n elseif ( mn == 0 )\n\n value = 1;\n\n else\n\n mx = max ( k, n - k );\n value = mx + 1;\n\n for i = 2 : mn\n value = ( value * ( mx + i ) ) / i;\n end\n\n end\n\n return\nend\nfunction table = legendre_linear_product ( p, e )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_LINEAR_PRODUCT computes a linearly weighted Legendre product table.\n%\n% Discussion:\n%\n% Let L(i)(X) represent the Legendre polynomial of degree i. \n%\n% For polynomial chaos applications, it is of interest to know the\n% value of the integrals of products of X with every possible pair\n% of basis functions. That is, we'd like to form\n%\n% Tij = Integral ( -1 <= X <= +1 ) X^E * L(i)(X) * L(j)(X) dx\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 May 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer P, the maximum degree of the polyonomial factors.\n% 0 <= P.\n%\n% Input, integer E, the exponent of X in the integrand.\n% 0 <= E.\n%\n% Output, real TABLE(P+1,P+1), the table of integrals. TABLE(I,J)\n% represents the weighted integral of X^E * L(i+1)(X) * L(j+1)(X).\n%\n table(1:p+1,1:p+1) = 0.0;\n\n order = p + 1 + floor ( ( e + 1 ) / 2 );\n [ x_table, w_table ] = legendre_quadrature_rule ( order );\n\n for k = 1 : order\n\n x = x_table(k);\n l_table = legendre_polynomial ( p, x );\n%\n% The following formula is an outer product in L_TABLE.\n%\n if ( e == 0 )\n table(1:p+1,1:p+1) = table(1:p+1,1:p+1) ...\n + w_table(k) * l_table(1:p+1)' * l_table(1:p+1);\n else\n table(1:p+1,1:p+1) = table(1:p+1,1:p+1) ...\n + w_table(k) * x^e * l_table(1:p+1)' * l_table(1:p+1);\n end\n\n end\n\n return\nend\nfunction l = legendre_polynomial ( p, x )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_POLYNOMIAL evaluates the Legendre polynomials L(0:P)(X).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 May 2008\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% Daniel Zwillinger, editor,\n% CRC Standard Mathematical Tables and Formulae,\n% 30th Edition,\n% CRC Press, 1996.\n%\n% Parameters:\n%\n% Input, integer P, the highest evaluation degree.\n%\n% Input, real X, the evaluation point.\n%\n% Output, real L(1:P+1), the Legendre polynomials of order 0 through P at X.\n%\n if ( p < 0 )\n l = [];\n return\n end\n%\n% Allocate space.\n%\n l(1:p+1) = 0.0;\n%\n% Apply recursion.\n%\n l(1) = 1.0;\n\n if ( 1 <= p )\n\n l(2) = x;\n \n for i = 2 : p\n \n l(i+1) = ( ( 2 * i - 1 ) * x * l(i) ...\n - ( i - 1 ) * l(i-1) ) ...\n / ( i );\n \n end\n\n end\n%\n% Normalize.\n%\n l(1:p+1) = l(1:p+1) .* sqrt ( ( 1 : 2 : 2*p+1 ) / 2 );\n\n return\nend\nfunction [ xtab, weight ] = legendre_quadrature_rule ( order )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_QUADRATURE_RULE computes a Gauss-Legendre quadrature rule.\n%\n% Discussion:\n%\n% The integration interval is [ -1, 1 ].\n%\n% The weight function is w(x) = 1.0.\n%\n% The integral to approximate:\n%\n% Integral ( -1 <= X <= 1 ) F(X) dX\n%\n% The quadrature rule:\n%\n% Sum ( 1 <= I <= NORDER ) WEIGHT(I) * F ( XTAB(I) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 May 2008\n%\n% Author:\n%\n% FORTRAN77 original version by Philip Davis, Philip Rabinowitz\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Philip Davis, Philip Rabinowitz,\n% Methods of Numerical Integration,\n% Second Edition,\n% Dover, 2007,\n% ISBN: 0486453391,\n% LC: QA299.3.D28.\n%\n% Parameters:\n%\n% Input, integer ORDER, the order of the rule.\n% ORDER must be greater than 0.\n%\n% Output, real XTAB(ORDER), the abscissas of the rule.\n%\n% Output, real WEIGHT(ORDER), the weights of the rule.\n% The weights are positive, symmetric, and should sum to 2.\n%\n xtab = zeros ( order, 1 );\n weight = zeros ( order, 1 );\n \n if ( order < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LEGENDRE_RULE - Fatal error!\\n' );\n fprintf ( 1, ' Illegal value of ORDER = %d\\n', order );\n error ( 'LEGENDRE_RULE - Fatal error!' );\n end\n\n e1 = order * ( order + 1 );\n\n m = floor ( ( order + 1 ) / 2 );\n\n for i = 1 : floor ( ( order + 1 ) / 2 )\n\n mp1mi = m + 1 - i;\n\n t = ( 4 * i - 1 ) * pi / ( 4 * order + 2 );\n\n x0 = cos(t) * ( 1.0 - ( 1.0 - 1.0 / ( order ) ) / ( 8 * order * order ) );\n\n pkm1 = 1.0;\n pk = x0;\n\n for k = 2 : order\n pkp1 = 2.0 * x0 * pk - pkm1 - ( x0 * pk - pkm1 ) / k;\n pkm1 = pk;\n pk = pkp1;\n end\n\n d1 = order * ( pkm1 - x0 * pk );\n\n dpn = d1 / ( 1.0 - x0 * x0 );\n\n d2pn = ( 2.0 * x0 * dpn - e1 * pk ) / ( 1.0 - x0 * x0 );\n\n d3pn = ( 4.0 * x0 * d2pn + ( 2.0 - e1 ) * dpn ) / ( 1.0 - x0 * x0 );\n\n d4pn = ( 6.0 * x0 * d3pn + ( 6.0 - e1 ) * d2pn ) / ( 1.0 - x0 * x0 );\n\n u = pk / dpn;\n v = d2pn / dpn;\n%\n% Initial approximation H:\n%\n h = - u * ( 1.0 + 0.5 * u * ( v + u * ( v * v - d3pn / ( 3.0 * dpn ) ) ) );\n%\n% Refine H using one step of Newton's method:\n%\n p = pk + h * ( dpn + 0.5 * h * ( d2pn + h / 3.0 ...\n * ( d3pn + 0.25 * h * d4pn ) ) );\n\n dp = dpn + h * ( d2pn + 0.5 * h * ( d3pn + h * d4pn / 3.0 ) );\n\n h = h - p / dp;\n\n xtemp = x0 + h;\n\n xtab(mp1mi) = xtemp;\n\n fx = d1 - h * e1 * ( pk + 0.5 * h * ( dpn + h / 3.0 ...\n * ( d2pn + 0.25 * h * ( d3pn + 0.2 * h * d4pn ) ) ) );\n\n weight(mp1mi) = 2.0 * ( 1.0 - xtemp * xtemp ) / fx / fx;\n\n end\n\n if ( mod ( order, 2 ) == 1 )\n xtab(1) = 0.0;\n end\n%\n% Shift the data up.\n%\n nmove = floor ( ( order + 1 ) / 2 );\n ncopy = order - nmove;\n\n for i = 1 : nmove\n iback = order + 1 - i;\n xtab(iback) = xtab(iback-ncopy);\n weight(iback) = weight(iback-ncopy);\n end\n%\n% Reflect values for the negative abscissas.\n%\n for i = 1 : order - nmove\n xtab(i) = - xtab(order+1-i);\n weight(i) = weight(order+1-i);\n end\n\n return\nend\nfunction phy = reference_to_physical_t3 ( t, n, ref )\n\n%*****************************************************************************80\n%\n%% REFERENCE_TO_PHYSICAL_T3 maps a reference point to a physical point.\n%\n% Discussion:\n%\n% Given the vertices of an order 3 physical triangle and a point\n% (XSI,ETA) in the reference triangle, the routine computes the value\n% of the corresponding image point (X,Y) in physical space.\n%\n% Note that this routine may also be appropriate for an order 6\n% triangle, if the mapping between reference and physical space\n% is linear. This implies, in particular, that the sides of the\n% image triangle are straight and that the \"midside\" nodes in the\n% physical triangle are halfway along the sides of\n% the physical triangle.\n%\n% The T3 reference element is suggested by the following diagram:\n%\n% |\n% 1 3\n% | |\\\n% | | \\\n% S | \\\n% | | \\\n% | | \\\n% 0 1-----2\n% |\n% +--0--R--1-->\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 June 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T(2,3), the coordinates of the vertices. The vertices are assumed \n% to be the images of (0,0), (1,0) and (0,1) respectively.\n%\n% Input, integer N, the number of points to transform.\n%\n% Input, real REF(2,N), the coordinates of points in the reference space.\n%\n% Output, real PHY(2,N), the coordinates of the corresponding points in the \n% physical space.\n%\n phy = zeros ( 2, n );\n \n for i = 1 : 2\n\n phy(i,1:n) = t(i,1) * ( 1.0 - ref(1,1:n) - ref(2,1:n) ) ...\n + t(i,2) * ref(1,1:n) ...\n + t(i,3) * ref(2,1:n);\n end\n\n return\nend\nfunction [ a, more, h, t, n2, more2 ] = subcomp_next ( n, k, a, more, h, t, ...\n n2, more2 )\n\n%*****************************************************************************80\n%\n%% SUBCOMP_NEXT computes the next subcomposition of 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 a value of N.\n%\n% A subcomposition of the integer N into K parts is a composition\n% of M into K parts, where 0 <= M <= N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 May 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the integer whose subcompositions are desired.\n%\n% Input, integer K, the number of parts in the subcomposition.\n%\n% Input, integer A(K), the parts of the subcomposition.\n%\n% Input, logical MORE, set to FALSE by the user to start the computation.\n%\n% Input, integer H, T, N2, MORE2, internal parameters needed for the\n% computation. The user may need to initialize these before the\n% very first call, but these initial values are not important.\n% The user should not alter these parameters once the computation\n% begins.\n%\n% Output, integer A(K), the parts of the subcomposition.\n%\n% Output, logical MORE, set to FALSE by the routine to terminate \n% the computation.\n%\n% Output, integer H, T, N2, MORE2, the updated values of the two internal \n% parameters.\n%\n\n%\n% The first computation.\n%\n if ( ~more )\n\n n2 = 0;\n a(1:k) = 0;\n more2 = 0;\n h = 0;\n t = 0;\n\n more = 1;\n%\n% Do the next element at the current value of N.\n%\n elseif ( more2 )\n\n [ a, more2, h, t ] = comp_next ( n2, k, a, more2, h, t );\n\n else\n\n more2 = 0;\n n2 = n2 + 1;\n\n [ a, more2, h, t ] = comp_next ( n2, k, a, more2, h, t );\n\n end\n%\n% Termination occurs if MORE2 = FALSE and N2 = N.\n%\n if ( ~more2 && n2 == n )\n more = 0;\n end\n\n return\nend\nfunction area = triangle_area_2d ( t )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_AREA_2D computes the area of a triangle in 2D.\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, real T(2,3), the triangle vertices.\n%\n% Output, real AREA, the absolute area of the triangle.\n%\n area = 0.5 * abs ( ...\n t(1,1) * ( t(2,2) - t(2,3) ) ...\n + t(1,2) * ( t(2,3) - t(2,1) ) ...\n + t(1,3) * ( t(2,1) - t(2,2) ) );\n\n return\nend\nfunction [ x, w ] = triangle_rule_13 ( )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_RULE_13 sets a 13 point quadrature rule for triangles.\n%\n% Discussion:\n%\n% The Integration region is points (X,Y) such that\n%\n% 0 <= X,\n% 0 <= Y, and\n% X + Y <= 1.\n%\n% Graph:\n%\n% ^\n% 1 | *\n% | |\\\n% Y | | \\\n% | | \\\n% 0 | *---*\n% +------->\n% 0 X 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 12 May 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Gilbert Strang, George Fix,\n% An Analysis of the Finite Element Method,\n% Prentice Hall, 1973, page 184,\n% ISBN: 096140888X,\n% LC: TA335.S77.\n%\n% Parameters:\n%\n% Output, real X(2,13), the abscissas.\n%\n% Output, real W(13), the weights.\n%\n a = 0.479308067841923;\n b = 0.260345966079038;\n c = 0.869739794195568;\n d = 0.065130102902216;\n e = 0.638444188569809;\n f = 0.312865496004875;\n g = 0.048690315425316;\n h = 1.0 / 3.0;\n t = 0.175615257433204;\n u = 0.053347235608839;\n v = 0.077113760890257;\n w = -0.149570044467670;\n\n x(1:2,1:13) = [ a, b, b, c, d, d, e, e, f, f, g, g, h;\n b, a, b, d, c, d, f, g, e, g, e, f, h ];\n\n w(1:13) = [ t, t, t, u, u, u, v, v, v, v, v, v, w ];\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/pce_legendre/pce_legendre_linear_assemble.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6977468583000501}} {"text": "% ATAN Inverse tangent, result in radians.\n% ATAN(X) is the arctangent of the elements of X.\n% \n% See also ATAN2, TAN, ATAND, ATAN2D.\n%\n% Reference page in Doc Center\n% doc atan\n%\n% Other functions named atan\n%\n% codistributed/atan gpuArray/atan sym/atan ts/atan\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/atan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.6977176668198576}} {"text": "function legendre_set_test ( )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_SET_TEST tests LEGENDRE_SET.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 November 2014\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LEGENDRE_SET_TEST\\n' );\n fprintf ( 1, ' LEGENDRE_SET returns points and weights of \\n' );\n fprintf ( 1, ' Gauss-Legendre quadrature rules.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N 1 X^4 Runge\\n' );\n fprintf ( 1, '\\n' );\n\n for n = 1 : 10\n [ x, w ] = legendre_set ( n );\n e1 = sum ( w(1:n,1) );\n e2 = w(1:n,1)' * x(1:n,1).^4;\n e3 = w(1:n,1)' * ( 1.0 ./ ( 1.0 + 25.0 * x(1:n,1).^2 ) );\n fprintf ( 1, ' %2d %14.6g %14.6g %14.6g\\n', n, e1, e2, e3 );\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/fem1d_lagrange/legendre_set_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.697717650988376}} {"text": "%% Machine Learning Online Class\n% Exercise 5 | Regularized Linear Regression and Bias-Variance\n%\n% Instructions\n% ------------\n% \n% This file contains code that helps you get started on the\n% exercise. You will need to complete the following functions:\n%\n% linearRegCostFunction.m\n% learningCurve.m\n% validationCurve.m\n%\n% For this exercise, you will not need to change any code in this file,\n% or any other files other than those mentioned above.\n%\n\n%% Initialization\nclear ; close all; clc\n\n%% =========== Part 1: Loading and Visualizing Data =============\n% We start the exercise by first loading and visualizing the dataset. \n% The following code will load the dataset into your environment and plot\n% the data.\n%\n\n% Load Training Data\nfprintf('Loading and Visualizing Data ...\\n')\n\n% Load from ex5data1: \n% You will have X, y, Xval, yval, Xtest, ytest in your environment\nload ('ex5data1.mat');\n\n% m = Number of examples\nm = size(X, 1);\n\n% Plot training data\nplot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);\nxlabel('Change in water level (x)');\nylabel('Water flowing out of the dam (y)');\n\nfprintf('Program paused. Press enter to continue.\\n');\n% pause;\n\n%% =========== Part 2: Regularized Linear Regression Cost =============\n% You should now implement the cost function for regularized linear \n% regression. \n%\n\ntheta = [1 ; 1];\nJ = linearRegCostFunction([ones(m, 1) X], y, theta, 1);\n\nfprintf(['Cost at theta = [1 ; 1]: %f '...\n '\\n(this value should be about 303.993192)\\n'], J);\n\nfprintf('Program paused. Press enter to continue.\\n');\n% pause;\n\n%% =========== Part 3: Regularized Linear Regression Gradient =============\n% You should now implement the gradient for regularized linear \n% regression.\n%\n\ntheta = [1 ; 1];\n[J, grad] = linearRegCostFunction([ones(m, 1) X], y, theta, 1);\n\nfprintf(['Gradient at theta = [1 ; 1]: [%f; %f] '...\n '\\n(this value should be about [-15.303016; 598.250744])\\n'], ...\n grad(1), grad(2));\n\nfprintf('Program paused. Press enter to continue.\\n');\n% pause;\n\n\n%% =========== Part 4: Train Linear Regression =============\n% Once you have implemented the cost and gradient correctly, the\n% trainLinearReg function will use your cost function to train \n% regularized linear regression.\n% \n% Write Up Note: The data is non-linear, so this will not give a great \n% fit.\n%\n\n% Train linear regression with lambda = 0\nlambda = 0;\n[theta] = trainLinearReg([ones(m, 1) X], y, lambda);\n\n% Plot fit over the data\nplot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);\nxlabel('Change in water level (x)');\nylabel('Water flowing out of the dam (y)');\nhold on;\nplot(X, [ones(m, 1) X]*theta, '--', 'LineWidth', 2)\nhold off;\n\nfprintf('Program paused. Press enter to continue.\\n');\n% pause;\n\n\n%% =========== Part 5: Learning Curve for Linear Regression =============\n% Next, you should implement the learningCurve function. \n%\n% Write Up Note: Since the model is underfitting the data, we expect to\n% see a graph with \"high bias\" -- slide 8 in ML-advice.pdf \n%\n\n\n\nlambda = 0;\n[error_train, error_val] = ...\n learningCurve([ones(m, 1) X], y, ...\n [ones(size(Xval, 1), 1) Xval], yval, ...\n lambda);\n\nplot(1:m, error_train, 1:m, error_val);\ntitle('Learning curve for linear regression')\nlegend('Train', 'Cross Validation')\nxlabel('Number of training examples')\nylabel('Error')\naxis([0 13 0 150])\n\nfprintf('# Training Examples\\tTrain Error\\tCross Validation Error\\n');\nfor i = 1:m\n fprintf(' \\t%d\\t\\t%f\\t%f\\n', i, error_train(i), error_val(i));\nend\n\nfprintf('Program paused. Press enter to continue.\\n');\n% pause;\n\n%% =========== Part 6: Feature Mapping for Polynomial Regression =============\n% One solution to this is to use polynomial regression. You should now\n% complete polyFeatures to map each example into its powers\n%\n\np = 8;\n\n% Map X onto Polynomial Features and Normalize\nX_poly = polyFeatures(X, p);\n[X_poly, mu, sigma] = featureNormalize(X_poly); % Normalize\nX_poly = [ones(m, 1), X_poly]; % Add Ones\n\n% Map X_poly_test and normalize (using mu and sigma)\nX_poly_test = polyFeatures(Xtest, p);\nX_poly_test = bsxfun(@minus, X_poly_test, mu);\nX_poly_test = bsxfun(@rdivide, X_poly_test, sigma);\nX_poly_test = [ones(size(X_poly_test, 1), 1), X_poly_test]; % Add Ones\n\n% Map X_poly_val and normalize (using mu and sigma)\nX_poly_val = polyFeatures(Xval, p);\nX_poly_val = bsxfun(@minus, X_poly_val, mu);\nX_poly_val = bsxfun(@rdivide, X_poly_val, sigma);\nX_poly_val = [ones(size(X_poly_val, 1), 1), X_poly_val]; % Add Ones\n\nfprintf('Normalized Training Example 1:\\n');\nfprintf(' %f \\n', X_poly(1, :));\n\nfprintf('\\nProgram paused. Press enter to continue.\\n');\npause;\n\n\n\n%% =========== Part 7: Learning Curve for Polynomial Regression =============\n% Now, you will get to experiment with polynomial regression with multiple\n% values of lambda. The code below runs polynomial regression with \n% lambda = 0. You should try running the code with different values of\n% lambda to see how the fit and learning curve change.\n%\n\nlambda = 0;\n[theta] = trainLinearReg(X_poly, y, lambda);\n\n% Plot training data and fit\nfigure(1);\nplot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);\nplotFit(min(X), max(X), mu, sigma, theta, p);\nxlabel('Change in water level (x)');\nylabel('Water flowing out of the dam (y)');\ntitle (sprintf('Polynomial Regression Fit (lambda = %f)', lambda));\n\nfigure(2);\n[error_train, error_val] = ...\n learningCurve(X_poly, y, X_poly_val, yval, lambda);\nplot(1:m, error_train, 1:m, error_val);\n\ntitle(sprintf('Polynomial Regression Learning Curve (lambda = %f)', lambda));\nxlabel('Number of training examples')\nylabel('Error')\naxis([0 13 0 100])\nlegend('Train', 'Cross Validation')\n\nfprintf('Polynomial Regression (lambda = %f)\\n\\n', lambda);\nfprintf('# Training Examples\\tTrain Error\\tCross Validation Error\\n');\nfor i = 1:m\n fprintf(' \\t%d\\t\\t%f\\t%f\\n', i, error_train(i), error_val(i));\nend\n\nfprintf('Program paused. Press enter to continue.\\n');\n% pause;\n\n%% =========== Part 8: Validation for Selecting Lambda =============\n% You will now implement validationCurve to test various values of \n% lambda on a validation set. You will then use this to select the\n% \"best\" lambda value.\n%\n\n[lambda_vec, error_train, error_val] = ...\n validationCurve(X_poly, y, X_poly_val, yval);\n\nclose all;\nplot(lambda_vec, error_train, lambda_vec, error_val);\nlegend('Train', 'Cross Validation');\nxlabel('lambda');\nylabel('Error');\n\nfprintf('lambda\\t\\tTrain Error\\tValidation Error\\n');\nfor i = 1:length(lambda_vec)\n fprintf(' %f\\t%f\\t%f\\n', ...\n lambda_vec(i), error_train(i), error_val(i));\nend\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n", "meta": {"author": "schneems", "repo": "Octave", "sha": "411e8794574abb3fb042e178bf95861dfcee3b04", "save_path": "github-repos/MATLAB/schneems-Octave", "path": "github-repos/MATLAB/schneems-Octave/Octave-411e8794574abb3fb042e178bf95861dfcee3b04/mlclass-ex5/mlclass-ex5/ex5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.6977176426915763}} {"text": "function snowfall_display ( )\n\n%*****************************************************************************80\n%\n%% SNOWFALL_DISPLAY plots yearly snowfall data side by side.\n%\n% Discussion:\n%\n% The file \"snowfall.txt\" contains snowfall records.\n% Each line contains the year, the snowfall in inches for 8 months, and \n% the total.\n%\n% We want to plot the yearly snowfall curves for 2000 through 2010,\n% side by side in a 3D plot.\n%\n% We can use PLOT3(X,Y,Z) to plot a single 3D curve.\n%\n% We can use HOLD ON / HOLD OFF to force multiple 3D curves to appear\n% together.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 November 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SNOWFALL_DISPLAY\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Demonstrate how to display several curves side by side.\\n' );\n fprintf ( 1, ' Here, each curve represents snowfall over a given year.\\n' );\n%\n% Load all the snowfall data.\n%\n data = load ( 'snowfall.txt' );\n%\n% Column 1 contains the years.\n%\n years = data ( :, 1 );\n offset = years(1) - 1;\n%\n% Columns 2 through 9 are snowfall amounts.\n%\n snow = data ( :, 2:9);\n%\n% Column 10 is the snowfall total.\n%\n total = data ( :, 10 );\n%\n% Create figure #1 and clear it.\n%\n figure ( 1 )\n clf\n%\n% Call HOLD ON so multiple curves share one image.\n%\n% Call PLOT3 to draw each snowfall curve.\n% \n hold on\n for year = 2000 : 2010\n x(1:8) = year;\n y(1:8) = ( 1 : 8 );\n z(1:8) = snow(year-offset,1:8);\n plot3 ( x, y, z, 'Linewidth', 3 );\n end\n%\n% Annotate the plot.\n%\n grid on\n xlabel ( 'Year' );\n ylabel ( 'Month' );\n set ( gca, 'yTick', 1 : 8 );\n set ( gca, 'yTickLabel', { 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May' } );\n zlabel ( 'Inches of Snow' );\n title ( 'Michigan Tech Snowfall Records', 'Fontsize', 16 );\n%\n% Set the 3D viewing angles in degrees.\n%\n azimuth = 45.0;\n elevation = 35.0;\n view ( azimuth, elevation );\n%\n% Call HOLD OFF because we are done concatenating plots.\n%\n hold off\n%\n% Save a copy of the plot as a PNG file.\n%\n filename = 'snowfall.png';\n print ( '-dpng', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' PNG image saved as \"%s\"\\n', filename );\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/side_by_side_display/snowfall_display.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.8633916117313211, "lm_q1q2_score": 0.6976784618780589}} {"text": "function cordic_test001 ( )\n\n%*****************************************************************************80\n%\n%% TEST001 demonstrates the use of COSSIN_CORDIC.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 June 2007\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST001:\\n' );\n fprintf ( 1, ' COSSIN_CORDIC computes the cosine and sine of an angle\\n' );\n fprintf ( 1, ' using the CORDIC algorithm.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A N Cos(A) Cos(A) Difference\\n' );\n fprintf ( 1, ' Tabulated CORDIC\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, a, c1 ] = cos_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, '\\n' );\n \n for n = 0 : 5 : 25\n \n v = cossin_cordic ( a, n );\n c2 = v(1);\n d = c1 - c2;\n\n fprintf ( 1, ' %12f %4d %16.8f %16.8f %9e\\n', a, n, c1, c2, d );\n \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/cordic/cordic_test001.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.6976784601525653}} {"text": "function [ a, b ] = p23_lim ( dim_num )\n\n%*****************************************************************************80\n%\n%% P23_LIM returns the integration limits for problem 23.\n%\n% Discussion:\n%\n% Because the integration region is the interior of the unit simplex,\n% the integration limits simply specify the limits of a box containing \n% the integration region.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 March 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the dimension of the argument.\n%\n% Output, real A(DIM_NUM), B(DIM_NUM), the lower and upper\n% limits of integration.\n%\n a(1:dim_num) = 0.0;\n b(1:dim_num) = 1.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/quadrature_test/p23_lim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.6976784482157147}} {"text": "% Demo script on various ways to create an ellipse.\n%\n% output = create_ellipse_demo(input)\n%\n% Example\n% create_ellipse_demo\n%\n% See also\n%\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% INRAE - BIA Research Unit - BIBS Platform (Nantes)\n% Created: 2022-09-09, using Matlab 9.12.0.1884302 (R2022a)\n% Copyright 2022 INRAE.\n\n\n%% Use explicit representation\n\ncenter = [50 50];\nradii = [40 20];\ntheta = 30;\nelli0 = [center radii theta];\n\nfigure; hold on; axis square; axis([0 100 0 100]);\ndrawEllipse(elli0, 'lineWidth', 2, 'color', 'b');\n\n\n%% Fit an ellipse to a set of points\n\n% choose several points on the ellipse, and add some noise\nnPoints = 100;\nti = rand(nPoints, 1) * 2 * pi;\npts = ellipsePoint(elli0, ti) + randn(nPoints, 2) * 2;\n\n% fit the ellipse to the set of points\nelli = fitEllipse(pts);\n\n% display points and fit result\nfigure; hold on; axis square; axis([0 100 0 100]);\ndrawPoint(pts, 'linewidth', 1, 'color', 'b');\ndrawEllipse(elli, 'lineWidth', 2, 'color', 'm');\n\n\n%% Equivalent ellipse from a set of points\n\n% generate random points within the ellipse, \n% with a density equal to 1 (1 point per unit square on average)\nnPoints = round(ellipseArea(elli));\npts0 = zeros(nPoints, 2);\nfor iPoint = 1:nPoints\n while true\n pt = rand([1 2]) * 100;\n if isPointInEllipse(pt, elli0)\n pts(iPoint,:) = pt;\n break;\n end\n end\nend\n\n% computes equivalent ellipse\nelli = equivalentEllipse(pts);\n\n% display result\nfigure; hold on; axis square; axis([0 100 0 100]);\ndrawPoint(pts, 'b.');\ndrawEllipse(elli, 'lineWidth', 2, 'color', 'm');\ndrawEllipseAxes(elli, 'lineWidth', 2, 'color', 'm');\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/demos/geom2d/create_ellipse_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.697678446490221}} {"text": "%{\n Tests the extended \"analysis\" form of basis pursuit de-noising\n\n min_1 alpha*||W_1 x||_1 + beta*|| W_2 x ||_1\ns.t.\n || A(x) - b || <= eps\n\nThe solvers solve a regularized version\n\nsee also test_sBP.m and test_sBPDN.m and test_sBPDN_W.m\n\n%}\n\n% Before running this, please add the TFOCS base directory to your path\nmyAwgn = @(x,snr) x + ...\n 10^( (10*log10(sum(abs(x(:)).^2)/length(x(:))) - snr)/20 )*randn(size(x));\n\n% Try to load the problem from disk\nfileName = fullfile('reference_solutions','basispursuit_WW_problem1_smoothed_noisy');\nrandn('state',34324);\nrand('state',34324);\n\nN = 512;\nM = round(N/2);\nK = round(M/5);\n\nA = randn(M,N);\nx = zeros(N,1);\n\n% introduce a sparsifying transform \"W\"\nd = round(4*N); % redundant\nWf = @(x) dct(x,d); % zero-padded DCT\ndownsample = @(x) x(1:N,:);\nWt = @(y) downsample( idct(y) ); % transpose of W\nW = Wf(eye(N)); % make an explicit matrix for CVX\n\n% and add another transform:\nd2 = round(2*N);\nW2 = randn(d2,N);\nif exist([fileName,'.mat'],'file')\n load(fileName);\n fprintf('Loaded problem from %s\\n', fileName );\nelse\n \n % Generate a new problem\n\n alpha = 1;\n beta = 2;\n \n % the signal x consists of several pure tones at random frequencies\n for k = 1:K\n x = x + randn()*sin( rand()*pi*(1:N) + 2*pi*rand() ).';\n end\n\n\n b_original = A*x;\n snr = 40; % SNR in dB\n b = myAwgn(b_original,snr);\n EPS = norm(b-b_original);\n x_original = x;\n \n mu = .01*norm(Wf(x),Inf);\n x0 = zeros(N,1);\n\n % get reference via CVX\n tic\n cvx_begin\n cvx_precision high\n variable xcvx(N,1)\n minimize alpha*norm(W*xcvx,1) + beta*norm(W2*xcvx,1) + ...\n mu/2*sum_square(xcvx-x0)\n subject to\n norm(A*xcvx - b ) <= EPS\n cvx_end\n time_IPM = toc;\n x_ref = xcvx; \n objF = @(x)alpha*norm(W*x,1) +beta*norm(W2*x,1)+ mu/2*norm(x-x0).^2;\n obj_ref = objF(x_ref);\n \n save(fileName,'x_ref','b','x_original','mu',...\n 'EPS','b_original','obj_ref','x0','time_IPM','snr',...\n 'd','d2','alpha','beta');\n fprintf('Saved data to file %s\\n', fileName);\n \nend\n\n\n[M,N] = size(A);\nnorm_x_ref = norm(x_ref);\nnorm_x_orig = norm(x_original);\ner_ref = @(x) norm(x-x_ref)/norm_x_ref;\ner_signal = @(x) norm(x-x_original)/norm_x_orig;\nresid = @(x) norm(A*x-b)/norm(b); % change if b is noisy\n\nfprintf('\\tA is %d x %d\\n', M, N );\nfprintf('\\tl1-norm solution and original signal differ by %.2e (mu = %.2e)\\n', ...\n norm(x_ref - x_original)/norm(x_original),mu );\n\n%% Call the TFOCS solver\nobjF = @(x)alpha*norm(W*x,1) +beta*norm(W2*x,1)+ mu/2*norm(x-x0).^2;\ninfeasF = @(x)norm(A*x-b) - EPS;\ner = er_ref; % error with reference solution (from IPM)\nopts = [];\nopts.errFcn = { @(f,dual,primal) er(primal), ...\n @(f,dual,primal) obj_ref - f, ...\n @(f,dual,primal) infeasF(primal) }; \nopts.maxIts = 2000;\nopts.tol = 1e-10;\n% opts.normA2 = norm(A*A');\n% opts.normW2 = norm(W'*W);\nz0 = []; % we don't have a good guess for the dual\ntic;\n[ x, out, optsOut ] = solver_sBPDN_WW( A, alpha,W,beta,W2,b, EPS, mu, x0, z0, opts );\ntime_TFOCS = toc;\nfprintf('x is sub-optimal by %.2e, and infeasible by %.2e\\n',...\n objF(x) - obj_ref, infeasF(x) );\n\nfprintf('Solution has %d nonzeros. Error vs. IPM solution is %.2e\\n',...\n nnz(x), er(x) );\n\n% Check that we are within allowable bounds\nif out.err(end,1) < 1e-3\n disp('Everything is working');\nelse\n error('Failed the test');\nend\n\n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/examples/smallscale/test_sBPDN_WW.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.6976768991663633}} {"text": "% This is material illustrating the methods from the book\n% Financial Modelling - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors: Joerg Kienitz\n% Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n%-----------------------------------------------------------------------\n% This script demonstrates the use of function LINPROG on the basis of\n% the C-VaR portfolio optimization problen given in:\n% Uryasev, Rockafellar: Optimization of Conditional Value-at-Risk(1999)\n\nclear\nclose all\nclc\nwarning 'off'\n\ntic\n\n% load matrix data \n% of annualized linear stock returns\nload 'LinRetMat'\n\n% M: number of samples\n% N: number of assets\n[M,N] = size(data);\n% sample mean\nmu = mean(data)';\n\n% confidence level\nbeta = 0.99;\n\n% number portfolios\nNumPorts = 50;\n% target returns\nRstar = min(mu):(max(mu)-min(mu))/(NumPorts-1):max(mu);\n% objective function vector\nf = objfCVaR(beta, M, N);\n% constraints matrices\n[A, b, Aeq, beq, lb, ub] = constCVaR(data, mu, Rstar(1));\n\nCVaR = zeros(NumPorts,1);\nweights = zeros(N,NumPorts);\n\nfor i = 1:NumPorts\n beq(1) = -Rstar(i);\n [optimvar, CVaR(i)] = linprog(f, A, b, Aeq, beq, lb, ub);\n weights(:,i) = optimvar(1:N);\nend\n\ntoc\nwarning 'on'\n\n\n% Create figure\nfigure1 = figure('Color',[1 1 1]);\ncolormap('gray');\n\n% plot efficient frontier\nplot(CVaR,Rstar,'k','LineWidth',1.5)\nlegend('Mean-CVaR Frontier','Location','NorthWest')\nset(gca,'xlim',[0 CVaR(end)],'ylim',[0 Rstar(end)])\ntitle('Mean-CVaR Frontier','FontSize',17)\nxlabel('$\\beta$-CVaR','Interpreter','latex','FontName','Helvetia','FontSize',16)\nylabel('$\\mu$','Interpreter','latex','FontName','Helvetia','FontSize',16,'Rotation',0)\nticks = get(gca,'YTick');\nset(gca,'YTickLabel',[num2str(ticks'*100),repmat('%',length(ticks),1)])\nticks = get(gca,'XTick');\nset(gca,'XTickLabel',[num2str(ticks'*100),repmat('%',length(ticks),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/38325-matlab-basics/Matlab Files Ch.11/testSrciptLinprogCVaR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.6976768844972421}} {"text": "function Cmatrix = correlation_3d_to_2d(C)\n% Turn an k x k x n matrix of correlations into a 2-d flat matrix\n% \n% Cmatrix = correlation_3d_to_2d(C)\n%\n% C = [k x k x n], each [k x k] matrix is inter-variable correlation\n% matrix, one correlation matrix for each of n replicates.\n\n% get data for prediction\n%-----------------------------------\n\n[j, k, n] = size(C);\n\nif j ~= k, error('Not a series of correlation matrices'); end\n\nE = eye(j);\n\nnout = j * (j - 1) ./ 2;\nCmatrix = zeros(n, nout);\n\nfor i = 1:n\n \n Cmatrix(i, :) = squareform(C(:, :, i) - E);\n \nend\n\nend\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Data_processing_tools/correlation_3d_to_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772351648676, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.6976768834394435}} {"text": "function cg_rc_test02 ( )\n\n%*****************************************************************************80\n%\n%% CG_RC_TEST02 tests CG_RC with the Wathen matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 January 2013\n%\n% Author:\n%\n% John Burkardt\n%\n n = 79;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CG_RC_TEST02\\n' );\n fprintf ( 1, ' Use CG_RC to solve a linear system\\n' );\n fprintf ( 1, ' involving the Wathen matrix.\\n' );\n\n nx = 5;\n ny = 4;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' NX = %d\\n', nx );\n fprintf ( 1, ' NY = %d\\n', ny );\n fprintf ( 1, ' N = %d\\n', n );\n\n a = wathen ( nx, ny, n );\n\n seed = 123456789;\n [ x_exact, seed ] = r8vec_uniform_01 ( n, seed );\n\n size ( x_exact )\n size ( a )\n b(1:n) = a(1:n,1:n) * x_exact(1:n);\n\n x = zeros ( n, 1 );\n%\n% Parameters we need for the stopping test.\n%\n it = 0;\n it_max = 30;\n tol = 1.0E-05;\n bnrm2 = norm ( b(1:n) );\n%\n% Set parameters for CG_RC.\n%\n r = zeros ( n, 1 );\n z = zeros ( n, 1 );\n p = zeros ( n, 1 );\n q = zeros ( n, 1 );\n job = 1;\n%\n% Repeatedly call CG_RC, and on return, do what JOB tells you.\n%\n while ( 1 )\n\n [ x, r, z, p, q, job ] = cg_rc ( n, b, x, r, z, p, q, job );\n%\n% Compute q = A * p.\n%\n if ( job == 1 )\n\n q = a * p;\n%\n% Solve M * z = r;\n%\n elseif ( job == 2 )\n\n for i = 1 : n\n z(i) = r(i) / a(i,i);\n end\n%\n% Compute r = r - A * x.\n%\n elseif ( job == 3 )\n\n r = r - a * x;\n%\n% Stopping test.\n%\n elseif ( job == 4 )\n\n rnrm2 = norm ( r );\n\n if ( bnrm2 == 0.0 )\n if ( rnrm2 <= tol )\n break\n end\n else\n if ( rnrm2 <= tol * bnrm2 )\n break\n end\n end\n\n it = it + 1;\n\n if ( it_max <= it )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Iteration limit exceeded.\\n' );\n fprintf ( 1, ' Terminating early.\\n' );\n break\n end\n\n end\n\n job = 2;\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of iterations was %d\\n', it );\n fprintf ( 1, ' Estimated error is %g\\n', rnrm2 );\n err = max ( abs ( x_exact(1:n) - x(1:n) ) );\n fprintf ( 1, ' Loo error is %g\\n', err );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I X(I) X_EXACT(I) B(I)\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %4d %14f %14f %14f\\n', ...\n i, x(i), x_exact(i), b(i) );\n end\n\n return\n end\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/cg_rc/cg_rc_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.826711791935942, "lm_q1q2_score": 0.6976580454216567}} {"text": "function suborder = lyness_suborder ( rule, suborder_num )\n\n%*****************************************************************************80\n%\n%% LYNESS_SUBORDER returns the suborders for a Lyness rule.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 September 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% James Lyness, Dennis Jespersen,\n% Moderate Degree Symmetric Quadrature Rules for the Triangle,\n% Journal of the Institute of Mathematics and its Applications,\n% Volume 15, Number 1, February 1975, pages 19-32.\n%\n% Parameters:\n%\n% Input, integer RULE, the index of the rule.\n%\n% Input, integer SUBORDER_NUM, the number of suborders\n% of the rule.\n%\n% Output, integer SUBORDER(SUBORDER_NUM), the suborders\n% of the rule.\n%\n if ( rule == 0 )\n suborder = [ 1 ]';\n elseif ( rule == 1 )\n suborder = [ 3 ]';\n elseif ( rule == 2 )\n suborder = [ 1, 3 ]';\n elseif ( rule == 3 )\n suborder = [ 1, 3 ]';\n elseif ( rule == 4 )\n suborder = [ 1, 3, 3 ]';\n elseif ( rule == 5 )\n suborder = [ 3, 3 ]';\n elseif ( rule == 6 )\n suborder = [ 1, 3, 6 ]';\n elseif ( rule == 7 )\n suborder = [ 3, 3, 3 ]';\n elseif ( rule == 8 )\n suborder = [ 1, 3, 3 ]';\n elseif ( rule == 9 )\n suborder = [ 1, 3, 3, 3 ]';\n elseif ( rule == 10 )\n suborder = [ 3, 3, 6 ]';\n elseif ( rule == 11 )\n suborder = [ 1, 3, 3, 3, 6 ]';\n elseif ( rule == 12 )\n suborder = [ 1, 3, 3, 6 ]';\n elseif ( rule == 13 )\n suborder = [ 1, 3, 3, 6 ]';\n elseif ( rule == 14 )\n suborder = [ 1, 3, 3, 3, 6 ]';\n elseif ( rule == 15 )\n suborder = [ 1, 3, 3, 3, 6 ]';\n elseif ( rule == 16 )\n suborder = [ 3, 3, 3, 3, 3, 6 ]';\n elseif ( rule == 17 )\n suborder = [ 1, 3, 3, 3, 6 ]';\n elseif ( rule == 18 )\n suborder = [ 1, 3, 3, 3, 3, 6 ]';\n elseif ( rule == 19 )\n suborder = [ 1, 3, 3, 3, 3, 3, 6 ]';\n elseif ( rule == 20 )\n suborder = [ 3, 3, 3, 3, 3, 6, 6 ]';\n elseif ( rule == 21 )\n suborder = [ 1, 3, 3, 3, 3, 3, 6, 6 ]';\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LYNESS_SUBORDER - Fatal error!\\n' );\n fprintf ( 1, ' Illegal RULE = %d\\n', rule );\n error ( 'LYNESS_SUBORDER - 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/triangle_lyness_rule/lyness_suborder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.697658042533223}} {"text": "% Convert an adjacency matrix of a general graph to the adjacency matrix of\n% a simple graph (symmetric, no loops, no double edges, no weights)\n%\n% INPUTS: adjacency matrix, nxn\n% OUTPUTs: adjacency matrix (nxn) of the corresponding simple graph\n%\n% Other routines used: symmetrize.m\n% GB: last updated, Sep 6 2014\n\nfunction adj=adj2simple(adj)\n\nadj=adj>0; % make all edges weight 1\nadj = symmetrize(adj);\nadj = adj - diag(diag(adj)); % clear the diagonal (selfloops)", "meta": {"author": "aeolianine", "repo": "octave-networks-toolbox", "sha": "e70f79eb62a54ef96934d900830f9177caf732c9", "save_path": "github-repos/MATLAB/aeolianine-octave-networks-toolbox", "path": "github-repos/MATLAB/aeolianine-octave-networks-toolbox/octave-networks-toolbox-e70f79eb62a54ef96934d900830f9177caf732c9/adj2simple.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.8267118004748678, "lm_q1q2_score": 0.6976580396447891}} {"text": "function hammersley_test01 ( )\n\n%*****************************************************************************80\n%\n%% TEST01 tests I4_TO_HAMMERSLEY_SEQUENCE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 May 2008\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST01\\n' );\n fprintf ( 1, ' I4_TO_HAMMERSLEY_SEQUENCE computes N elements of\\n' );\n fprintf ( 1, ' a Hammersley sequence on a single call.\\n' );\n fprintf ( 1, ' All arguments are specified explicitly.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' In this example, we compute the first 10 elements\\n' );\n fprintf ( 1, ' of a \"classical\" Hammersley sequence, and then\\n' );\n fprintf ( 1, ' the \"last\" 10 elements.\\n' );\n\n nmax = 1000;\n\n dim_num = 4;\n n = 10;\n step = 1;\n seed(1:dim_num) = 0;\n leap(1:dim_num) = 1;\n base(1) = -nmax;\n for i = 2 : dim_num\n base(i) = prime ( i - 1 );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' DIM_NUM = %12d\\n', dim_num );\n fprintf ( 1, ' N = %12d\\n', n );\n fprintf ( 1, ' STEP = %12d\\n', step );\n i4vec_transpose_print ( dim_num, seed, ' SEED = ' );\n i4vec_transpose_print ( dim_num, leap, ' LEAP = ' );\n i4vec_transpose_print ( dim_num, base, ' BASE = ' );\n\n r = i4_to_hammersley_sequence ( dim_num, n, step, seed, leap, base );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' STEP Hammersley\\n' );\n fprintf ( 1, '\\n' );\n for j = 1 : n\n fprintf ( 1, ' %6d ', step+j-1 );\n for i = 1 : dim_num\n fprintf ( 1, '%12f ', r(i,j) );\n end\n fprintf ( 1, '\\n' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' We can jump ahead in the sequence by changing STEP.\\n' );\n\n step = nmax - n + 1;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' STEP = %12d\\n', step );\n\n r = i4_to_hammersley_sequence ( dim_num, n, step, seed, leap, base );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' STEP Hammersley\\n' );\n fprintf ( 1, '\\n' );\n for j = 1 : n\n fprintf ( 1, ' %6d ', step+j-1 );\n for i = 1 : dim_num\n fprintf ( 1, '%12f ', r(i,j) );\n end\n fprintf ( 1, '\\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/hammersley/hammersley_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.6976580286572162}} {"text": "\n% GP_COV_SE - Squared exponential covariance function for Gaussian\n% processes.\n%\n% [K, DK_LOGTHETA, DK_X2] = GP_COV_SE(X1, X2, LOGTHETA)\n\n% Last modified 2010-10-06\n% Copyright (c) Jaakko Luttinen (jaakko.luttinen@tkk.fi)\n\nfunction [K, dK_logtheta, dK_x2] = gp_cov_se(x1, x2, logtheta)\n\n% 2-norm distances\nif ~isempty(x2)\n % Distances for covariances\n n1 = cols(x1);\n n2 = cols(x2);\n D = zeros(n1,n2);\n for i=1:n1\n for j=1:n2\n D(i,j) = norm(x1(:,i) - x2(:,j));\n end\n end\nelse\n % Distances for variances\n n = rows(x1);\n D = zeros(n,1);\nend\n \n\n% Covariance matrix\nD2 = D.^2;\nK = exp(logtheta(1)) * exp(-0.5*exp(-2*logtheta(2))*D2);\n\n% Gradient for hyperparameters\nif nargout >= 2\n dK_logtheta = zeros([size(D), 2]);\n dK_logtheta(:,:,1) = K;\n dK_logtheta(:,:,2) = K .* (-0.5*D2*exp(-2*logtheta(2))) .* (-2);\nend\n\n% Gradients for inputs x2\nif nargout >= 3\n if isempty(x2)\n error('Can''t calculate gradient: x2 not given');\n end\n d = rows(x2); % dimensionality of inputs\n m = cols(x1); % number of other inputs\n n = cols(x2); % number of inputs\n dK_x2 = zeros([d,m,n]);\n for i=1:m\n for j=1:n\n dK_x2(:,i,j) = K(i,j) * (-0.5*exp(-2*logtheta(2))) * 2*(x2(:,j)-x1(:,i));\n end\n end\nend\n\n\n\nfunction [K, dK] = gpK_sqexp(D, p1, p2)\n\n% [K, dK] = gpK_sqexp(D, p1, p2)\n%\n% Squared exponential covariance function for GP.\n%\n% p1 is the scale\n% p2 is the length\n%\nK = p1^2*exp(-0.5*D.^2/(p2^2));\n\nif nargout >= 2\n dK = zeros([size(D), 2]);\n dK(:,:,1) = K .* 2 / p1;\n dK(:,:,2) = K .* (-0.5*D.^2) .* (-2*p2^(-3));\nend\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/gp/gp_cov_se_backup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6975859966032271}} {"text": "function g = p10_g ( n, x )\n\n%*****************************************************************************80\n%\n%% P10_G evaluates the gradient for problem 10.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 October 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the values of the variables.\n%\n% Output, real G(N), the gradient of the objective function.\n%\n g = zeros ( n, 1 );\n\n g(1) = 2.0 * x(1) - 2000000.0 + 2.0 * x(1) * x(2) * x(2) - 4.0 * x(2);\n\n g(2) = 2.0 * x(2) - 0.000004 + 2.0 * x(1)^2 * x(2) - 4.0 * x(1);\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_opt/p10_g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.6975859890034822}} {"text": "function [pass, u1, u2, info1, info2] = test_scalarODEdamping(pref)\n% A nonlinear CHEBOP test. This test tests a scalar ODE, where no breakpoints\n% occur. It solves the problem using chebcolloc1, chebcolloc2 and ultraS\n% discretizations. The problem solved requires damping for the Newton iteration\n% to converge.\n%\n% Asgeir Birkisson, May 2014.\n\n%% Setup\ndom = [0 pi];\nif ( nargin == 0 )\n pref = cheboppref;\nend\n\nN = chebop(@(x,u) .05*diff(u,2) + cos(5*x).*sin(u), dom);\nN.lbc = @(u) u - 2; \nN.rbc = @(u) u - 3;\nrhs = 0;\n\npref.bvpTol = 1e-10;\n\n% Try different discretizations:\n\n%% Start with chebcolloc2\npref.discretization = @chebcolloc2;\npref.bvpTol = 1e-13;\n[u1, info1] = solvebvp(N, rhs, pref);\nerr(1) = norm(N(u1));\n\n%% Change to chebcolloc1\npref.discretization = @chebcolloc1;\n[u2, info2] = solvebvp(N, rhs, pref);\nerr(2) = norm(N(u2));\n\n%% Change to ultraS\npref.discretization = @ultraS;\npref.bvpTol = 1e-12;\n[u3, info3] = solvebvp(N, rhs, pref);\nerr(3) = norm(N(u3));\n\n%% Did we pass? \n% To pass, both residuals have to be small, but we should not expect u1 and u2\n% to be identical!\n\ntol = 1e-9;\npass = err < tol;\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/tests/chebop/test_scalarODE_damping.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.6975859851824404}} {"text": "function [Fs spec] = PTSpec2d(Y, F, psd)\n%% [Fs spec] = PTSpec2d(Y, F, psd) \n% computes standard fft on input data Y. F is sample frequency in Hz. \n\n% ----------------------------------------------------------------------------------\n% \"THE BEER-WARE LICENSE\" (Revision 42):\n% wrote this file. As long as you retain this notice you\n% can do whatever you want with this stuff. If we meet some day, and you think\n% this stuff is worth it, you can buy me a beer in return. -Brian White\n% ----------------------------------------------------------------------------------\n\nif psd\n % N = length(Y);\n % [psdx,Fs] = periodogram(Y,[], N-1, F*1000,'psd'); % power psd\n % [spec,Fs] = pspectrum(Y, F*1000, 'FrequencyResolution', 10);\n \n N = length(Y);\n Fs = ((F*1000)*(0:(N/2))/N);\n Y = Y.*hann(N)';\n Y = fft(Y); \n psdx = abs(Y).^2 / (F*1000*N); % (1/(F*N)) * abs(Y).^2 is exactly same as abs(Y).^2 / (F*N), to \n psdx(2:end-1) = 2*psdx(2:end-1);\n psdx = psdx(1:N/2+1); \n% % scale to dB\n spec = 10 * log10(psdx)';\nelse \n N = length(Y);\n Fs = ((F*1000)*(0:(N/2))/N);\n Y = Y.*hann(N)';\n Y = fft(Y); \n spec = abs(Y) / N; % (1/(F*N)) * abs(Y).^2 is exactly same as abs(Y).^2 / (F*N), to \n spec = spec(1:N/2+1)';\nend\n\nend\n", "meta": {"author": "bw1129", "repo": "PIDtoolbox", "sha": "0a6c2944ae728968f44467a629cc53b63db75dd7", "save_path": "github-repos/MATLAB/bw1129-PIDtoolbox", "path": "github-repos/MATLAB/bw1129-PIDtoolbox/PIDtoolbox-0a6c2944ae728968f44467a629cc53b63db75dd7/PTSpec2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6975772059850317}} {"text": "function [A,B] = kmo(X)\n%KMO Kaiser-Meyer-Olkin Measure of Sampling Adequacy.\n% Factor analysis can be used as a guide to how coherently a set of variables\n% relate to a hypothesized underlying dimension that they are all being used\n% to measure. External validity analysis assesses whether the scale that has\n% been constructed performs as theoretically expected in correlation with\n% other variables to which it is expected to be related.\n% There are some assumptions about the characteristics of factors that are\n% extracted and defined that are unobserved common dimensions that may be\n% listed to account for the correlations among observed variables. Sampling\n% adequacy predicts if data are likely to factor well, based on correlation\n% and partial correlation. Is used to assess which variables to drop from the\n% model because they are too multicollinear.\n% It has been suggested that inv(R) should be a near-diagonal matrix in order\n% to successfully fit a factor analysis model. To assess how close inv(R)\n% is to a diagonal matrix, Kaiser (1970) proposed a measure of sampling\n% adequacy, now called KMO (Kaiser-Meyer-Olkin) index. The common part, called\n% the image of a variable, is defined as that part which is predictable by\n% regressing each variable on all other variables.\n% The anti-image is the specific part of the variable that cannot be predicted.\n% Examining the anti-image of the correlation matrix. That is the negative of the\n% partial correlations, partialling out all other variables.\n% There is a KMO statistic for each individual variable and their sum is\n% the overall statistic. If it is not > 0.6 drop the indicator variables with\n% the lowest individual statistic value until the overall one rises above 0.6:\n% factors which is meritorious. The diagonal elements on the Anti-image \n% correlation matrix are the KMO individual statistics for each variable. A KMO\n% index <= 0.5 indicates the correlation matrix is not suitable for factor\n% analysis.\n%\n% Syntax: function kmo(X) \n% \n% Input:\n% X - Input matrix can be a data matrix (size n-data x p-variables)\n% Output(s):\n% - Kaiser-Meyer-Olkin Index.\n% - Degree of Common Variance Report (shared by a set of variables\n% and thus assesses the degree to which they measure a common\n% underlying factor).\n% optional(s):\n% - Anti-image Covariance Matrix.\n% - Anti-image Correlation Matrix\n%\n% Example: From the example given on the web page\n% http://www.ncl.ac.uk/iss/statistics/docs/factoranalysis.html\n% We are interested to calculate the Kaiser-Meyer-Olkin measure of sampling\n% adequacy in order to see if proceeds a satisfactory factor analysis to\n% investigate the reasons why customers buy a product such as a particular\n% brand of soft drink (e.g. coca cola). Several variables were identified\n% which influence customer to buy coca cola. Some of the variables identified\n% as being influential include availability of product (X1), cost of product\n% (X2), experience with product (X3), popularity of product (X4), prestige\n% attached to product (X5), quality of product (X6), quantity of product (X7),\n% and respectability of product (X8). From this, you designed a questionnaire\n% to solicit customers' view on a seven point scale, where 1 = not important\n% and 7 = very important. The results from your questionnaire are show on the\n% table below. Only the first twelve respondents (cases) are used in this\n% example. \n%\n% Table 1: Customer survey\n% --------------------------------------------------\n% X1 X2 X3 X4 X5 X6 X7 X8 \n% --------------------------------------------------\n% 4 1 4 5 2 3 6 7\n% 4 2 7 6 6 3 3 4\n% 6 4 3 4 2 5 7 7\n% 5 3 5 4 3 4 6 7\n% 5 2 4 5 2 5 5 6\n% 6 3 3 5 4 4 7 7\n% 6 2 4 4 4 3 4 5\n% 4 1 3 4 3 3 5 6\n% 5 3 4 3 4 3 6 6\n% 5 4 3 4 4 4 6 7\n% 6 2 4 4 4 3 7 5\n% 5 2 3 3 3 3 7 6 \n% --------------------------------------------------\n%\n% Data matrix must be:\n% X=[4 1 4 5 2 3 6 7;4 2 7 6 6 3 3 4;6 4 3 4 2 5 7 7;5 3 5 4 3 4 6 7;\n% 5 2 4 5 2 5 5 6;6 3 3 5 4 4 7 7;6 2 4 4 4 3 4 5;4 1 3 4 3 3 5 6;\n% 5 3 4 3 4 3 6 6;5 4 3 4 4 4 6 7;6 2 4 4 4 3 7 5;5 2 3 3 3 3 7 6];\n%\n% Calling on Matlab the function: \n% kmo(X)\n%\n% Answer is:\n%\n% Kaiser-Meyer-Olkin Measure of Sampling Adequacy: 0.4172\n% The KMO test yields a degree of common variance unacceptable (Don't Factor).\n%\n%\n% Created by A. Trujillo-Ortiz, R. Hernandez-Walls, A. Castro-Perez, \n% K. Barba-Rojo and A. Otero-Limon\n% Facultad de Ciencias Marinas\n% Universidad Autonoma de Baja California\n% Apdo. Postal 453\n% Ensenada, Baja California\n% Mexico.\n% atrujo@uabc.mx\n%\n% Copyright. October 10, 2006.\n%\n% To cite this file, this would be an appropriate format:\n% Trujillo-Ortiz, A., R. Hernandez-Walls, A. Castro-Perez, K. Barba-Rojo \n% and A. Otero-Limon (2006). kmo:Kaiser-Meyer-Olkin Measure of Sampling\n% Adequacy. A MATLAB file. [WWW document]. URL http://www.mathworks.com/\n% matlabcentral/fileexchange/loadFile.do?objectId=12736\n%\n% References:\n% Rencher, A. C. (2002), Methods of Multivariate Analysis. 2nd. ed.\n% New-Jersey:John Wiley & Sons. Chapter 13 (pp. 408-450).\n%\n\nerror(nargchk(1,1,nargin));\nmsg = nargoutchk(1, 2, nargout);\n\nX = corrcoef(X);\n\niX = inv(X);\nS2 = diag(diag((iX.^-1)));\nAIS = S2*iX*S2; %anti-image covariance matrix\nIS = X+AIS-2*S2; %image covariance matrix\nDai = diag(diag(sqrt(AIS)));\nIR = inv(Dai)*IS*inv(Dai); %image correlation matrix\nAIR = inv(Dai)*AIS*inv(Dai); %anti-image correlation matrix\na = sum((AIR - diag(diag(AIR))).^2);\nAA = sum(a);\nb = sum((X - eye(size(X))).^2);\nBB = sum(b);\nMSA = b./(b+a); %measures of sampling adequacy\nAIR = AIR-eye(size(AIR))+diag(MSA);\n%Examine the anti-image of the correlation matrix. That is the negative of the partial correlations,\n%partialling out all other variables.\nN = BB;\nD = AA+BB;\nkmo = N/D;\n\ndisp(' ')\nfprintf('Kaiser-Meyer-Olkin Measure of Sampling Adequacy: %3.4f\\n', kmo);\nif (kmo >= 0.00 && kmo < 0.50);\n disp('The KMO test yields a degree of common variance unacceptable (Don''t Factor).')\nelseif (kmo >= 0.50 && kmo < 0.60);\n disp('The KMO test yields a degree of common variance miserable.')\nelseif (kmo >= 0.60 && kmo < 0.70);\n disp('The KMO test yields a degree of common variance mediocre.')\nelseif (kmo >= 0.70 && kmo < 0.80);\n disp('The KMO test yields a degree of common variance middling.')\nelseif (kmo >= 0.80 && kmo < 0.90);\n disp('The KMO test yields a degree of common variance meritorious.')\nelse (kmo >= 0.90 && kmo <= 1.00);\n disp('The KMO test yields a degree of common variance marvelous.')\nend\n\nif nargout == 1;\n disp(' ')\n disp('A = Anti-image covariance matrix.'); \n A = AIS;\nelseif nargout > 1;\n disp(' ')\n disp('A = Anti-image covariance matrix.');\n A = AIS;\n disp('B = Anti-image correlation matrix.');\n B = AIR;\nend\n\nreturn,", "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/12736-kmo/kmo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6975772023958018}} {"text": "% INVWISHRND - Inverse Wishart Distribution - Random Matrix Value\n% Copyright (c) 1998, Harvard University. Full copyright in the file Copyright\n%\n% [ IW ] = invwishrnd(S,d) \n%\n% S = p x p symmetric, postitive definite \"scale\" matrix \n% d = \"degrees of freedom\" parameter (integer)\n% = \"precision\" parameter (d may be non-integer)\n%\n% IW = random matrix from the inverse Wishart distribution\n%\n% Note:\n% Different sources use different parameterizations.\n% This routine uses that of Press and Shigemasu (1989):\n% density (IW) is proportional to \n% exp[-.5*trace(S*inv(IW))] / [det(IW) ^ (d/2)].\n%\n% With this density definition:\n% mean of IW = S/(d-2p-2) for d>2p+2,\n% mode of IW = S/d.\n%\n% See also: INVWISHIRND, WISHRND\n\nfunction [IW] = invwishrnd(S,d) \n\n[p,p2] = size(S) ;\n\nW = wishrnd(inv(S),d-p-1) ;\n\nIW = inv(W) ;\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/198-mcmc/mcmc/invwishrnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6975771956841513}} {"text": "function y = FourierShift2D(x, delta)\n%\n% y = FourierShift(x, [delta_x delta_y])\n%\n% Shifts x by delta cyclically. Uses the fourier shift theorem.\n%\n% Real inputs should give real outputs.\n%\n% By Tim Hutt, 26/03/2009\n% Small fix thanks to Brian Krause, 11/02/2010\n\n% The size of the matrix.\n[N, M] = size(x);\n\n% FFT of our possibly padded input signal.\nX = fft2(x);\n\n% The mathsy bit. The floors take care of odd-length signals.\nx_shift = exp(-1i * 2 * pi * delta(1) * [0:floor(N/2)-1 floor(-N/2):-1]' / N);\ny_shift = exp(-1i * 2 * pi * delta(2) * [0:floor(M/2)-1 floor(-M/2):-1] / M);\n\n\n% Force conjugate symmetry. Otherwise this frequency component has no\n% corresponding negative frequency to cancel out its imaginary part.\nif mod(N, 2) == 0\n\tx_shift(N/2+1) = real(x_shift(N/2+1));\nend \nif mod(M, 2) == 0\n\ty_shift(M/2+1) = real(y_shift(M/2+1));\nend\n\n\nY = X .* (x_shift * y_shift);\n\n% Invert the FFT.\ny = ifft2(Y);\n\n% There should be no imaginary component (for real input\n% signals) but due to numerical effects some remnants remain.\nif isreal(x)\n y = real(y);\nend\n\nend", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/image_proc/FourierShift2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6975771938895363}} {"text": "function pass = test_sum( pref ) \n% Test with function cos(cos(lam)*sin(th))\n\n% Grab some preferences\nif ( nargin == 0 )\n pref = chebfunpref();\nend\ntol = 1e4*pref.techPrefs.chebfuneps;\n\n%% Integrate over r\n\n% Example 1\nf = ballfun(@(r,lam,th)r.*cos(lam).*sin(th), 'spherical');\ng = sum(f, 1);\nexact = spherefun(@(lam,th)cos(lam).*sin(th)/4);\npass(1) = norm(g-exact) < tol;\n\n% Example 2\nf = ballfun(@(r,lam,th)1, 'spherical');\ng = sum(f, 1);\nexact = spherefun(@(lam,th)1/3);\npass(2) = norm(g-exact) < tol;\n\n%% Integrate over lambda\n\n% Example 3\nf = ballfun(@(r,lam,th)(r.*sin(lam).*sin(th)).^2, 'spherical');\ng = sum(f, 2);\nexact = diskfun(@(th,r)pi*r.^2.*sin(th).^2,'polar');\npass(3) = norm(g-exact) < tol;\n\n%% Integrate over theta\n\n% Example 4\nf = ballfun(@(r,lam,th)r.*cos(lam).*sin(th), 'spherical');\ng = sum(f, 3);\nexact = diskfun(@(lam,r)r.*cos(lam)*pi/2,'polar');\npass(4) = norm(g-exact) < tol;\n\nif (nargout > 0)\n pass = all(pass(:));\nend\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/ballfun/test_sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.697577190300306}} {"text": "function [lp,dlp] = priorGaussMulti(mu,s2,x)\n\n% Multivariate Gaussian hyperparameter prior distribution.\n% Compute log-likelihood and its derivative or draw a random sample.\n% The prior distribution is parameterized as:\n%\n% p(x) = exp(-r2/2) / sqrt(det(2*pi*s2)) where r2(x) = (x-mu)'*inv(s2)*(x-mu),\n%\n% mu(Dx1) is the mean parameter, s2(Dx1) or s2(DxD) is the variance parameter\n% and x(DxN) contains query hyperparameters for prior evaluation.\n%\n% For more help on design of priors, try \"help priorDistributions\".\n%\n% Copyright (c) by Roman Garnett and Hannes Nickisch, 2014-09-12.\n%\n% See also PRIORDISTRIBUTIONS.M, PRIORGAUSS.M.\n\nif nargin<2, error('mu and s2 parameters need to be provided'), end\nif ndims(mu)~=2 || size(mu,2)~=1, error('mu needs to be (Dx1)'), end\nD = size(mu,1);\ns2_ok = ndims(s2)==2 && all(size(s2)==[D,1] | size(s2)==[D,D]);\nif ~s2_ok, error('s2 needs to be (DxD) or (Dx1)'), end\nif size(s2,2)==D % full multivariate case\n s = chol(s2)'; lds = sum(log(diag(s))); % lds = log(det(s2))/2\nelse % diagonal covariance\n s = sqrt(s2); lds = sum(log(s));\nend\nif nargin<3 % return a random sample\n lp = randn(D,1); % unit sample\n if size(s,2)==D, lp = s*lp+mu; else lp = s.*lp+mu; end % affine transformation\n return\nend\nif D==1 && size(x,1)>1 % both mu/s2 scalar => inflate\n D = size(x,1); mu = mu*ones(D,1); s = s*ones(D,1); lds = D*lds;\nend\nif ~(ndims(x)==2 && size(x,1)==D), error('x needs to be (Dxn)'), end\n\noN = ones(1,size(x,2));\nif size(s,2)==D\n xs = s\\(x-mu*oN); dlp = -s'\\xs;\nelse\n xs = (x-mu*oN)./(s*oN); dlp = -xs./(s*oN);\nend\nlp = -sum(xs.^2,1)/2 - D*log(2*pi)/2 - lds;", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/gpml/prior/priorGaussMulti.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.6975771894393104}} {"text": "function [Results,u_star2,t]=Arm_1DOF_LinearStateTransition_Fun(StartAngle,Stable,I,l_c)\n% this suggests an initial solution for the pendulium problem\n%Stable 1 hanging pendulium, -1 inverted\n%StartAngle given in degrees\n\n%system parameters\nm=1; %mass of plumb, kg\ng=9.806; %gravity, m/sec^2\n% I and l_c are now set by input\n\n% simumation parameters\nX_0=[StartAngle(1),0].'*pi/180; %intial value\nX_F=[0,0].'*pi/180; %final value\nt0=0;\ntf=1;\nT=linspace(t0,tf,1000);\nT_2=[T, T(end)+(0.0001:0.01:0.1)];\n\n% I*theta_ddot = -m*g*l_c*sin(theta)+u \n% regular pendulium\n% linearizing about theta=0 for now\nA = [0 1; -Stable*m*g*l_c/I, 0]; \nB=[0; 1/I];\n\n% W_c_fun=@(t) expm(A*t(n))*B*(B.')*expm(A.'*t(n));\n% Written as subroutine below\ntemp11= quad(@(timein) W_c_fun(timein,A,B,1,1),t0,tf);\ntemp21= quad(@(timein) W_c_fun(timein,A,B,2,1),t0,tf);\ntemp12= quad(@(timein) W_c_fun(timein,A,B,1,2),t0,tf);\ntemp22= quad(@(timein) W_c_fun(timein,A,B,2,2),t0,tf);\nW_c= [temp11, temp12; temp21, temp22];\n\nu_pre=-B.';\nu_post=(W_c\\(expm(tf*A)*X_0-X_F));\nu_star=zeros(size(T_2));\nfor alice=1:length(T)\nu_star(alice)=u_pre*expm(A.'*(tf-T(alice)))*u_post;\nend\n\nDynamics=@(t,x) [x(2); -Stable*(m*g*l_c/I)*sin(x(1))+...\n (sign(interp1(T_2,u_star,t,'pchip'))*min([abs(interp1(T_2,u_star,t,'pchip')),7]))/I];\n[t,Results]=ode45(Dynamics,T_2,X_0);\n% Apply saturation\nu_star2=sign(interp1(T_2,u_star,t,'pchip')).*...\n min(abs(interp1(T_2,u_star,t,'pchip')),7);\nend\n\nfunction temp = W_c_fun(t,A,B,WhichRow,WhichCol)\ntemp=zeros([1,length(t)]); \nfor n=1:length(t)\n temp1=expm(A*t(n))*B*(B.')*expm(A.'*t(n));\n temp(n)=temp1(WhichRow,WhichCol);\nend\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/28597-simmechanics-pendulum-used-for-control-optimization/Submission/Arm_1DOF_LinearStateTransition_Fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631688, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6975771840554653}} {"text": "function varargout = sumk(varargin)\n% SUMK Returns sum of k largest (eigen-)values.\n%\n% s = SUMK(X,k,w)\n%\n% For a vector X, SUMK returns the sum of the k largest elements.\n%\n% For a symmetric matrix X, SUMK returns the sum of the k largest eigen-values.\n%\n% A third argument can be used to generalize to weighted sum.\n% The weights have to be non-negative and non-increasing.\n%\n% See also SUMABSK\n\nif nargin == 1\n error('sumk needs at least two arguments');\nend\n\nswitch class(varargin{1})\n \n case 'double' % What is the numerical value of this argument (needed for displays etc)\n \n X = varargin{1};\n [n,m] = size(X);\n if (min(n,m) > 1 & ~issymmetric(X))\n error('sumk can only be applied on vectors and symmetric matrices');\n else\n k = min(length(X),varargin{2});\n w = ones(k,1);\n if nargin == 3\n w = varargin{3};\n if length(w)==1\n w = ones(k,1)*w; \n end\n end\n if min(n,m)==1\n sorted = sort(X,'descend');\n else\n sorted = sort(eig(X),'descend');\n end\n sorted = sorted(:);\n w = w(:);\n varargout{1} = sum(sorted(1:k).*w(1:k));\n end\n \n case 'sdpvar' % Overloaded operator for SDPVAR objects. Pass on args and save them.\n X = varargin{1};\n [n,m] = size(X);\n if nargin < 3\n w = 1;\n else\n w = varargin{3};\n if length(w)>1\n if any(diff(w)>0) || any(w<0)\n error('The weights have to be non-negative non-increasing')\n end\n end\n end\n if (min(n,m) > 1 & ~issymmetric(X))\n error('sumk can only be applied on vectors and symmetric matrices');\n else\n varargout{1} = yalmip('define',mfilename,varargin{:});\n end\n \n case 'char' % YALMIP send 'model' when it wants the epigraph or hypograph\n if isequal(varargin{1},'graph')\n t = varargin{2}; % Second arg is the extended operator variable\n X = varargin{3}; % Third arg and above are the args user used when defining t.\n k = min(varargin{4},length(X));\n if nargin == 5\n w = varargin{5};\n else\n w = 1;\n end \n [Model,Properties] = sumk_generator(X,k,t,w);\n varargout{1} = Model;\n varargout{2} = Properties;\n varargout{3} = X;\n else\n end\n otherwise\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/operators/sumk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6975354098229035}} {"text": "function M = makeSincMovie\n\n% Copyright 2008-2009 The MathWorks, Inc. \n\n% Make suitable X and Y matricies to plot the sinc function over\n[X, Y] = meshgrid(linspace(-3*pi, 3*pi, 50), linspace(-3*pi, 3*pi, 50));\n% From X & Y make the matrix R of radius\nR = sqrt(X.^2 + Y.^2);\n% Calculate the sinc function from R\nF = sin(R)./R;\n% Make an amplitude vector that represents the various amplitudes we will\n% movie the function over\nA = linspace(-1, 1, 30);\n% Iterate over each amplitude\nfor j = 1:numel(A) \n % Plot the surface with colouring defined by the function with no\n % amplitude modification\n surf(X, Y, A(j)*F, F);\n % Always use the same axis otherwise the movie will look funny\n axis([-10 10 -10 10 -1 1]);\n % Then turn off the axis - don't want tosee them in the movie. Also\n % remove the lines around each face of the surface\n axis off\n shading flat\n % Finally get this frame and the symmetric one so that when we show the\n % whole movie it ends at the same point it began\n M(j) = getframe; %#ok\n M(2*numel(A) - j) = M(j); %#ok\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/22732-matlab-in-physics-visualisation/Lecture1/makeSincMovie.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297781091839, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6975354077550991}} {"text": "function Ch4Ex1_main()\n%% SOS-based Policy Iteration for a car suspension systems\n% The function is tested in MATLAB R2014b\n% Copyright 2015 Yu Jiang\n% Contact Yu Jiang (yu.jiang@nyu.edu)\n\n% System requirements:\n% - MATLAB (Manually Tested in MATLAB R2014b)\n% - MATLAB Symbolic Toolbox\n% - SDPT3-4.0\n% - SISOTOOLS (free to download at http://www.cds.caltech.edu/sostools/)\n\n% You can download tools.zip and run setuptools.m in the folder.\n\nsyms x1 x2 x3 x4 real\nmb = 300; % kg\nmw = 60; % kg\nbs = 1000; % N/m/s\nks = 16000 ; % N/m\nkt = 190000; % N/m\nkn = 0.1*ks;\n\n% State matrices\nA = [ 0 1 0 0;\n [-ks -bs ks bs]/mb ; ...\n 0 0 0 1;\n [ks bs -ks-kt -bs]/mw];\nB = [ 0 0; 0 10000/mb ; 0 0 ; [kt -10000]/mw];\nB = B(:,2);\n\n% LQR feedback gains for the linearized system\n% Klqr = lqr(A,B,eye(4),1);\n% f(x)\nf = A*[x1;x2;x3;x4] + [0;-kn*(x1-x3)^3/mb;0;kn*(x1-x3)^3/mw];\n\n% Polynomial Weighting functions\nq0 = 100*x1^2+x2^2+x3^2+x4^2;\nrx = 1;%+(x1^2+x2^2+x3^2+x4^2);\nvars = [x1;x2;x3;x4];\n\n% Initialize the SOSp\nprog = sosprogram(vars);\n\n% The Lyapunov function V(x)\n[prog,V] = sospolyvar(prog,monomials([x1;x2;x3;x4],2:4),'wscoeff');\n\n% Objective of the SOSp\nmyObj = int(int(int(int(V,-.5,.5),-10,10),-.5,.5),-10,10);\n\n% Add Inequality constraint to assure V is positive definite\nprog = sosineq(prog,V-0.0001*(x1^2+x2^2+x3^2+x4^2));\n\n% Add Inequality constraint to assure stability and performance\nexpr = -[diff(V,x1) diff(V,x2) diff(V,x3) diff(V,x4)]*rx*f-rx*q0;\nprog = sosineq(prog,expr);\n\n% Solve the SOSp\nprog = sossolve(prog);\n\n% Obtain the Initial Lyapunov function\nV0 = sosgetsol(prog,V);\nV_old = V0;\n\n% Initializing the old contol policy\nu_prev = zeros(size(x1));\n\n% Iteration\nfor i=1:10\n clear prog V\n %------------------------------ SOSp Start ----------------------------\n prog = sosprogram(vars);\n [prog,V] = sospolyvar(prog,monomials([x1;x2;x3;x4],2:4),'wscoeff');\n prog = sosineq(prog,V_old - V);\n prog = sosineq(prog, V);\n u = -1/2*B'*[diff(V_old,x1) diff(V_old,x2) diff(V_old,x3) diff(V_old,x4)].';\n qfcn =rx*q0 + u'*u;\n expr = -[diff(V,x1) diff(V,x2) diff(V,x3) diff(V,x4)]*(rx*f+B*u)-qfcn;\n prog = sosineq(prog,expr);\n prog = sossetobj(prog, myObj);\n prog = sossolve(prog);\n %------------------------------ SOSp End ------------------------------\n V_ = sosgetsol(prog,V);\n V_old = V_;\nend\n\n% Save the improved value function\nVnew = V_;\n\n%% Post-processing results\nx0 = [0,0,0,0]; % Iniial Condition\ntIntv = [0 3];\n[t1,y1] = ode23s(@(t,x) LocalSuspSys(t,x,u), [0 3], x0);\n[t,y] = ode23s(@(t,x) LocalSuspSys(t,x,0), tIntv, x0);\n\n%% Plot Results\nfigure(1)\nsubplot(411);\nplot(t1,y1(:,1),t,y(:,1), 'r:','linewidth',2);\nxlabel('time (sec)', 'FontSize',12)\nylabel('x_1','FontSize',12)\nhl = legend('Improved performance', 'Uncontrolled performance');\nset(hl, 'FontSize', 12');\nsubplot(412);\nplot(t1,y1(:,2),t,y(:,2),'r:','linewidth',2);\nxlabel('time (sec)', 'FontSize',12)\nylabel('x_2','FontSize',12)\nhl = legend('Improved performance', 'Uncontrolled performance');\nset(hl, 'FontSize', 12');\nsubplot(413);\nplot(t1,y1(:,3),t,y(:,3), 'r:','linewidth',2);\nxlabel('time (sec)', 'FontSize',12)\nylabel('x_3','FontSize',12)\nhl = legend('Improved performance', 'Uncontrolled performance');\nset(hl, 'FontSize', 12');\nsubplot(414);\nplot(t1,y1(:,4),t,y(:,4),'r:','linewidth',2);\nxlabel('time (sec)', 'FontSize',12)\nylabel('x_4','FontSize',12)\nhl = legend('Improved performance', 'Uncontrolled performance');\nset(hl, 'FontSize', 12');\n\n\nfigure(2)\nxx1 = -.4:.04:.4;\nxx2 = -5:0.5:5;\nvn = zeros(length(xx1),length(xx2));\nv1 = zeros(length(xx1),length(xx2));\nun=vn;\nulqr = un;\nkn=vn;\nk1=v1;\nx3=0;\nx4=0;\nfor i=1:length(xx1)\n x1 = xx1(i);\n for j=1:length(xx2)\n x2 = xx2(j);\n vn(i,j)=eval(Vnew);\n v1(i,j)=eval(V0);\n end\nend\nsurf(xx1,xx2,vn')\nhold on\nsurf(xx1,xx2,v1')\nhold off\nxlabel('x_1', 'FontSize', 12)\nylabel('x_2', 'FontSize', 12)\nview(gca,[-30.5 28]);\n% Create textarrow\nannotation(gcf,'textarrow',[0.210714285714286 0.174535137214669],...\n [0.895238095238095 0.631440045897884],'TextEdgeColor','none','FontSize',12,...\n 'String',{'V_0(x1,x2,0,0)'});\n\n% Create textarrow\nannotation(gcf,'textarrow',[0.139285714285714 0.186735060271868],...\n [0.183333333333333 0.386454388984516],'TextEdgeColor','none','FontSize',12,...\n 'String',{'V_{10}(x1,x2,0,0)'});\n% export_fig Ex3_cost -pdf -transparent\n\nend\n\n\n%% LocalSuspSys\n% Dynamics of the nonlinear suspension system\nfunction dx = LocalSuspSys(t,x,u)\nmb = 300; % kg\nmw = 60; % kg\nbs = 1000; % N/m/s\nks = 16000 ; % N/m\nkt = 190000; % N/m\n\n[x1,x2,x3,x4] = deal(x(1),x(2),x(3),x(4));\n\n% State matrices\nA = [ 0 1 0 0;\n [-ks -bs ks bs]/mb ; ...\n 0 0 0 1;\n [ks bs -ks-kt -bs]/mw];\nB = [ 0; 10000/mb ; 0 ; -10000/mw];\nB1 = [ 0; 0 ; 0 ; kt/mw];\n\nif ~isdouble(u)\n u = eval(u);\nend\n \nif t <= 0.001\n r = 10;\nelse\n r = 0;\nend\n\ndx = A*x + B*u + B1*r;\nend\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/Chapter4_Example1/Ch4Ex1_main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6975354072047079}} {"text": "function x=t2x(T,str)\n\n% x=t2x(T,str);\n% \n% Converts transformation matrix T between B and A coordinate\n% frames into a generalized position vector x, which contains\n% position and orientation vectors of B with respect to A.\n% Orientation can be expressed with quaternions, euler angles\n% (xyz or zxz convention), unit vector and rotation angle.\n% Also both orientation and position can be expressed with\n% Denavitt-Hartemberg parameters.\n% \n% ---------------------------------------------------------------------------\n% \n% The transformation matrix T between B and A coordinate\n% frames is a 4 by 4 matrix such that:\n% T(1:3,1:3) = Orientation matrix between B and A = unit vectors\n% of x,y,z axes of B expressed in the A coordinates.\n% T(1:3,4) = Origin of B expressed in A coordinates.\n% T(4,1:3) = zeros(1,3)\n% T(4,4) = 1\n%\n% ---------------------------------------------------------------------------\n% \n% The generalized position vector x contains the origin of B\n% expressed in the A coordinates in the first four entries,\n% and orientation of B with respect to A in the last four entries.\n% In more detail, its shape depends on the value of str as \n% specified below :\n% \n% ---------------------------------------------------------------------------\n% \n% str='van' : UNIT VECTOR AND ROTATION ANGLE \n% \n% [ Ox ] origin of the B coordinate frame \n% x(1:4) = [ Oy ] with respect to A.\n% [ Oz ] \n% [ 1 ] \n% \n% [ Vx ] Vx,Vy,Vz = unit vector respect to A, \n% x(5:8) = [ Vy ] which B is rotated about.\n% [ Vz ] \n% [ Th ] Th = angle which B is rotated (-pi,pi].\n% ---------------------------------------------------------------------------\n% \n% str='qua' : UNIT QUATERNION \n% \n% [ Ox ] origin of the B coordinate frame \n% x(1:4) = [ Oy ] with respect to A.\n% [ Oz ] \n% [ 1 ] \n% \n% [ q1 ] q1,q2,q3 = V*sin(Th/2)\n% x(5:8) = [ q2 ] q0 = cos(Th/2) where :\n% [ q3 ] V = unit vector respect to A, which B is \n% [ q0 ] rotated about, Th = angle which B is rotated (-pi,pi].\n% ---------------------------------------------------------------------------\n% \n% str='erp' : EULER-RODRIGUEZ PARAMETERS\n% \n% [ Ox ] origin of the B coordinate frame \n% x(1:4) = [ Oy ] with respect to A.\n% [ Oz ] \n% [ 1 ] \n% \n% [ r1 ] r1,r2,r3 = V*tan(Th/2), where :\n% x(5:8) = [ r2 ] V = unit vector with respect to A, which B is \n% [ r3 ] rotated about.\n% [ 0 ] Th = angle which B is rotated (-pi,pi) (<> pi).\n% ---------------------------------------------------------------------------\n% \n% str='rpy' : ROLL, PITCH, YAW ANGLES (euler x-y-z convention) \n% \n% [ Ox ] origin of the B coordinate frame \n% x(1:4) = [ Oy ] with respect to A.\n% [ Oz ] \n% [ 1 ] \n% \n% [ r ] r = roll angle ( fi (-pi,pi], about x, )\n% x(5:8) = [ p ] p = pitch angle ( theta (-pi,pi], about y, <> +-pi/2)\n% [ y ] y = yaw angle ( psi (-pi,pi], about z, )\n% [ 0 ] \n% ---------------------------------------------------------------------------\n% \n% str='rpm' : ROTATION, PRECESSION, MUTATION ANGLES (euler z-x-z convention) \n% \n% [ Ox ] origin of the B coordinate frame \n% x(1:4) = [ Oy ] with respect to A.\n% [ Oz ] \n% [ 1 ] \n% \n% [ r ] r = rotation angle ( (-pi,pi] ,about z )\n% x(5:8) = [ p ] p = precession angle ( (-pi,pi] ,about x , <> 0,pi )\n% [ y ] y = mutation angle ( (-pi,pi] ,about z )\n% [ 0 ] \n% ---------------------------------------------------------------------------\n% \n% str='dht' : DENAVITT-HARTEMBERG PARAMETERS \n% \n% [ b ] [ a ] this four-parameter \n% x(1:4) = [ d ] , x(5:8) = [ t ] , description does not involve\n% [ 0 ] [ 0 ] a loss of information if and \n% [ 0 ] [ 0 ] only if T has this shape:\n% \n% [ ct -st 0 b ] where : \n% T = [ ca*st ca*ct -sa -d*sa ] \n% [ sa*st sa*ct ca d*ca ] sa = sin(a), ca = cos(a)\n% [ 0 0 0 1 ] st = sin(t), ct = cos(t)\n% ---------------------------------------------------------------------------\n% \n% Example (see also x2t):\n% x=[rand(3,1);1;rand(3,1);0];x-t2x(x2t(x,'rpm'),'rpm')\n% \n%\n% Giampiero Campa 1/11/96\n% \n\n% ---------------------------------------------------------------------------\n% UNIT VECTOR AND ROTATION ANGLE \n\nif [ str=='van' size(T)==[4 4] ],\n\nO=T(1:3,4);\nR=T(1:3,1:3);\nd=round(.5*(trace(R)-1)*1e12)/1e12;\n\nif d==1,\n v=[0 0 1]';\n th=0;\n\nelseif d==-1,\n v0=sum(R'+eye(3,3))';\n\n if v0 == 0 \n\t v0=R(:,2)+R(:,3)+[0 1 1]';\n end;\n\n if v0 == 0 \n\t v0=R(:,3)+[0 0 1]';\n end;\n\n v=v0/norm(v0);\n th=pi;\n\nelse \n\n sg=(vp([1 0 0]',R(:,1))+vp([0 1 0]',R(:,2))+vp([0 0 1]',R(:,3)));\n\n if norm(sg) < 1e-12\n disp(' ');\n disp('T2x warning: det(R)<>1, unit vector assumed to be [0 0 1]''.');\n disp(' ');\n sg=[0 0 1]';\n end\n\n v=sg/norm(sg);\n th=atan2(norm(sg)/2,d);\n\nend\n\nx=[O;1;v;th];\n\n% ---------------------------------------------------------------------------\n% UNIT QUATERNION \n\nelseif [ str=='qua' size(T)==[4 4] ],\n\nO=T(1:3,4);\nR=T(1:3,1:3);\nd=round(.5*(trace(R)-1)*1e12)/1e12;\n\nif d==1,\n v=[0 0 1]';\n th=0;\n\nelseif d==-1,\n v0=sum(R'+eye(3,3))';\n\n if v0 == 0 \n\tv0=R(:,2)+R(:,3)+[0 1 1]';\n end;\n\n if v0 == 0 \n\tv0=R(:,3)+[0 0 1]';\n end;\n\n v=v0/norm(v0);\n th=pi;\n\nelse \n\n sg=(vp([1 0 0]',R(:,1))+vp([0 1 0]',R(:,2))+vp([0 0 1]',R(:,3)));\n\n if norm(sg) < 1e-12\n disp(' ');\n disp('T2x warning: det(R)<>1, unit vector assumed to be [0 0 1]''.');\n disp(' ');\n sg=[0 0 1]';\n end\n\n v=sg/norm(sg);\n th=atan2(norm(sg)/2,d);\n \nend\n\nq=v*sin(th/2);\nq0=cos(th/2);\n\nx=[O;1;q;q0];\n\n% ---------------------------------------------------------------------------\n% EULER-RODRIGUEZ PARAMETERS\n\nelseif [ str=='erp' size(T)==[4 4] ],\n\nO=T(1:3,4);\nR=T(1:3,1:3);\nd=round(.5*(trace(R)-1)*1e12)/1e12;\n\nif d==1,\n v=[0 0 1]';\n th=0;\n\nelseif d==-1,\n v0=sum(R'+eye(3,3))';\n\n if v0 == 0 \n\tv0=R(:,2)+R(:,3)+[0 1 1]';\n end;\n\n if v0 == 0 \n\tv0=R(:,3)+[0 0 1]';\n end;\n\n v=v0/norm(v0);\n th=pi;\n\nelse \n\n sg=(vp([1 0 0]',R(:,1))+vp([0 1 0]',R(:,2))+vp([0 0 1]',R(:,3)));\n\n if norm(sg) < 1e-12\n disp(' ');\n disp('T2x warning: det(R)<>1, unit vector assumed to be [0 0 1]''.');\n disp(' ');\n sg=[0 0 1]';\n end\n\n v=sg/norm(sg);\n th=atan2(norm(sg)/2,d);\n \nend\n\np=v*tan(th/2);\nx=[O;1;p;0];\n\n% ---------------------------------------------------------------------------\n% ROLL, PITCH, YAW ANGLES (euler x-y-z convention) \n\nelseif [ str=='rpy' size(T)==[4 4] ],\n\nO=T(1:3,4);\nR=T(1:3,1:3);\nd=round([0 0 1]*R(:,1)*1e12)/1e12;\n\nif d==1,\n y=atan2([0 1 0]*R(:,2),[1 0 0]*R(:,2));\n p=-pi/2;\n r=-pi/2;\n\nelseif d==-1\n y=atan2([0 1 0]*R(:,2),[1 0 0]*R(:,2));\n p=pi/2;\n r=pi/2;\n\nelse \n sg=vp([0 0 1]',R(:,1));\n j2=sg/sqrt(sg'*sg);\n k2=vp(R(:,1),j2);\n\n r=atan2(k2'*R(:,2),j2'*R(:,2));\n p=atan2(-[0 0 1]*R(:,1),[0 0 1]*k2);\n y=atan2(-[1 0 0]*j2,[0 1 0]*j2);\nend\n\ny1=y+(1-sign(y)-sign(y)^2)*pi;\np1=p+(1-sign(p)-sign(p)^2)*pi;\nr1=r+(1-sign(r)-sign(r)^2)*pi;\n\n% takes smaller values of angles\n\nif norm([y1 p1 r1]) < norm([y p r])\n x=[O;1;r1;-p1;y1;0];\nelse\n x=[O;1;r;p;y;0];\nend\n\n% ---------------------------------------------------------------------------\n% ROTATION, PRECESSION, MUTATION ANGLES (euler z-x-z convention) \n\nelseif [ str=='rpm' size(T)==[4 4] ],\n\nO=T(1:3,4);\nR=T(1:3,1:3);\nd=round([0 0 1]*R(:,3)*1e12)/1e12;\n\nif d==1,\n m=0;\n p=0;\n r=atan2([0 1 0]*R(:,1),[1 0 0]*R(:,1));\n\nelseif d==-1\n m=0;\n p=pi;\n r=atan2([0 1 0]*R(:,1),[1 0 0]*R(:,1));\n\nelse \n sg=vp([0 0 1]',R(:,3));\n i2=sg/norm(sg);\n j2=vp(R(:,3),i2);\n\n m=atan2(j2'*R(:,1),i2'*R(:,1));\n p=atan2([0 0 1]*j2,[0 0 1]*R(:,3));\n r=atan2([0 1 0]*i2,[1 0 0]*i2);\n \nend\n\nr1=r+(1-sign(r)-sign(r)^2)*pi;\np1=p;\nm1=m+(1-sign(m)-sign(m)^2)*pi;\n\n% takes the smaller values of angles\n\nif norm([r1 p1 m1]) < norm([r p m])\n x=[O;1;r1;-p1;m1;0];\nelse\n x=[O;1;r;p;m;0];\nend\n\n% ---------------------------------------------------------------------------\n% DENAVITT-HARTEMBERG PARAMETERS \n\nelseif [ str=='dht' size(T)==[4 4] ],\n\n% b calculation\nb=T(1,4);\n\n% d calculation\nif norm(T(3,3)) > norm(T(2,3))\n d=T(3,4)/T(3,3);\nelse\n d=T(2,4)/T(2,3);\nend\n\n% alfa and theta computation by mean of euler-zxz angles\nR=T(1:3,1:3);\ndl=round([0 0 1]*R(:,3)*1e12)/1e12;\n\nif dl==1,\n th=0;\n alfa=0;\n n=atan2([0 1 0]*R(:,1),[1 0 0]*R(:,1));\nelseif dl==-1\n th=0;\n alfa=pi;\n n=atan2([0 1 0]*R(:,1),[1 0 0]*R(:,1));\nelse \n sg=vp([0 0 1]',R(:,3));\n i2=sg/norm(sg);\n j2=vp(R(:,3),i2);\n\n th=atan2(j2'*R(:,1),i2'*R(:,1));\n alfa=atan2([0 0 1]*j2,[0 0 1]*R(:,3));\n n=atan2([0 1 0]*i2,[1 0 0]*i2);\nend\n\nth1=th+(1-sign(th)-sign(th)^2)*pi;\nalfa1=alfa;\nn1=n+(1-sign(n)-sign(n)^2)*pi;\n\n% takes the smaller values of angles\n\nif norm([th1 alfa1 n1]) < norm([th alfa n])\n x=[b;d;0;0;-alfa1;th1;0;0];\nelse\n x=[b;d;0;0;alfa;th;0;0];\nend\n\n% ---------------------------------------------------------------------------\n% OTHER STRING\n\nelse\n\ndisp(' ');\ndisp(' x=T2x(T,str)');\ndisp(' where T is a 4 by 4 matrix (see help for details)');\ndisp(' and str can be : ''van'',''qua'',''erp'',''rpy'',''rpm'',''dht''. ');\ndisp(' ');\n\nend\n\n\nfunction z=vp(x,y)\n\n% z=vp(x,y); z = 3d cross product of x and y\n% vp(x) is the 3d cross product matrix : vp(x)*y=vp(x,y).\n%\n% by Giampiero Campa. \n\nz=[ 0 -x(3) x(2);\n x(3) 0 -x(1);\n -x(2) x(1) 0 ];\n\nif nargin>1, z=z*y; end\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/956-3d-rotations/t2x.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570318, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6975354040361199}} {"text": "% GETMSWTFEAT Gets the Multiscale Wavelet Transform features, these\n% include: Energy, Variance, Standard Deviation, and Waveform Length\n% feat = getmswtfeat(x,winsize,wininc,SF)\n% ------------------------------------------------------------------\n% The signals in x are divided into multiple windows of size\n% \"winsize\" and the windows are spaced \"wininc\" apart.\n% Inputs\n% ------\n% x: \t\tcolumns of signals\n% winsize:\twindow size (length of x)\n% wininc:\tspacing of the windows (winsize)\n% SF: sampling frequency (Not used in the current implementation, but I left you some options down there)\n% Outputs\n% -------\n% feat: WT features organized as [Energy, Variance, Waveform Length, Entropy]\n\n% Example\n% -------\n% feat = getmswtfeat(rand(1024,1),128,32,32)\n% Assuming here rand(1024,1) (this can be any one dimensional signal,\n% for example EEG or EMG) is a one dimensional signal sampled at 32\n% for 32 seconds only. Utilizing a window size of 128 at 32 increments,\n% features are extracted from the wavelet tree.\n% I assumed 10 decomposition levels (J=10) below in the code.\n% For a full tree at 10 levels you should get 11 features\n% as we have decided to extract 4 types of features then we get 11 x 4 =44\n% features.\n% =========================================================================\n% Multiscale Wavelet Transform feature extraction code by Dr. Rami Khushaba\n% Research Fellow - Faculty of Engineering and IT\n% University of Technology, Sydney.\n% Email: Rami.Khushaba@uts.edu.au\n% URL: www.rami-khushaba.com (Matlab Code Section)\n% last modified 29/08/2012\n% last modified 09/02/2013\n\nfunction feat = getmswtfeat(x,winsize,wininc,SF)\n\nif nargin < 4\n if nargin < 3\n if nargin < 2\n winsize = size(x,1);\n end\n wininc = winsize;\n end\n error('Please provide the sampling frequency of this signal')\nend\n\ndatawin = ones(winsize,1);\ndatasize = size(x,1);\nNsignals = size(x,2);\n\n%% Chop the signal according to a sliding window approach\nnumwin = floor((datasize - winsize)/wininc)+1;\n% allocate memory\nfeat = zeros(winsize,numwin);\nst = 1;\nen = winsize;\nfor i = 1:numwin\n curwin = x(st:en,:).*repmat(datawin,1,Nsignals);\n feat(1:winsize,i) = detrend(curwin);\n \n st = st + wininc;\n en = en + wininc;\nend\n%% ---------------- Various options for J -----------------------\n% Note I put SF above in the inputs because you can use SF to determine the\n% best decompisition level J, however for simplicity here I put it J=10;\nJ=10;% Number of decomposition levels which can also be set using\n% or J=wmaxlev(winsize,'Sym5');\n% or J=(log(SF/2)/log(2))-1;\n%% Multisignal one-dimensional wavelet transform decomposition\ndec = mdwtdec('col',feat,J,'db4');\n% Proceed with Multisignal 1-D decomposition energy distribution\n\nif isequal(dec.dirDec,'c')\n dim = 1;\nend\n[cfs,longs] = wdec2cl(dec,'all');\nlevel = length(longs)-2;\n\nif dim==1\n cfs = cfs';\n longs = longs';\nend\nnumOfSIGs = size(cfs,1);\nnum_CFS_TOT = size(cfs,2);\nabsCFS = abs(cfs);\nabsCFS0 = (cfs);\ncfs_POW2 = absCFS.^2;\nEnergy = sum(cfs_POW2,2);\npercentENER = 0*ones(size(cfs_POW2));\nnotZER = (Energy>0);\npercentENER(notZER,:) = 100*cfs_POW2(notZER,:)./Energy(notZER,ones(1,num_CFS_TOT));\n\n%% or try this version below and tell us which one is the best on your data\n% percentENER(notZER,:) = cfs_POW2(notZER,:);\n\n%% Pre-define and allocate memory\ntab_ENER = zeros(numOfSIGs,level+1);\ntab_VAR = zeros(numOfSIGs,level+1);\n% tab_STD = zeros(numOfSIGs,level+1);\ntab_WL = zeros(numOfSIGs,level+1);\ntab_entropy = zeros(numOfSIGs,level+1);\n\n\n%% Feature extraction section\nst = 1;\nfor k=1:level+1\n nbCFS = longs(k);\n en = st+nbCFS-1;\n tab_ENER(:,k) = mean(percentENER(:,st:en),2);%.*sum(abs(diff(absCFS0(:,st:en)')'),2); % energy per waveform length\n tab_VAR(:,k) = var(percentENER(:,st:en),0,2); % variance of coefficients\n % tab_STD(:,k) = std(percentENER(:,st:en),[],2); % standard deviation of coefficients\n tab_WL(:,k) = sum(abs(diff(percentENER(:,st:en)').^2))'; % waveform length\n percentENER(:,st:en) = percentENER(:,st:en)./repmat(sum(percentENER(:,st:en),2),1,size(percentENER(:,st:en),2));\n tab_entropy(:,k) = -sum(percentENER(:,st:en).*log(percentENER(:,st:en)),2)./size(percentENER(:,st:en),2);\n st = en + 1;\nend\nfeat =([log1p([tab_ENER tab_VAR tab_WL]) tab_entropy]);", "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/37950-feature-extraction-using-multisignal-wavelet-transform-decomposition/getmswtfeat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6975354010012949}} {"text": "function prob_test1341 ( )\n\n%*****************************************************************************80\n%\n%% TEST01341 checks RIBESL against BESSEL_IX_VALUES.\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 fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST1341:\\n' );\n fprintf ( 1, ' RIBESL computes values of Bessel functions\\n' );\n fprintf ( 1, ' of NONINTEGER order.\\n' );\n fprintf ( 1, ' BESSEL_IX_VALUES returns selected values of the\\n' );\n fprintf ( 1, ' Bessel function In for NONINTEGER order.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ...\n ' ALPHA X FX FX2\\n' );\n fprintf ( 1, ...\n ' (table) (RIBESL)\\n' );\n fprintf ( 1, '\\n' );\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, alpha, x, fx ] = bessel_ix_values ( n_data );\n\n if ( n_data == 0 );\n break\n end\n\n ize = 1;\n nb = floor ( alpha ) + 1;\n alpha_frac = alpha - floor ( alpha );\n\n [ b, ncalc ] = ribesl ( x, alpha_frac, nb, ize );\n fx2 = b(nb);\n\n fprintf ( 1, ' %12f %12f %24.16e %24.16e\\n', alpha, x, fx, fx2 );\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/prob_test1341.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.697447340627098}} {"text": "% Script file: doy.m\n%\n% Purpose: \n% This program calculates the day of year corresponding \n% to a specified date. It illustrates the use switch\n% and for constructs. \n%\n% Record of revisions:\n% Date Programmer Description of change\n% ==== ========== =====================\n% 01/27/07 S. J. Chapman Original code \n%\n% Define variables:\n% day -- Day (dd)\n% day_of_year -- Day of year\n% ii -- Loop index\n% leap_day -- Extra day for leap year\n% month -- Month (mm)\n% year -- Year (yyyy)\n\n% Get day, month, and year to convert\ndisp('This program calculates the day of year given the ');\ndisp('specified date.');\nmonth = input('Enter specified month (1-12): ');\nday = input('Enter specified day(1-31): ');\nyear = input('Enter specified year(yyyy): ');\n\n% Check for leap year, and add extra day if necessary\nif mod(year,400) == 0 \n leap_day = 1; % Years divisible by 400 are leap years\nelseif mod(year,100) == 0 \n leap_day = 0; % Other centuries are not leap years\nelseif mod(year,4) == 0\n leap_day = 1; % Otherwise every 4th year is a leap year\nelse\n leap_day = 0; % Other years are not leap years\nend\n\n% Calculate day of year by adding current day to the\n% days in previous months.\nday_of_year = day;\nfor ii = 1:month-1\n\n % Add days in months from January to last month\n switch (ii)\n case {1,3,5,7,8,10,12},\n day_of_year = day_of_year + 31;\n case {4,6,9,11},\n day_of_year = day_of_year + 30;\n case 2,\n day_of_year = day_of_year + 28 + leap_day;\n end\n\nend\n\n% Tell user\nfprintf('The date %2d/%2d/%4d is day of year %d.\\n', ...\n month, day, year, day_of_year);\n", "meta": {"author": "101Hub", "repo": "Matlab101", "sha": "07273f68f1147a110443aeb121fa10962234f298", "save_path": "github-repos/MATLAB/101Hub-Matlab101", "path": "github-repos/MATLAB/101Hub-Matlab101/Matlab101-07273f68f1147a110443aeb121fa10962234f298/assets/\u300aMatlab\u7f16\u7a0b\u300b\u6e90\u7801/chap4/doy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.6974473342227561}} {"text": "function centroid = polyhedronCentroid(vertices, faces) %#ok\n%POLYHEDRONCENTROID Compute the centroid of a 3D convex polyhedron.\n%\n% CENTRO = polyhedronCentroid(V, F)\n% Computes the centroid (center of mass) of the polyhedron defined by\n% vertices V and faces F.\n% The polyhedron is assumed to be convex.\n%\n% Example\n% % Creates a polyhedron centered on origin, and add an arbitrary\n% % translation\n% [v, f] = createDodecahedron;\n% v2 = bsxfun(@plus, v, [3 4 5]);\n% % computes the centroid, that should equal the translation vector\n% centroid = polyhedronCentroid(v2, f)\n% centroid =\n% 3.0000 4.0000 5.0000\n%\n%\n% See also \n% meshes3d, meshVolume, meshSurfaceArea, polyhedronMeanBreadth\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@nantes.inra.fr\n% Created: 2012-04-05, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012-2022 INRA - Cepia Software Platform\n\n% compute set of elementary tetrahedra\nDT = delaunayTriangulation(vertices);\nT = DT.ConnectivityList;\n\n% number of tetrahedra\nnT = size(T, 1);\n\n% initialize result\ncentroid = zeros(1, 3);\nvt = 0;\n\n% Compute the centroid and the volume of each tetrahedron\nfor i = 1:nT\n % coordinates of tetrahedron vertices\n tetra = vertices(T(i, :), :);\n \n % centroid is the average of vertices. \n centi = mean(tetra);\n \n % compute volume of tetrahedron\n vol = det(tetra(1:3,:) - tetra([4 4 4],:)) / 6;\n \n % add weighted centroid of current tetraedron\n centroid = centroid + centi * vol;\n \n % compute the sum of tetraedra volumes\n vt = vt + vol;\nend\n\n% compute by sum of tetrahedron volumes\ncentroid = centroid / vt;\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/meshes3d/polyhedronCentroid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.6974473298659837}} {"text": "function linplus_test035 ( )\n\n%*****************************************************************************80\n%\n%% TEST035 tests R83_GS_SL.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n n = 100;\n maxit = 1000;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST035\\n' );\n fprintf ( 1, ' For a real tridiagonal system,\\n' );\n fprintf ( 1, ' R83_GS_SL solves a linear system using\\n' );\n fprintf ( 1, ' Gauss-Seidel iteration\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix order N = %d\\n', n );\n fprintf ( 1, ' Iterations per call = %d\\n', maxit );\n fprintf ( 1, '\\n' );\n%\n% Set the matrix values.\n%\n a(1,1) = 0.0E+00;\n a(1,2:n) = -1.0E+00;\n a(2,1:n) = 2.0E+00;\n a(3,1:n-1) = -1.0E+00;\n a(3,n) = 0.0E+00;\n\n for job = 0 : 1\n\n if ( job == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Solving A * x = b.\\n' );\n fprintf ( 1, '\\n' );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Solving A'' * x = b.\\n' );\n fprintf ( 1, '\\n' );\n end\n%\n% Set the desired solution.\n%\n x = r8vec_indicator ( n );\n%\n% Compute the corresponding right hand side.\n%\n if ( job == 0 )\n b = r83_mxv ( n, a, x );\n else\n b = r83_vxm ( n, a, x );\n end\n%\n% Set the starting solution.\n%\n x(1:n) = 0.0E+00;\n%\n% Solve the linear system.\n%\n for i = 1 : 3\n\n x_new = r83_gs_sl ( n, a, b, x, maxit, job );\n\n r8vec_print_some ( n, x_new, 1, 10, ' Current solution estimate:' );\n\n x(1:n) = x_new(1:n);\n \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/linplus/linplus_test035.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.6974473168340563}} {"text": "function [der,errest,finaldelta] = derivest(fun,x0,varargin)\n% DERIVEST: estimate the n'th derivative of fun at x0, provide an error estimate\n% usage: [der,errest] = DERIVEST(fun,x0) % first derivative\n% usage: [der,errest] = DERIVEST(fun,x0,prop1,val1,prop2,val2,...)\n%\n% Derivest will perform numerical differentiation of an\n% analytical function provided in fun. It will not\n% differentiate a function provided as data. Use gradient\n% for that purpose, or differentiate a spline model.\n%\n% The methods used by DERIVEST are finite difference\n% approximations of various orders, coupled with a generalized\n% (multiple term) Romberg extrapolation. This also yields\n% the error estimate provided. DERIVEST uses a semi-adaptive\n% scheme to provide the best estimate that it can by its\n% automatic choice of a differencing interval.\n%\n% Finally, While I have not written this function for the\n% absolute maximum speed, speed was a major consideration\n% in the algorithmic design. Maximum accuracy was my main goal.\n%\n%\n% Arguments (input)\n% fun - function to differentiate. May be an inline function,\n% anonymous, or an m-file. fun will be sampled at a set\n% of distinct points for each element of x0. If there are\n% additional parameters to be passed into fun, then use of\n% an anonymous function is recommended.\n%\n% fun should be vectorized to allow evaluation at multiple\n% locations at once. This will provide the best possible\n% speed. IF fun is not so vectorized, then you MUST set\n% 'vectorized' property to 'no', so that derivest will\n% then call your function sequentially instead.\n%\n% Fun is assumed to return a result of the same\n% shape as its input x0.\n%\n% x0 - scalar, vector, or array of points at which to\n% differentiate fun.\n%\n% Additional inputs must be in the form of property/value pairs.\n% Properties are character strings. They may be shortened\n% to the extent that they are unambiguous. Properties are\n% not case sensitive. Valid property names are:\n%\n% 'DerivativeOrder', 'MethodOrder', 'Style', 'RombergTerms'\n% 'FixedStep', 'MaxStep'\n%\n% All properties have default values, chosen as intelligently\n% as I could manage. Values that are character strings may\n% also be unambiguously shortened. The legal values for each\n% property are:\n%\n% 'DerivativeOrder' - specifies the derivative order estimated.\n% Must be a positive integer from the set [1,2,3,4].\n%\n% DEFAULT: 1 (first derivative of fun)\n%\n% 'MethodOrder' - specifies the order of the basic method\n% used for the estimation.\n%\n% For 'central' methods, must be a positive integer\n% from the set [2,4].\n%\n% For 'forward' or 'backward' difference methods,\n% must be a positive integer from the set [1,2,3,4].\n%\n% DEFAULT: 4 (a second order method)\n%\n% Note: higher order methods will generally be more\n% accurate, but may also suffere more from numerical\n% problems.\n%\n% Note: First order methods would usually not be\n% recommended.\n%\n% 'Style' - specifies the style of the basic method\n% used for the estimation. 'central', 'forward',\n% or 'backwards' difference methods are used.\n%\n% Must be one of 'Central', 'forward', 'backward'.\n%\n% DEFAULT: 'Central'\n%\n% Note: Central difference methods are usually the\n% most accurate, but sometiems one must not allow\n% evaluation in one direction or the other.\n%\n% 'RombergTerms' - Allows the user to specify the generalized\n% Romberg extrapolation method used, or turn it off\n% completely.\n%\n% Must be a positive integer from the set [0,1,2,3].\n%\n% DEFAULT: 2 (Two Romberg terms)\n%\n% Note: 0 disables the Romberg step completely.\n%\n% 'FixedStep' - Allows the specification of a fixed step\n% size, preventing the adaptive logic from working.\n% This will be considerably faster, but not necessarily\n% as accurate as allowing the adaptive logic to run.\n%\n% DEFAULT: []\n%\n% Note: If specified, 'FixedStep' will define the\n% maximum excursion from x0 that will be used.\n%\n% 'Vectorized' - Derivest will normally assume that your\n% function can be safely evaluated at multiple locations\n% in a single call. This would minimize the overhead of\n% a loop and additional function call overhead. Some\n% functions are not easily vectorizable, but you may\n% (if your matlab release is new enough) be able to use\n% arrayfun to accomplish the vectorization.\n%\n% When all else fails, set the 'vectorized' property\n% to 'no'. This will cause derivest to loop over the\n% successive function calls.\n%\n% DEFAULT: 'yes'\n%\n%\n% 'MaxStep' - Specifies the maximum excursion from x0 that\n% will be allowed, as a multiple of x0.\n%\n% DEFAULT: 100\n%\n% 'StepRatio' - Derivest uses a proportionally cascaded\n% series of function evaluations, moving away from your\n% point of evaluation. The StepRatio is the ratio used\n% between sequential steps.\n%\n% DEFAULT: 2.0000001\n%\n% Note: use of a non-integer stepratio is intentional,\n% to avoid integer multiples of the period of a periodic\n% function under some circumstances.\n%\n%\n% See the document DERIVEST.pdf for more explanation of the\n% algorithms behind the parameters of DERIVEST. In most cases,\n% I have chosen good values for these parameters, so the user\n% should never need to specify anything other than possibly\n% the DerivativeOrder. I've also tried to make my code robust\n% enough that it will not need much. But complete flexibility\n% is in there for your use.\n%\n%\n% Arguments: (output)\n% der - derivative estimate for each element of x0\n% der will have the same shape as x0.\n%\n% errest - 95% uncertainty estimate of the derivative, such that\n%\n% abs(der(j) - f'(x0(j))) < erest(j)\n%\n% finaldelta - The final overall stepsize chosen by DERIVEST\n%\n%\n% Example usage:\n% First derivative of exp(x), at x == 1\n% [d,e]=derivest(@(x) exp(x),1)\n% d =\n% 2.71828182845904\n%\n% e =\n% 1.02015503167879e-14\n%\n% True derivative\n% exp(1)\n% ans =\n% 2.71828182845905\n%\n% Example usage:\n% Third derivative of x.^3+x.^4, at x = [0,1]\n% derivest(@(x) x.^3 + x.^4,[0 1],'deriv',3)\n% ans =\n% 6 30\n%\n% True derivatives: [6,30]\n%\n%\n% See also: gradient\n%\n%\n% Author: John D'Errico\n% e-mail: woodchips@rochester.rr.com\n% Release: 1.0\n% Release date: 12/27/2006\n\npar.DerivativeOrder = 1;\npar.MethodOrder = 4;\npar.Style = 'central';\npar.RombergTerms = 2;\npar.FixedStep = [];\npar.MaxStep = 100;\n% setting a default stepratio as a non-integer prevents\n% integer multiples of the initial point from being used.\n% In turn that avoids some problems for periodic functions.\npar.StepRatio = 2.0000001;\npar.NominalStep = [];\npar.Vectorized = 'yes';\n\nna = length(varargin);\nif (rem(na,2)==1)\n error 'Property/value pairs must come as PAIRS of arguments.'\nelseif na>0\n par = parse_pv_pairs(par,varargin);\nend\npar = check_params(par);\n\n% Was fun a string, or an inline/anonymous function?\nif (nargin<1)\n help derivest\n return\nelseif isempty(fun)\n error 'fun was not supplied.'\nelseif ischar(fun)\n % a character function name\n fun = str2func(fun);\nend\n\n% no default for x0\nif (nargin<2) || isempty(x0)\n error 'x0 was not supplied'\nend\npar.NominalStep = max(x0,0.02);\n\n% was a single point supplied?\nnx0 = size(x0);\nn = prod(nx0);\n\n% Set the steps to use.\nif isempty(par.FixedStep)\n % Basic sequence of steps, relative to a stepsize of 1.\n delta = par.MaxStep*par.StepRatio .^(0:-1:-25)';\n ndel = length(delta);\nelse\n % Fixed, user supplied absolute sequence of steps.\n ndel = 3 + ceil(par.DerivativeOrder/2) + ...\n par.MethodOrder + par.RombergTerms;\n if par.Style(1) == 'c'\n ndel = ndel - 2;\n end\n delta = par.FixedStep*par.StepRatio .^(-(0:(ndel-1)))';\nend\n\n% generate finite differencing rule in advance.\n% The rule is for a nominal unit step size, and will\n% be scaled later to reflect the local step size.\nfdarule = 1;\nswitch par.Style\n case 'central'\n % for central rules, we will reduce the load by an\n % even or odd transformation as appropriate.\n if par.MethodOrder==2\n switch par.DerivativeOrder\n case 1\n % the odd transformation did all the work\n fdarule = 1;\n case 2\n % the even transformation did all the work\n fdarule = 2;\n case 3\n % the odd transformation did most of the work, but\n % we need to kill off the linear term\n fdarule = [0 1]/fdamat(par.StepRatio,1,2);\n case 4\n % the even transformation did most of the work, but\n % we need to kill off the quadratic term\n fdarule = [0 1]/fdamat(par.StepRatio,2,2);\n end\n else\n % a 4th order method. We've already ruled out the 1st\n % order methods since these are central rules.\n switch par.DerivativeOrder\n case 1\n % the odd transformation did most of the work, but\n % we need to kill off the cubic term\n fdarule = [1 0]/fdamat(par.StepRatio,1,2);\n case 2\n % the even transformation did most of the work, but\n % we need to kill off the quartic term\n fdarule = [1 0]/fdamat(par.StepRatio,2,2);\n case 3\n % the odd transformation did much of the work, but\n % we need to kill off the linear & quintic terms\n fdarule = [0 1 0]/fdamat(par.StepRatio,1,3);\n case 4\n % the even transformation did much of the work, but\n % we need to kill off the quadratic and 6th order terms\n fdarule = [0 1 0]/fdamat(par.StepRatio,2,3);\n end\n end\n case {'forward' 'backward'}\n % These two cases are identical, except at the very end,\n % where a sign will be introduced.\n\n % No odd/even trans, but we already dropped\n % off the constant term\n if par.MethodOrder==1\n if par.DerivativeOrder==1\n % an easy one\n fdarule = 1;\n else\n % 2:4\n v = zeros(1,par.DerivativeOrder);\n v(par.DerivativeOrder) = 1;\n fdarule = v/fdamat(par.StepRatio,0,par.DerivativeOrder);\n end\n else\n % par.MethodOrder methods drop off the lower order terms,\n % plus terms directly above DerivativeOrder\n v = zeros(1,par.DerivativeOrder + par.MethodOrder - 1);\n v(par.DerivativeOrder) = 1;\n fdarule = v/fdamat(par.StepRatio,0,par.DerivativeOrder+par.MethodOrder-1);\n end\n \n % correct sign for the 'backward' rule\n if par.Style(1) == 'b'\n fdarule = -fdarule;\n end\n \nend % switch on par.style (generating fdarule)\nnfda = length(fdarule);\n\n% will we need fun(x0)?\nif (rem(par.DerivativeOrder,2) == 0) || ~strncmpi(par.Style,'central',7)\n if strcmpi(par.Vectorized,'yes')\n f_x0 = fun(x0);\n else\n % not vectorized, so loop\n f_x0 = zeros(size(x0));\n for j = 1:numel(x0)\n f_x0(j) = fun(x0(j));\n end\n end\nelse\n f_x0 = [];\nend\n\n% Loop over the elements of x0, reducing it to\n% a scalar problem. Sorry, vectorization is not\n% complete here, but this IS only a single loop.\nder = zeros(nx0);\nerrest = der;\nfinaldelta = der;\nfor i = 1:n\n x0i = x0(i);\n h = par.NominalStep(i);\n\n % a central, forward or backwards differencing rule?\n % f_del is the set of all the function evaluations we\n % will generate. For a central rule, it will have the\n % even or odd transformation built in.\n if par.Style(1) == 'c'\n % A central rule, so we will need to evaluate\n % symmetrically around x0i.\n if strcmpi(par.Vectorized,'yes')\n f_plusdel = fun(x0i+h*delta);\n f_minusdel = fun(x0i-h*delta);\n else\n % not vectorized, so loop\n f_minusdel = zeros(size(delta));\n f_plusdel = zeros(size(delta));\n for j = 1:numel(delta)\n f_plusdel(j) = fun(x0i+h*delta(j));\n f_minusdel(j) = fun(x0i-h*delta(j));\n end\n end\n \n if ismember(par.DerivativeOrder,[1 3])\n % odd transformation\n f_del = (f_plusdel - f_minusdel)/2;\n else\n f_del = (f_plusdel + f_minusdel)/2 - f_x0(i);\n end\n elseif par.Style(1) == 'f'\n % forward rule\n % drop off the constant only\n if strcmpi(par.Vectorized,'yes')\n f_del = fun(x0i+h*delta) - f_x0(i);\n else\n % not vectorized, so loop\n f_del = zeros(size(delta));\n for j = 1:numel(delta)\n f_del(j) = fun(x0i+h*delta(j)) - f_x0(i);\n end\n end\n else\n % backward rule\n % drop off the constant only\n if strcmpi(par.Vectorized,'yes')\n f_del = fun(x0i-h*delta) - f_x0(i);\n else\n % not vectorized, so loop\n f_del = zeros(size(delta));\n for j = 1:numel(delta)\n f_del(j) = fun(x0i-h*delta(j)) - f_x0(i);\n end\n end\n end\n \n % check the size of f_del to ensure it was properly vectorized.\n f_del = f_del(:);\n if length(f_del)~=ndel\n error 'fun did not return the correct size result (fun must be vectorized)'\n end\n\n % Apply the finite difference rule at each delta, scaling\n % as appropriate for delta and the requested DerivativeOrder.\n % First, decide how many of these estimates we will end up with.\n ne = ndel + 1 - nfda - par.RombergTerms;\n\n % Form the initial derivative estimates from the chosen\n % finite difference method.\n der_init = vec2mat(f_del,ne,nfda)*fdarule.';\n\n % scale to reflect the local delta\n der_init = der_init(:)./(h*delta(1:ne)).^par.DerivativeOrder;\n \n % Each approximation that results is an approximation\n % of order par.DerivativeOrder to the desired derivative.\n % Additional (higher order, even or odd) terms in the\n % Taylor series also remain. Use a generalized (multi-term)\n % Romberg extrapolation to improve these estimates.\n switch par.Style\n case 'central'\n rombexpon = 2*(1:par.RombergTerms) + par.MethodOrder - 2;\n otherwise\n rombexpon = (1:par.RombergTerms) + par.MethodOrder - 1;\n end\n [der_romb,errors] = rombextrap(par.StepRatio,der_init,rombexpon);\n \n % Choose which result to return\n \n % first, trim off the \n if isempty(par.FixedStep)\n % trim off the estimates at each end of the scale\n nest = length(der_romb);\n switch par.DerivativeOrder\n case {1 2}\n trim = [1 2 nest-1 nest];\n case 3\n trim = [1:4 nest+(-3:0)];\n case 4\n trim = [1:6 nest+(-5:0)];\n end\n \n [der_romb,tags] = sort(der_romb);\n \n der_romb(trim) = [];\n tags(trim) = [];\n errors = errors(tags);\n trimdelta = delta(tags);\n \n [errest(i),ind] = min(errors);\n \n finaldelta(i) = h*trimdelta(ind);\n der(i) = der_romb(ind);\n else\n [errest(i),ind] = min(errors);\n finaldelta(i) = h*delta(ind);\n der(i) = der_romb(ind);\n end\nend\n\nend % mainline end\n\n% ============================================\n% subfunction - romberg extrapolation\n% ============================================\nfunction [der_romb,errest] = rombextrap(StepRatio,der_init,rombexpon)\n% do romberg extrapolation for each estimate\n%\n% StepRatio - Ratio decrease in step\n% der_init - initial derivative estimates\n% rombexpon - higher order terms to cancel using the romberg step\n%\n% der_romb - derivative estimates returned\n% errest - error estimates\n% amp - noise amplification factor due to the romberg step\n\nsrinv = 1/StepRatio;\n\n% do nothing if no romberg terms\nnexpon = length(rombexpon);\nrmat = ones(nexpon+2,nexpon+1);\nswitch nexpon\n case 0\n % rmat is simple: ones(2,1)\n case 1\n % only one romberg term\n rmat(2,2) = srinv^rombexpon;\n rmat(3,2) = srinv^(2*rombexpon);\n case 2\n % two romberg terms\n rmat(2,2:3) = srinv.^rombexpon;\n rmat(3,2:3) = srinv.^(2*rombexpon);\n rmat(4,2:3) = srinv.^(3*rombexpon);\n case 3\n % three romberg terms\n rmat(2,2:4) = srinv.^rombexpon;\n rmat(3,2:4) = srinv.^(2*rombexpon);\n rmat(4,2:4) = srinv.^(3*rombexpon);\n rmat(5,2:4) = srinv.^(4*rombexpon);\nend\n\n% qr factorization used for the extrapolation as well\n% as the uncertainty estimates\n[qromb,rromb] = qr(rmat,0);\n\n% the noise amplification is further amplified by the Romberg step.\n% amp = cond(rromb);\n\n% this does the extrapolation to a zero step size.\nne = length(der_init);\nrhs = vec2mat(der_init,nexpon+2,max(1,ne - (nexpon+2)));\nrombcoefs = rromb\\(qromb.'*rhs); \nder_romb = rombcoefs(1,:).';\n\n% uncertainty estimate of derivative prediction\ns = sqrt(sum((rhs - rmat*rombcoefs).^2,1));\nrinv = rromb\\eye(nexpon+1);\ncov1 = sum(rinv.^2,2); % 1 spare dof\nerrest = s.'*12.7062047361747*sqrt(cov1(1));\n\nend % rombextrap\n\n\n% ============================================\n% subfunction - vec2mat\n% ============================================\nfunction mat = vec2mat(vec,n,m)\n% forms the matrix M, such that M(i,j) = vec(i+j-1)\n[i,j] = ndgrid(1:n,0:m-1);\nind = i+j;\nmat = vec(ind);\nif n==1\n mat = mat.';\nend\n\nend % vec2mat\n\n\n% ============================================\n% subfunction - fdamat\n% ============================================\nfunction mat = fdamat(sr,parity,nterms)\n% Compute matrix for fda derivation.\n% parity can be\n% 0 (one sided, all terms included but zeroth order)\n% 1 (only odd terms included)\n% 2 (only even terms included)\n% nterms - number of terms\n\n% sr is the ratio between successive steps\nsrinv = 1./sr;\n\nswitch parity\n case 0\n % single sided rule\n [i,j] = ndgrid(1:nterms);\n c = 1./factorial(1:nterms);\n mat = c(j).*srinv.^((i-1).*j);\n case 1\n % odd order derivative\n [i,j] = ndgrid(1:nterms);\n c = 1./factorial(1:2:(2*nterms));\n mat = c(j).*srinv.^((i-1).*(2*j-1));\n case 2\n % even order derivative\n [i,j] = ndgrid(1:nterms);\n c = 1./factorial(2:2:(2*nterms));\n mat = c(j).*srinv.^((i-1).*(2*j));\nend\n\nend % fdamat\n\n\n\n% ============================================\n% subfunction - check_params\n% ============================================\nfunction par = check_params(par)\n% check the parameters for acceptability\n%\n% Defaults\n% par.DerivativeOrder = 1;\n% par.MethodOrder = 2;\n% par.Style = 'central';\n% par.RombergTerms = 2;\n% par.FixedStep = [];\n\n% DerivativeOrder == 1 by default\nif isempty(par.DerivativeOrder)\n par.DerivativeOrder = 1;\nelse\n if (length(par.DerivativeOrder)>1) || ~ismember(par.DerivativeOrder,1:4)\n error 'DerivativeOrder must be scalar, one of [1 2 3 4].'\n end\nend\n\n% MethodOrder == 2 by default\nif isempty(par.MethodOrder)\n par.MethodOrder = 2;\nelse\n if (length(par.MethodOrder)>1) || ~ismember(par.MethodOrder,[1 2 3 4])\n error 'MethodOrder must be scalar, one of [1 2 3 4].'\n elseif ismember(par.MethodOrder,[1 3]) && (par.Style(1)=='c')\n error 'MethodOrder==1 or 3 is not possible with central difference methods'\n end\nend\n\n% style is char\nvalid = {'central', 'forward', 'backward'};\nif isempty(par.Style)\n par.Style = 'central';\nelseif ~ischar(par.Style)\n error 'Invalid Style: Must be character'\nend\nind = find(strncmpi(par.Style,valid,length(par.Style)));\nif (length(ind)==1)\n par.Style = valid{ind};\nelse\n error(['Invalid Style: ',par.Style])\nend\n\n% vectorized is char\nvalid = {'yes', 'no'};\nif isempty(par.Vectorized)\n par.Vectorized = 'yes';\nelseif ~ischar(par.Vectorized)\n error 'Invalid Vectorized: Must be character'\nend\nind = find(strncmpi(par.Vectorized,valid,length(par.Vectorized)));\nif (length(ind)==1)\n par.Vectorized = valid{ind};\nelse\n error(['Invalid Vectorized: ',par.Vectorized])\nend\n\n% RombergTerms == 2 by default\nif isempty(par.RombergTerms)\n par.RombergTerms = 2;\nelse\n if (length(par.RombergTerms)>1) || ~ismember(par.RombergTerms,0:3)\n error 'RombergTerms must be scalar, one of [0 1 2 3].'\n end\nend\n\n% FixedStep == [] by default\nif (length(par.FixedStep)>1) || (~isempty(par.FixedStep) && (par.FixedStep<=0))\n error 'FixedStep must be empty or a scalar, >0.'\nend\n\n% MaxStep == 10 by default\nif isempty(par.MaxStep)\n par.MaxStep = 10;\nelseif (length(par.MaxStep)>1) || (par.MaxStep<=0)\n error 'MaxStep must be empty or a scalar, >0.'\nend\n\nend % check_params\n\n\n% ============================================\n% Included subfunction - parse_pv_pairs\n% ============================================\nfunction params=parse_pv_pairs(params,pv_pairs)\n% parse_pv_pairs: parses sets of property value pairs, allows defaults\n% usage: params=parse_pv_pairs(default_params,pv_pairs)\n%\n% arguments: (input)\n% default_params - structure, with one field for every potential\n% property/value pair. Each field will contain the default\n% value for that property. If no default is supplied for a\n% given property, then that field must be empty.\n%\n% pv_array - cell array of property/value pairs.\n% Case is ignored when comparing properties to the list\n% of field names. Also, any unambiguous shortening of a\n% field/property name is allowed.\n%\n% arguments: (output)\n% params - parameter struct that reflects any updated property/value\n% pairs in the pv_array.\n%\n% Example usage:\n% First, set default values for the parameters. Assume we\n% have four parameters that we wish to use optionally in\n% the function examplefun.\n%\n% - 'viscosity', which will have a default value of 1\n% - 'volume', which will default to 1\n% - 'pie' - which will have default value 3.141592653589793\n% - 'description' - a text field, left empty by default\n%\n% The first argument to examplefun is one which will always be\n% supplied.\n%\n% function examplefun(dummyarg1,varargin)\n% params.Viscosity = 1;\n% params.Volume = 1;\n% params.Pie = 3.141592653589793\n%\n% params.Description = '';\n% params=parse_pv_pairs(params,varargin);\n% params\n%\n% Use examplefun, overriding the defaults for 'pie', 'viscosity'\n% and 'description'. The 'volume' parameter is left at its default.\n%\n% examplefun(rand(10),'vis',10,'pie',3,'Description','Hello world')\n%\n% params = \n% Viscosity: 10\n% Volume: 1\n% Pie: 3\n% Description: 'Hello world'\n%\n% Note that capitalization was ignored, and the property 'viscosity'\n% was truncated as supplied. Also note that the order the pairs were\n% supplied was arbitrary.\n\nnpv = length(pv_pairs);\nn = npv/2;\n\nif n~=floor(n)\n error 'Property/value pairs must come in PAIRS.'\nend\nif n<=0\n % just return the defaults\n return\nend\n\nif ~isstruct(params)\n error 'No structure for defaults was supplied'\nend\n\n% there was at least one pv pair. process any supplied\npropnames = fieldnames(params);\nlpropnames = lower(propnames);\nfor i=1:n\n p_i = lower(pv_pairs{2*i-1});\n v_i = pv_pairs{2*i};\n \n ind = strmatch(p_i,lpropnames,'exact');\n if isempty(ind)\n ind = find(strncmp(p_i,lpropnames,length(p_i)));\n if isempty(ind)\n error(['No matching property found for: ',pv_pairs{2*i-1}])\n elseif length(ind)>1\n error(['Ambiguous property name: ',pv_pairs{2*i-1}])\n end\n end\n p_i = propnames{ind};\n \n % override the corresponding default in params\n params = setfield(params,p_i,v_i); %#ok\n \nend\n\nend % parse_pv_pairs\n\n", "meta": {"author": "yorgoon", "repo": "minimum-snap-geometric-control", "sha": "efbd741223d1b38f5451f3e5ff421cb3dbf7f8ac", "save_path": "github-repos/MATLAB/yorgoon-minimum-snap-geometric-control", "path": "github-repos/MATLAB/yorgoon-minimum-snap-geometric-control/minimum-snap-geometric-control-efbd741223d1b38f5451f3e5ff421cb3dbf7f8ac/poly_optimization/derivest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.6972565451092537}} {"text": "% Usage: e = Faddeeva_erfi(z [, relerr])\n% \n% Compute erfi(z) = -i*erf(i*z), the imaginary error function,\n% for an array or matrix of complex values z.\n% \n% relerr, if supplied, indicates a desired relative error tolerance in\n% w; the default is 0, indicating that machine precision is requested (and\n% a relative error < 1e-13 is usually achieved). Specifying a larger\n% relerr may improve performance for some z (at the expense of accuracy).\n% \n% S. G. Johnson, http://ab-initio.mit.edu/Faddeeva\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/Faddeeva_MATLAB/Faddeeva_erfi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6972565382987098}} {"text": "i = imread('lab.pgm');\n\n%Make image greyscale\nif length(size(i)) == 3\n\tim = double(i(:,:,2));\nelse\n\tim = double(i);\nend\n\ncs = fast_corner_detect_9(im, 30);\nc = fast_nonmax(im, 30, cs);\n\nimage(im/4)\naxis image\ncolormap(gray)\nhold on\nplot(cs(:,1), cs(:,2), 'r.')\nplot(c(:,1), c(:,2), 'g.')\nlegend('9 point FAST corners', 'nonmax-suppressed corners')\ntitle('9 point FAST corner detection on an image')\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/13006-fast-corner-detector/fast-matlab-src/example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6972565368724916}} {"text": "function [x_sigma, x_gam] = gaussian_para_esti(x)\n% x = x(:);\ngam = 0.2:0.001:10;\nr_gam = (gamma(1./gam).*gamma(3./gam))./((gamma(2./gam)).^2);\nx_mu = mean(x);\nx_sigma_sq = mean((x - x_mu).^2);\nx_sigma = sqrt(x_sigma_sq);\nE_x = mean(abs(x - x_mu));\nrho_x = x_sigma_sq/E_x^2;\n[x_diff, x_ind] = min(abs(rho_x - r_gam));\nx_gam = gam(x_ind); \n", "meta": {"author": "vztu", "repo": "VIDEVAL", "sha": "8a86166bb9a9c8fc5e5eac5db7a77771cf576947", "save_path": "github-repos/MATLAB/vztu-VIDEVAL", "path": "github-repos/MATLAB/vztu-VIDEVAL/VIDEVAL-8a86166bb9a9c8fc5e5eac5db7a77771cf576947/include/C_DIIVINE/gaussian_para_esti.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.697255949669952}} {"text": "function varargout = interp2(varargin)\n% bsarray/interp2: 2-D interpolation (table lookup)\n% usage: ZI = interp2(B,XI,YI);\n% or: ZI = interp2(B,XI,YI,EXTRAPVAL);\n%\n% arguments:\n% B - bsarray object having tensorOrder 2. The positions of the\n% x-coordinates of the underlying data array are assumed to be \n% X = s(2).*(1:Nx), where Nx is the number of data points in the X \n% dimension (i.e., second element of get(B,'dataSize')), and s \n% is the element spacing (i.e., get(B,'elementSpacing')). The\n% positions of the y-coordinates of the underlying data array are\n% assumed to be Y = s(1).*(1:Ny).\n% XI - x-coordinates of points at which to interpolate B.\n% YI - y-coordinates of points at which to interpolate B. YI must be the\n% same size as XI.\n%\n% EXTRAPVAL - value to return for points in XI and YI that are outside \n% the range of X and Y, respectively. Default EXTRAPVAL = NaN.\n%\n% ZI - the values of the underlying bsarray B evaluated at the points in\n% the array XI.\n%\n\n% author: Nathan D. Cahill\n% email: ndcahill@gmail.com\n% date: 18 April 2008\n\n% parse input arguments\n[b,xi,yi,extrapval] = parseInputs(varargin{:});\n\n% get flag to determine if basis functions in each dimension are centred or\n% shifted\nm = double(get(b,'centred'));\nmx = m(2); my = m(1);\n\n% get number of data elements and coefficients, determine amount of padding\n% that has been done to create coefficients\nnData = get(b,'dataSize'); nDatax = nData(2); nDatay = nData(1);\nn = get(b,'coeffsSize'); nx = n(2); ny = n(1);\npadNum = (n-nData-1)/2; padNumx = padNum(2); padNumy = padNum(1);\n\n% get the spacing between elements, and then construct vectors of the\n% locations of the data and of the BSpline coefficients\nh = get(b,'elementSpacing'); hx = h(2); hy = h(1);\nxCol = hx.*((1-padNumx):(nDatax+padNumx+1))';\nxDataCol = xCol((1+padNumx):(end-padNumx));\nyCol = hy.*((1-padNumy):(nDatay+padNumy+1))';\nyDataCol = yCol((1+padNumy):(end-padNumy));\n\n% turn evaluation points into a column vector, but retain original size so\n% output can be returned in same size as input\nsiz_xi = size(xi);\nsiz_zi = siz_xi;\n\n% grab the BSpline coefficients\ncMat = get(b,'coeffs');\n\n% initialize some variables for use in interpolation\nnumelXi = numel(xi);\nziMat = zeros(numelXi,1);\np = 1:numelXi;\n\n% Find indices of subintervals, x(k) <= u < x(k+1),\n% or u < x(1) or u >= x(m-1).\nkx = min(max(1+floor((xi(:)-xCol(1))/hx),1+padNumx),nx-padNumx) + 1-mx;\nky = min(max(1+floor((yi(:)-yCol(1))/hy),1+padNumy),ny-padNumy) + 1-my;\nsx = (xi(:) - xCol(kx))/hx;\nsy = (yi(:) - yCol(ky))/hy;\n\n% perform interpolation\nd = get(b,'degree'); dx = d(2); dy = d(1);\nxflag = (~mx && mod(dx,2));\nyflag = (~my && mod(dy,2));\nfor j=1:ceil((dx+1)/2) % loop over BSpline degree in x dimension\n Bx1 = evalBSpline(sx+j-(1+mx)/2,dx);\n Bx2 = evalBSpline(sx-j+(1-mx)/2,dx);\n for i=1:ceil((dy+1)/2) % loop over BSpline degree in y dimension\n By1 = evalBSpline(sy+i-(1+my)/2,dy);\n By2 = evalBSpline(sy-i+(1-my)/2,dy);\n for ind = 1:numelXi % loop over evaluation points, computing interpolated value\n ziMat(ind) = ziMat(ind) + cMat(ky(ind)-i+my,kx(ind)-j+mx).*By1(ind).*Bx1(ind) + ...\n cMat(ky(ind)+i-1+my,kx(ind)-j+mx).*By2(ind).*Bx1(ind) + ...\n cMat(ky(ind)-i+my,kx(ind)+j-1+mx).*By1(ind).*Bx2(ind) + ...\n cMat(ky(ind)+i-1+my,kx(ind)+j-1+mx).*By2(ind).*Bx2(ind);\n end\n end\n if yflag % add a correction factor if BSpline in y direction is shifted and of odd degree \n By1 = evalBSpline(sy+i+1/2,dy);\n for ind = 1:numelXi\n ziMat(ind) = ziMat(ind) + By1(ind).*...\n (cMat(ky(ind)-i-1,kx(ind)-j+mx).*Bx1(ind) + cMat(ky(ind)-i-1,kx(ind)+j-1+mx).*Bx2(ind));\n end\n end\nend\nif xflag % add a correction factor if BSpline in x direction is shifted and of odd degree\n Bx1 = evalBSpline(sx+j+1/2,dx);\n for i=1:ceil((dy+1)/2)\n By1 = evalBSpline(sy+i-(1+my)/2,dy);\n By2 = evalBSpline(sy-i+(1-my)/2,dy);\n for ind = 1:numelXi\n ziMat(ind) = ziMat(ind) + Bx1(ind).*...\n (cMat(ky(ind)-i+my,kx(ind)-j-1).*By1(ind) + cMat(ky(ind)+i-1+my,kx(ind)-j-1).*By2(ind));\n end\n end\nend\n\n% perform extrapolation\noutOfBounds = xi(:)xDataCol(nDatax) | yi(:)yDataCol(nDatay);\nziMat(p(outOfBounds)) = extrapval;\n\n% reshape result to have same size as input xi\nzi = reshape(ziMat,siz_zi);\nvarargout{1} = zi;\n\n\n%% subfunction parseInputs\nfunction [b,xi,yi,extrapval] = parseInputs(varargin)\n\nnargs = length(varargin);\nerror(nargchk(3,4,nargs));\n\n% Process B\nb = varargin{1};\nif ~isequal(b.tensorOrder,2)\n error([mfilename,'parseInputs:WrongOrder'], ...\n 'bsarray/interp2 can only be used with bsarray objects having tensor order 2.');\nend\n\n% Process XI\nxi = varargin{2};\nif ~isreal(xi)\n error([mfilename,'parseInputs:ComplexInterpPts'], ...\n 'The interpolation points XI should be real.')\nend\n\n% Process YI\nyi = varargin{3};\nif ~isreal(yi)\n error([mfilename,'parseInputs:ComplexInterpPts'], ...\n 'The interpolation points YI should be real.')\nend\nif ~isequal(size(xi),size(yi))\n error([mfilename,'parseInputs:YIXINotSameSize'], ...\n 'YI must be the same size as XI');\nend\n\n% Process EXTRAPVAL\nif nargs > 3\n extrapval = varargin{4};\nelse\n extrapval = [];\nend\nif isempty(extrapval)\n extrapval = NaN;\nend\nif ~isscalar(extrapval)\n error([mfilename,':NonScalarExtrapValue'],...\n 'EXTRAP option must be a scalar.')\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/19632-n-dimensional-bsplines/@bsarray/interp2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.697255944053596}} {"text": "%%%% calculation of field spatial distributions, starting from the eigenvectors (Fourier coefficients)\n%%%% omega = normalized frequency\n%%%% eta = inverse of matrix containing the Fourier coeff. of dielectric\n%%%% function\n%%%% Phi = matrix of column eigenvectors [hx,hy]'\n%%%% kz = vector of real eigenvalues\n%%%% u = index of selected eigenvalue/eigenvector\nfunction [Ex,Ey,Ez,Hx,Hy,Hz] = rfields(omega,eta,kGx,kGy,kz,Phi,N1,N2,u)\nN=N1*N2;\nhx=Phi(1:N,u); hy=Phi((N+1):2*N,u); \nhz=-(1/kz(u))*(kGx*hx+kGy*hy);\nex=-(1/omega)*eta*(kGy*hz-kz(u)*hy); \ney=-(1/omega)*eta*(kz(u)*hx-kGx*hz); \nez=-(1/omega)*eta*(kGx*hy-kGy*hx); \n\nex=reshape(ex,N1,N2); ey=reshape(ey,N1,N2); ez=reshape(ez,N1,N2); \nhx=reshape(hx,N1,N2); hy=reshape(hy,N1,N2); hz=reshape(hz,N1,N2);\nEx=(N1*N2)*ifft2(ifftshift(ex')); \nEy=(N1*N2)*ifft2(ifftshift(ey'));\nEz=(N1*N2)*ifft2(ifftshift(ez')); \n\nHx=(N1*N2)*ifft2(ifftshift(hx')); \nHy=(N1*N2)*ifft2(ifftshift(hy')); \nHz=(N1*N2)*ifft2(ifftshift(hz'));\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/22808-eigenmodes-in-a-2d-photonic-crystal/rfields.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6972051233263188}} {"text": "function ret = wrap_boundary_liu(img, img_size)\n% wrap_boundary_liu.m\n%\n% pad image boundaries such that image boundaries are circularly smooth\n%\n% written by Sunghyun Cho (sodomau@postech.ac.kr)\n%\n% This is a variant of the method below:\n% Reducing boundary artifacts in image deconvolution\n% Renting Liu, Jiaya Jia\n% ICIP 2008\n%\n [H, W, Ch] = size(img);\n H_w = img_size(1) - H;\n W_w = img_size(2) - W;\n\n ret = zeros(img_size(1), img_size(2), Ch);\n for ch = 1:Ch\n alpha = 1;\n HG = img(:,:,ch);\n\n r_A = zeros(alpha*2+H_w, W);\n r_A(1:alpha, :) = HG(end-alpha+1:end, :);\n r_A(end-alpha+1:end, :) = HG(1:alpha, :);\n a = ((1:H_w)-1)/(H_w-1);\n r_A(alpha+1:end-alpha, 1) = (1-a)*r_A(alpha,1) + a*r_A(end-alpha+1,1);\n r_A(alpha+1:end-alpha, end) = (1-a)*r_A(alpha,end) + a*r_A(end-alpha+1,end);\n\n A2 = solve_min_laplacian(r_A(alpha:end-alpha+1,:));\n r_A(alpha:end-alpha+1,:) = A2;\n A = r_A;\n\n r_B = zeros(H, alpha*2+W_w);\n r_B(:, 1:alpha) = HG(:, end-alpha+1:end);\n r_B(:, end-alpha+1:end) = HG(:, 1:alpha);\n a = ((1:W_w)-1)/(W_w-1);\n r_B(1, alpha+1:end-alpha) = (1-a)*r_B(1,alpha) + a*r_B(1,end-alpha+1);\n r_B(end, alpha+1:end-alpha) = (1-a)*r_B(end,alpha) + a*r_B(end,end-alpha+1);\n\n B2 = solve_min_laplacian(r_B(:, alpha:end-alpha+1));\n r_B(:,alpha:end-alpha+1,:) = B2;\n B = r_B;\n\n r_C = zeros(alpha*2+H_w, alpha*2+W_w);\n r_C(1:alpha, :) = B(end-alpha+1:end, :);\n r_C(end-alpha+1:end, :) = B(1:alpha, :);\n r_C(:, 1:alpha) = A(:, end-alpha+1:end);\n r_C(:, end-alpha+1:end) = A(:, 1:alpha);\n\n C2 = solve_min_laplacian(r_C(alpha:end-alpha+1, alpha:end-alpha+1));\n r_C(alpha:end-alpha+1, alpha:end-alpha+1) = C2;\n C = r_C;\n\n A = A(alpha:end-alpha-1, :);\n B = B(:, alpha+1:end-alpha);\n C = C(alpha+1:end-alpha, alpha+1:end-alpha);\n\n ret(:,:,ch) = [img(:,:,ch) B; A C];\n end\n\nend\n\n\nfunction [img_direct] = solve_min_laplacian(boundary_image)\n% function [img_direct] = poisson_solver_function(gx,gy,boundary_image)\n% Inputs; Gx and Gy -> Gradients\n% Boundary Image -> Boundary image intensities\n% Gx Gy and boundary image should be of same size\n [H,W] = size(boundary_image);\n\n % Laplacian\n f = zeros(H,W); clear j k\n\n % boundary image contains image intensities at boundaries\n boundary_image(2:end-1, 2:end-1) = 0;\n j = 2:H-1; k = 2:W-1; f_bp = zeros(H,W);\n f_bp(j,k) = -4*boundary_image(j,k) + boundary_image(j,k+1) + ...\n boundary_image(j,k-1) + boundary_image(j-1,k) + boundary_image(j+1,k);\n clear j k\n\n %f1 = f - reshape(f_bp,H,W); % subtract boundary points contribution\n f1 = f - f_bp; % subtract boundary points contribution\n clear f_bp f\n\n % DST Sine Transform algo starts here\n f2 = f1(2:end-1,2:end-1); clear f1\n % compute sine tranform\n tt = dst(f2); f2sin = dst(tt')'; clear f2\n\n % compute Eigen Values\n [x,y] = meshgrid(1:W-2, 1:H-2);\n denom = (2*cos(pi*x/(W-1))-2) + (2*cos(pi*y/(H-1)) - 2);\n\n % divide\n f3 = f2sin./denom; clear f2sin x y\n\n % compute Inverse Sine Transform\n tt = idst(f3); clear f3; img_tt = idst(tt')'; clear tt\n\n % put solution in inner points; outer points obtained from boundary image\n img_direct = boundary_image;\n img_direct(2:end-1,2:end-1) = 0;\n img_direct(2:end-1,2:end-1) = img_tt;\nend\n", "meta": {"author": "cszn", "repo": "IRCNN", "sha": "d9dcd537bdac3ae5b753296cd675db8a303c8f72", "save_path": "github-repos/MATLAB/cszn-IRCNN", "path": "github-repos/MATLAB/cszn-IRCNN/IRCNN-d9dcd537bdac3ae5b753296cd675db8a303c8f72/utilities/wrap_boundary_liu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.697201755339405}} {"text": "classdef VNT4 < PROBLEM\n% \n% Benchmark MOP proposed by Viennet\n\n%------------------------------- Reference --------------------------------\n% R. Viennet, C. Fonteix, and I. Marc, Multicriteria optimization using a\n% genetic algorithm for determining a Pareto set, International Journal of\n% Systems Science, 1996, 27(2): 255-260.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n methods\n %% Default settings of the problem\n function Setting(obj)\n obj.M = 3;\n obj.D = 2;\n obj.lower = [-4,-4];\n obj.upper = [4,4];\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,PopDec)\n PopObj(:,1) = (PopDec(:,1)-2).^2/2 + (PopDec(:,2)+1).^2/13 + 3;\n PopObj(:,2) = (PopDec(:,1)+PopDec(:,2)-3).^2/175 + (2*PopDec(:,2)-PopDec(:,1)).^2/17 - 13;\n PopObj(:,3) = (3*PopDec(:,1)-2*PopDec(:,2)+4).^2/8 + (PopDec(:,1)-PopDec(:,2)+1).^2/27 + 15;\n end\n %% Calculate constraint violations\n function PopCon = CalCon(obj,PopDec)\n PopCon(:,1) = PopDec(:,2) + 4*PopDec(:,1) - 4;\n PopCon(:,2) = -1 - PopDec(:,1);\n PopCon(:,3) = PopDec(:,1) - 2 - PopDec(:,2);\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n N = ceil(sqrt(N));\n x = linspace(-1,1.2,N);\n X = [];\n for i = 1 : N\n X = [X;repmat(x(i),N,1),linspace(x(i)-2,-4*x(i)+4,N)'];\n end\n R = obj.CalObj(X);\n R = R(NDSort(R,1)==1,:);\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n x = linspace(-1,1.2,40);\n X = [];\n for i = 1 : 40\n X = [X;repmat(x(i),40,1),linspace(x(i)-2,-4*x(i)+4,40)'];\n end\n R = obj.CalObj(X);\n R(NDSort(R,1)>1,:) = nan;\n R = {reshape(R(:,1),40,40),reshape(R(:,2),40,40),reshape(R(:,3),40,40)};\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/VNT/VNT4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.6971898821363924}} {"text": "function beta_nc_test01 ( )\n\n%*****************************************************************************80\n%\n%% BETA_NC_TEST01 tests BETA_NONCENTRAL_CDF against tabulated values.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 January 2008\n%\n% Author:\n%\n% John Burkardt\n%\n error_max = 1.0E-10;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BETA_NC_TEST01:\\n' );\n fprintf ( 1, ' Compare tabulated values of the noncentral\\n' );\n fprintf ( 1, ' incomplete Beta Function against values\\n' );\n fprintf ( 1, ' computed by BETA_NONCENTRAL_CDF.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1,' A B LAMBDA X ' );\n fprintf ( 1,' CDF CDF DIFF\\n' );\n fprintf ( 1,' ' );\n fprintf ( 1,' (tabulated) (BETA_NC)\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, a, b, lambda, x, fx ] = beta_noncentral_cdf_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fx2 = beta_noncentral_cdf ( a, b, lambda, x, error_max );\n\n fprintf ( 1, ' %7.1f %7.1f %7.1f %7.3f %24.16e %24.16e %10.4e\\n', ...\n a, b, lambda, x, fx, fx2, abs ( fx - fx2 ) );\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/beta_nc/beta_nc_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.6971898771302191}} {"text": "function [ n_data, n, z, fx ] = polylogarithm_values ( n_data )\n\n%*****************************************************************************80\n%\n%% POLYLOGARITHM_VALUES returns some values of the polylogarithm.\n%\n% Discussion:\n%\n% The polylogarithm of n and z is defined as\n%\n% f[n,z] = Sum ( 1 <= k < infinity ) z^k / k^n\n%\n% In Mathematica, the function can be evaluated by:\n%\n% PolyLog[n,z]\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% 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 exponent of the denominator.\n%\n% Output, real Z, the base of the numerator.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 12;\n\n fx_vec = [ ...\n 0.1644934066848226E+01, ...\n 0.1202056903159594E+01, ...\n 0.1000994575127818E+01, ...\n 0.5822405264650125E+00, ...\n 0.5372131936080402E+00, ...\n 0.5002463206060068E+00, ...\n 0.3662132299770635E+00, ...\n 0.3488278611548401E+00, ...\n 0.3334424797228716E+00, ...\n 0.1026177910993911E+00, ...\n 0.1012886844792230E+00, ...\n 0.1000097826564961E+00 ];\n\n n_vec = [ ...\n 2, 3, 10, 2, 3, 10, 2, 3, 10, 2, 3, 10 ];\n\n z_vec = [ ...\n 0.1000000000000000E+01, ...\n 0.1000000000000000E+01, ...\n 0.1000000000000000E+01, ...\n 0.5000000000000000E+00, ...\n 0.5000000000000000E+00, ...\n 0.5000000000000000E+00, ...\n 0.3333333333333333E+00, ...\n 0.3333333333333333E+00, ...\n 0.3333333333333333E+00, ...\n 0.1000000000000000E+00, ...\n 0.1000000000000000E+00, ...\n 0.1000000000000000E+00 ];\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 z = 0.0;\n fx = 0.0;\n else\n n = n_vec(n_data);\n z = z_vec(n_data);\n fx = fx_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/polylogarithm_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.6971898695007633}} {"text": "function a = fourier_sine_inverse ( n )\n\n%*****************************************************************************80\n%\n%% FOURIER_SINE_INVERSE returns the inverse of the FOURIER_SINE matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real A(N,N), the matrix.\n%\n a = fourier_sine ( 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_mat/fourier_sine_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.8479677526147222, "lm_q1q2_score": 0.6971898618438859}} {"text": "%\n% Compute the factorization of a multivariate polynomial \n% by Ruppert matrix, projection, Newton polygon, generalized eigenvalue\n% and numerical GCD\n%\n% Syntax: >> fac = NIF(F,tol)\n% \n% Input: F -- (matrix) multivariate polynomial in coeff. matrices\n% !!!must be squarefree!!!\n% tol -- (numeric) coefficient error tolerence\n%\n% Output: fac -- (cell) irreducible factors of G in coeff. matrices\n% \n% Example:\n%\n% >> F\n%\n% F =\n%\n% 0 1 1 2\n% 0 1 0 1\n% 0 0 2 2\n% 15 10 3 2\n%\n% >> fac = NIF(F,1e-10);\n% >> fac{:}\n%\n% ans =\n% \n% 0 1.0000 \n% 0 1.0000 \n% 0 0 \n% 0.8320 - 0.0035i 0.5547 - 0.0024i\n% \n% \n% ans =\n% \n% 0 1.0000 \n% 0 0 \n% 0 2.0000 \n% 0.9729 + 0.1223i 0.1946 + 0.0245i\n% \n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/homotopy/NIF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951570602081, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6971886668563979}} {"text": "%TEST 07: Simple v.s. Area (two methods of building weight matrix)\nclear\nclc\nfprintf('TEST 07: Simple v.s. Area (two methods of building weight matrix)\\r');\nim = imtest('s4',156);\nfigure('name','Original Image: Phantom')\nimshow(im)\nsiz = size(im);\nangles = 0:3:179;\n[W1,p1,~,~] = buildWeightMatrixSimple(im,angles);\n[W2,p2,~,~] = buildWeightMatrixArea(im,angles);\n%Simple\nfprintf('Reconstruct from simple-W:\\r')\nim_rec1 = tomo_recon_lsqr(W1, p1, siz, 1e-6, 1000);\nim_rec1 = uint8(imscale(im_rec1));\nfigure('name','Simple')\nimshow(im_rec1);\n%Area\nfprintf('Reconstruct from area-W:\\r')\nim_rec2 = tomo_recon_lsqr(W2, p2, siz, 1e-6, 1000);\nim_rec2 = uint8(imscale(im_rec2));\nfigure('name','Area')\nimshow(im_rec2);\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/43008-tomotools/tomotool/test_07_Compare_simple_area_weightmat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565739, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6971837450423688}} {"text": "function determ = hankel_n_determinant ( n )\n\n%*****************************************************************************80\n%\n%% HANKEL_N_DETERMINANT returns the determinant of the HANKEL_N matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 January 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Output, real DETERM, the determinant.\n%\n determ = r8_mop ( floor ( n / 2 ) ) * n ^ 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_mat/hankel_n_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.6970802719314325}} {"text": "function [xH, H, HNMax, HNMin] = hopkins_main (dataXY_all, xlim1, xlim2, ylim1, ylim2, m, N, Nbins, envelopes, Nsimul, filename)\n% HOPKINS_MAIN computes hopkins statistics\n% [xH, H, HNMax, HNMin] = hopkins_main (dataXY_all, xlim1, xlim2, ylim1, ylim2, m, N, Nbins, envelopes, Nsimul, filename)\n% dataXY_all - whole data\n% [xlim1, xlim2, ylim1, ylim2] - selected ROI\n% m - number of random events and points for Hopkins computation \n% N - number of iterations for histogram computation \n% Nbins - numbero of bins in histogram \n% envelopes - if set to 1 maximum and minimum envelopes for Poisson random \n% process are computed\n% Nsimul - number of simulations for envelopes computation \n% filename - name of the txt file where results are written \n\nHopp.xlim1=xlim1; Hopp.xlim2=xlim2; Hopp.ylim1=ylim1; Hopp.ylim2=ylim2;\nHopp.Nbins = Nbins; Hopp.m = m; Hopp.N = N; \nif envelopes, Hopp.Nsimul = Nsimul; end\n\nfigure\ndataXY = ROIdata(dataXY_all, Hopp.xlim1, Hopp.xlim2, Hopp.ylim1, Hopp.ylim2, 1); \nHopp.Npoints = length(dataXY);\n\nfprintf('Computing Hopkins statistics for selected ROI... \\n');\nh = waitbar(0,'Computing Hopkins...');\nfor ii=1:Hopp.N\n HopD(ii) = hopkins(dataXY, Hopp.xlim1, Hopp.xlim2, Hopp.ylim1, Hopp.ylim2, Hopp.m);\n waitbar(ii/Hopp.N,h)\nend\nclose (h)\n\n[H, xH] = hist(HopD, Nbins);\nH = H/trapz(xH, H); % normalization\n\nif envelopes\n [HNMin, HNMax, xH] = ...\n hopkinsEnv(Hopp.Npoints, Hopp.xlim1, Hopp.xlim2, Hopp.ylim1, Hopp.ylim2, Hopp.m,Hopp.N, xH, Hopp.Nsimul);\n if nargin>10\n writedata(xH, HNMax, Hopp, [filename '_envelope_Max'], ['Hopkins statistics - Maximum of ' num2str(Hopp.Nsimul) ' simulations of Poisson process']);\n writedata(xH, HNMin, Hopp, [filename '_envelope_Min'], ['Hopkins statistics - Mainimum of ' num2str(Hopp.Nsimul) ' simulations of Poisson process'])\n end\nelse\n HNMin = [];\n HNMax = [];\nend\n\nif nargin>10\n writedata(xH, H, Hopp, filename, 'Hopkins statistics')\n save (filename)\nend \n\n\nfunction [HhistMin, HhistMax, xHhist] = hopkinsEnv(Npoints, xlim1, xlim2, ylim1, ylim2, m,N, bins, Nsimul)\n% function [HhistMin, HhistMax, xHhist] = hopkinsEnv(Npoints, xlim1, xlim2,\n% ylim1, ylim2, m,N, bins, Nsimul)\n\nh = waitbar(0,'Computing Hopkins Envelope...');\nfor ii=1 : Nsimul\n waitbar(ii/Nsimul,h)\n simNoise = generateNoise(Npoints, [xlim1,xlim2,ylim1,ylim2]);\n for jj=1 : N\n H(jj) = hopkins (simNoise,xlim1, xlim2, ylim1, ylim2, m);\n end\n [Hhist, xHhist] = hist(H, bins);\n Hhist = Hhist/trapz(xHhist, Hhist); % normalization\n if ii==1\n HhistMin = Hhist;\n HhistMax = Hhist;\n else\n HhistMin = min(HhistMin, Hhist);\n HhistMax = max(HhistMax, Hhist);\n end\nend\nclose (h)", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/PatternAnalysis/hopkins_main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.6970802636503403}} {"text": "%% meshCleave\n% Below is a demonstration of the features of the |meshCleave| function\n\n%%\nclear; close all; clc;\n\n%% Syntax\n% |[logicAt]=meshCleave(E,V);|\n% |[logicAt]=meshCleave(E,V,P,n);|\n% |[logicAt,logicAbove,logicBelow]=meshCleave(E,V,P,n,inclusiveSwitch);|\n% |[logicAt,logicAbove,logicBelow]=meshCleave(E,V,P,n,inclusiveSwitch);|\n\n%% Description\n% This function creates logic arrays for the mesh components (e.g. elements\n% or faces) which are at, above, or below a plane defined by the point P,\n% and the normal direction n. \n% The optional inclusiveSwitch is a 2-component vector (default [0 0]) and\n% sets how \"inclusive\", the below/above logic is, i.e. they set wether <\n% and > is used ([0 0]), or <= and >= are used ([1 1]). A combination may\n% also be used e.g. [1 0] results in below checks which features <= and\n% above checks using >. \n\n%% Examples\nclear; close all; clc;\n\n%% Example: Cleaving a surface mesh\n\n%%\n% Create example patch data\n[F,V]=stanford_bunny; \n\n%%\n\nn=[0 0 1]; %Normal direction to plane\nP=mean(V,1); %Point on plane\n[logicAt,logicAbove,logicBelow]=meshCleave(F,V,P,n);\n\n%%\n% Visualize\ncFigure; \nsubplot(1,3,1); hold on;\ntitle('At cleave plane');\ngpatch(F,V,'w','none',0.2);\ngpatch(F(logicAt,:),V,'bw','k',1);\ncamlight headlight;\naxisGeom; \n\nsubplot(1,3,2); hold on;\ntitle('Above cleave plane');\ngpatch(F,V,'w','none',0.2);\ngpatch(F(logicAbove,:),V,'bw','k',1);\ncamlight headlight;\naxisGeom; \n\nsubplot(1,3,3); hold on;\ntitle('Below cleave plane');\ngpatch(F,V,'w','none',0.2);\ngpatch(F(logicBelow,:),V,'bw','k',1);\ncamlight headlight;\naxisGeom; \n\ngdrawnow;\n\n%% Example 2: Cleaving a tetrahedral mesh\n\n%%\n% Creating an example tetrahedral mesh\nboxDim=[5 5 5]; % Box dimenstions \npointSpacing=0.25;\n[meshStruct]=tetMeshBox(boxDim,pointSpacing);\nE=meshStruct.elements;\nV=meshStruct.nodes;\nF=meshStruct.facesBoundary;\nVE=patchCentre(E,V);\nC=minDist(VE,mean(VE,1));\n\n%%\n\nn=[0 0 1]; %Normal direction to plane\nP=mean(V,1); %Point on plane\n[logicAt,logicAbove,logicBelow]=meshCleave(E,V,P,n);\n\n% Get faces and matching color data for visualization\n[F_cleave,CF_cleave]=element2patch(E(logicAt,:),C(logicAt));\n[F_above,CF_above]=element2patch(E(logicAbove,:),C(logicAbove));\n[F_below,CF_below]=element2patch(E(logicBelow,:),C(logicBelow));\n\n%%\n% Visualize\ncFigure; \nsubplot(1,3,1); hold on;\ntitle('At cleave plane');\ngpatch(F,V,'w','none',0.2);\ngpatch(F_cleave,V,CF_cleave,'k',1);\ncamlight headlight;\naxisGeom; \n\nsubplot(1,3,2); hold on;\ntitle('Above cleave plane');\ngpatch(F,V,'w','none',0.2);\ngpatch(F_above,V,CF_above,'k',1);\ncamlight headlight;\naxisGeom; \n\nsubplot(1,3,3); hold on;\ntitle('Below cleave plane');\ngpatch(F,V,'w','none',0.2);\ngpatch(F_below,V,CF_below,'k',1);\ncamlight headlight;\naxisGeom; \n\ngdrawnow;\n\n%% \n% Visualizing cleaving operation for varying angles\n\nhf=cFigure; hold on; \ngpatch(F,V,'w','none',0.2);\nhp1=gpatch(F_cleave,V,CF_cleave,'k',1);\naxisGeom; axis manual; \ncamlight headligth;\ngdrawnow; \n\nnSteps=50; %Number of animation steps\n\n%Create the time vector\nanimStruct.Time=linspace(0,1,nSteps);\n\n%The vector lengths\na=linspace(0,2*pi,nSteps);\nb=linspace(0,2*pi,nSteps);\nfor q=1:1:nSteps \n R=euler2DCM([a(q) b(q) 0]);\n nn=n*R; \n \n logicAt=meshCleave(E,V,P,nn,[1 0]);\n\n % Get faces and matching color data for cleaves elements \n [F_cleave,CF_cleave]=element2patch(E(logicAt,:),C(logicAt));\n\n %Set entries in animation structure\n animStruct.Handles{q}=[hp1 hp1]; %Handles of objects to animate\n animStruct.Props{q}={'Faces','CData'}; %Properties of objects to animate\n animStruct.Set{q}={F_cleave,CF_cleave}; %Property values for to set in order to animate\nend\nanim8(hf,animStruct);\n\n%% Example 3: Cleaving a hexahedral mesh\n\nboxDim=[5 5 5]; % Box dimenstions\nboxEl=[20 20 20];\n[meshStruct]=hexMeshBox(boxDim,boxEl,2);\n\nE=meshStruct.elements;\nV=meshStruct.nodes;\nF=meshStruct.facesBoundary;\nVE=patchCentre(E,V);\nC=minDist(VE,mean(VE,1));\n\n%%\n\nn=[0 0 1]; %Normal direction to plane\nP=mean(V,1); %Point on plane\ninclusiveSwitch=[1 0];\n[logicAt,logicAbove,logicBelow]=meshCleave(E,V,P,n,inclusiveSwitch);\n\nlogicPlot=logicAt;\n\n% Get faces and matching color data for visualization\n[F_cleave,CF_cleave]=element2patch(E(logicAt,:),C(logicAt));\n[F_above,CF_above]=element2patch(E(logicAbove,:),C(logicAbove));\n[F_below,CF_below]=element2patch(E(logicBelow,:),C(logicBelow));\n\n%%\n% Visualize\ncFigure; \nsubplot(1,3,1); hold on;\ntitle('At cleave plane');\ngpatch(F,V,'w','none',0.2);\ngpatch(F_cleave,V,CF_cleave,'k',1);\ncamlight headlight;\naxisGeom; \n\nsubplot(1,3,2); hold on;\ntitle('Above cleave plane');\ngpatch(F,V,'w','none',0.2);\ngpatch(F_above,V,CF_above,'k',1);\ncamlight headlight;\naxisGeom; \n\nsubplot(1,3,3); hold on;\ntitle('Below cleave plane');\ngpatch(F,V,'w','none',0.2);\ngpatch(F_below,V,CF_below,'k',1);\ncamlight headlight;\naxisGeom; \n\ngdrawnow;\n\n%% \n% Visualizing slicing operation for varying angles\n\nhf=cFigure; hold on; \ngpatch(F,V,'w','none',0.2);\nhp1=gpatch(F_cleave,V,CF_cleave,'k',1);\naxisGeom; axis manual; \ncamlight headligth;\ngdrawnow; \n\nnSteps=50; %Number of animation steps\n\n%Create the time vector\nanimStruct.Time=linspace(0,1,nSteps);\n\n%The vector lengths\na=linspace(0,2*pi,nSteps);\nb=linspace(0,2*pi,nSteps);\nfor q=1:1:nSteps \n R=euler2DCM([a(q) b(q) 0]);\n nn=n*R; \n \n logicAt=meshCleave(E,V,P,nn,inclusiveSwitch);\n\n % Get faces and matching color data for cleaves elements \n [F_cleave,CF_cleave]=element2patch(E(logicAt,:),C(logicAt));\n\n %Set entries in animation structure\n animStruct.Handles{q}=[hp1 hp1]; %Handles of objects to animate\n animStruct.Props{q}={'Faces','CData'}; %Properties of objects to animate\n animStruct.Set{q}={F_cleave,CF_cleave}; %Property values for to set in order to animate\nend\nanim8(hf,animStruct);\n\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/docs/HELP_meshCleave.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.6970802588917757}} {"text": "function[varargout]=trajchunk(varargin)\n%TRAJCHUNK Chunks Lagrangian trajectories based on the Coriolis period.\n%\n% TRAJCHUNK is used to split float or drifter data into chunks such that\n% the length of each chunk is a fixed multiple of one over the mean\n% Coriolis frequency. This can be useful in spectral analysis. \n%\n% [NUMO,LATO]=TRAJCHUNK(NUM,LAT,P), where NUM and LAT are date number and\n% latitude for Lagangian float or drifter data, re-organizes these into \n% chunks such that the average Coriolis frequency f_C in each chunk is at \n% least P times the Rayleigh frequency f_R for that chunk.\n%\n% The Rayleigh frequency is f_R=2*pi/(DT*N), in units of radians per unit \n% time, where DT is the sample interval and N is the number of samples.\n% The Rayleigh frequency decreases as the chunk length increases.\n%\n% The input fields NUM and LAT may either be numerical arrays, or \n% cell arrays of numerical arrays, e.g. NUM{1}=NUM1, NUM{2}=NUM2, etc.\n%\n% The output variables NUM and LAT are cell arrays of numerical arrays, \n% with each cell being just long enough such that f_C > P * f_R. \n%\n% Trajectories that are not long enough to satisfy this criterion are \n% discarded, as are short residual segments at the end of trajectories. \n%\n% Each input trajectory is thus split into zero, one, or more than one\n% cells in the output variables. \n%\n% TRAJCHUNK(...,P,LMIN) additionally specifies a mininum number of points\n% LMIN for each chunk. \n% __________________________________________________________________\n%\n% Multiple input / output arguments\n%\n% [NUMO,LATO,Y1,Y2,...,YM]=TRAJCHUNK(NUM,LAT,X1,X2,...XM,P) chunks the M\n% input arrays X1, X2,... XM in the same manner, and returns these as Y1,\n% Y2,... YM. The input variables may either all be numerical arrays of \n% all the same size, or cell arrays of numerical arrays. \n%\n% In the case of cell array input, some of the XM may be numerical arrays\n% of the same length as the cells NUM and LAT. The corresponding output \n% variable will then also be a numerical array. An example of such a\n% field is the identification number used in FLOATS.MAT and DRIFTERS.MAT. \n%\n% TRAJCHUNK with no output arguments overwrites the original named output\n% variables. \n% __________________________________________________________________\n% \n% Optional behaviors\n%\n% By default, any data in short trajectories for which f_C < P * f_R are \n% discarded, as are data segments at the end of the trajectories. \n%\n% TRAJCHUNK(...,'keep') keeps these instead. Short trajectories are \n% returned in their own chunks, and leftover segments are appended to \n% the end of the preceding chunk. \n%\n% TRAJCHUNK(...,'full') instead ensures that the output cells span the \n% full duration of the input fields. This is done by appending a final \n% cell having f_C > P * f_R, like the others, but that ends at the final\n% data point, regardless of the degree of overlap with the previous cell. \n% Data from cells shorter than the specified length are discarded. \n% __________________________________________________________________\n% \n% Overlap\n%\n% TRAJCHUNK(...,'overlap',PCT) outputs chunks with a percentage PCT \n% overlap. For example, TRAJCHUNK(...,'overlap',50) outputs chunks that \n% overlap by 50%. The default behavior gives chunks with no overlap.\n% __________________________________________________________________ \n%\n% See also CELLCHUNK.\n%\n% 'trajchunk --t' runs a test.\n%\n% Usage: [num,lat]=trajchunk(num,lat,P);\n% [num,lat,lon,cv]=trajchunk(num,lat,lon,cv,P);\n% [num,lat,lon,cv]=trajchunk(num,lat,lon,cv,P,lmin);\n% [num,lat,lon,cv]=trajchunk(num,lat,lon,cv,P,'overlap',50);\n% trajchunk(num,lat,lon,cv,P);\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2014--2019 J.M. Lilly --- type 'help jlab_license' for details\n\n% [...,II,KK]=TRAJCHUNK(...) in this case also outputs the indices of\n% the data locations within the input cells. KK is not a cell array\n% like the other output arguments, but rather a row array of LENGTH(II).\n\n% [..,II]=TRAJCHUNK(...), with an extra final output argument, \n% outputs a cell array II of indices to the original time series. \n%\n% As an example, LAT(II{1}) gives the latitudes of the data in the first \n% cell of the output, LATO{1}.\n\n\n% Equivalently, this means that the inertial period 2*pi/f_C is just less\n% than 1/M times the chunk duration DT*N, or 2*pi/f_C < (1/M) * (DT*N). \n% Thus M inertial oscillations fit into each chunk.\n% Not completely sure about the wording of this due to the definition of \n% 'mean Coriolis frequency' etc.\n\nif strcmpi(varargin{1}, '--t')\n trajchunk_test,return\nend\n\nfactor=1;\nopt='nokeep'; %What to do with leftover points\n\nfor i=1:2\n if ischar(varargin{end})\n if strcmpi(varargin{end}(1:3),'kee')||strcmpi(varargin{end}(1:3),'nok')||strcmpi(varargin{end}(1:3),'ful')\n opt=varargin{end};\n varargin=varargin(1:end-1);\n end\n end\n if ischar(varargin{end-1})\n if strcmpi(varargin{end-1}(1:3),'ove')\n factor=1-varargin{end}/100;\n varargin=varargin(1:end-2);\n end\n end\nend\n\nif ~iscell(varargin{end-1})&&length(varargin{end-1})==1\n N=varargin{end-1};\n M=varargin{end};\n varargin=varargin(1:end-2);\nelse\n N=varargin{end};\n M=0;\n varargin=varargin(1:end-1);\nend\n \nnum=varargin{1};\nlat=varargin{2};\n%Note: leave num and lat as first two entries also\nna=length(varargin);\n\n%na,N,M,size(num),size(lat),str,opt\nif ~iscell(lat)\n %Create ii index \n varargin{na+1}=[1:length(lat)]';\n index=trajchunk_index(num,lat,N,M,opt,factor);\n n=0;\n if ~isempty(index)\n for k=1:length(index)\n n=n+1;\n for j=1:na+1\n varargout{j}{n,1}=varargin{j}(index{k});\n end\n end\n end\nelse \n %/**************\n %Put numerical array input into cell arrays\n bid=false(size(varargin));\n for i=3:length(bid) %Lat and lon are not allowed to be arrays\n if ~iscell(varargin{i})\n bid(i)=true;\n varargin{i}=celladd(varargin{i},cellmult(0,varargin{1}));\n end\n end\n %\\**************\n \n% %Create ii and kk indices\n% for i=1:length(lat)\n% varargin{na+1}{i}=[1:length(lat{i})]';\n% varargin{na+2}{i}=i+0*lat{i};\n% end\n index=[];\n for i=1:length(lat)\n if length(lat)>1000\n if res((i-1)/1000)==0\n disp(['TRAJCHUNK working on cells ' int2str(i) ' to ' int2str(min(i+1000,length(lat))) ' of ' int2str(length(lat)) '.'])\n end\n end\n index{i,1}=trajchunk_index(num{i},lat{i},N,M,opt,factor);\n end \n n=0;\n for i=1:length(lat)\n if ~isempty(index{i})\n for k=1:length(index{i})\n n=n+1;\n for j=1:na\n varargout{j}{n,1}=varargin{j}{i}(index{i}{k});\n end\n end\n end\n end\n \n %Return numerical array input back to numerical arrays\n for i=1:length(bid)\n if bid(i)\n varargout{i}=cellfirst(varargout{i});\n end\n end\n \n% %i,j,k,n\n% %Convert cell array kk into numeric array\n% temp=varargout{na+2};\n% varargout{na+2}=zeros(size(varargout{na+1}));\n% for i=1:length(varargout{na+1})\n% varargout{na+2}(i)=temp{i}(1);\n% end\nend\n\neval(to_overwrite(na));\n\nfunction[index]=trajchunk_index(num,lat,N,M,opt,factor)\nif length(num)<2\n index=[];\nelse \n dt=num(2)-num(1);\n \n fo=abs(corfreq(lat))*24;\n meanfo=frac(cumsum(fo),[1:length(fo)]');\n fr=frac(2*pi,dt*[1:length(fo)]');\n %aresame(meanfo(end),vmean(fo,1))\n \n bdone=false;\n n=0;\n \n x=[1:length(fo)]';\n index=[];\n while ~bdone\n ii=max(find(N*fr=length(x)\n bdone=1;\n else\n index{n}=x(1:ii);\n %N*fr(ii)32*fr))\n%length(num),length(cell2col(num))\n\nuse ebasnfloats\ndt=1;\ntrajchunk(num,lat,lon,32,'overlap',50);\nmeanfo=vmean(abs(corfreq(col2mat(cell2col(lat)))),1)'*24*dt;\nfr=frac(2*pi,dt*cellength(lat));\nreporttest('TRAJCHUNK overlap',allall(meanfo>32*fr))\n\n% load drifterheyerdahl\n% use drifterheyerdahl\n% \n% [numc,latc]=trajchunk(num,lat,60,'overlap',50);\n% [~,latc2,numc2]=trajchunk(num,flipud(lat),flipud(num),60,'overlap',50);\n% \n% min(cellmin(numc))-min(num)\n% max(cellmax(numc))-max(num)\n% \n% numc{end+1}=flipud(numc2{1});\n% latc{end+1}=flipud(latc2{1});\n% \n% for i=1:length(numc)\n% P(i)=sum(abs(corfreq(latc{i}))*24.*(numc{i}-numc{i}(1))/2/pi/24);\n% end\n% \n% plot(cellmax(numc)-cellmin(numc))\n% plot(60*2*pi./(cellmean(cellabs(corfreq(latc)))*24))\n\n\n\n%length(num),length(cell2col(num))\n\n% with minimum length \n%\n% trajchunk(num,lat,lon,32,35);\n%\n% load drifters\n% use drifters \n% %trajchunk(num,lat,lon,32,'overlap');\n% trajchunk(num,lat,lon,128);\n% \n% %meanfo=zeros(length(num),1);\n% %fr=zeros(length(num),1);\n% \n% %dt=1/4;\n% \n% %Same as below but faster\n% tic\n% meanfo=vmean(abs(corfreq(col2mat(cell2col(lat)))),1)'*24*dt;\n% fr=frac(2*pi,dt*cellength(lat));\n% toc\n% \n% % tic\n% % for i=1:length(num)\n% % meanfo(i)=vmean(abs(corfreq(lat{i})),1)*24*dt;\n% % fr(i)=frac(2*pi,dt*length(lat{i}));\n% % end\n% % toc\n% \n% figure,plot(meanfo,'b.'),hold on,plot(32*fr,'ro')\n% figure,plot(2*pi./(meanfo/32),'b.'),hold on,plot(2*pi./fr,'ro')\n% figure,plot(2*pi./(meanfo/32),2*pi./fr,'ro'),axis equal\n\n", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jOceans/trajchunk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.6970523764245239}} {"text": "function timespvals(options, n, d)\n% TIMESPVALS Measure the performance of SPVALS\n% TIMESPVALS(OPTIONS) Script file to test the performance of the\n% sparse grid interpolation routine SPVALS by measuring the\n% required time to compute the hierarchical surpluses. By default,\n% the Clenshaw-Curtis grid is used. Other grid types can be\n% selected using the SPSET method. \n% \n% TIMESPVALS(OPTIONS, D) argument D contains the dimension that\n% the performance should be measured and graphed for, N\n%\n% Note: This demo takes a couple of minutes to run.\n%\n% See also SPSET, SPVALS, TESTFUNCTIONS.\n\n% Author : Andreas Klimke, Universitaet Stuttgart\n% Version: 1.6\n% Date : May 31, 2006\n\n% ------------------------------------------------------------\n% Sparse Grid Interpolation Toolbox\n% Copyright (c) 2006 W. Andreas Klimke, Universitaet Stuttgart \n% Copyright (c) 2007-2008 W. A. Klimke. All Rights Reserved.\n% See LICENSE.txt for license. \n% email: klimkeas@ians.uni-stuttgart.de\n% web : http://www.ians.uni-stuttgart.de/spinterp\n% ------------------------------------------------------------\n\nif nargin < 1, options = []; end\nif nargin < 2, n = []; d = []; end\n\nsparseIndices = spget(options, 'SparseIndices', 'auto');\ngridtype = spget(options, 'GridType', 'Clenshaw-Curtis');\nenableDCT = spget(options, 'EnableDCT', 'on');\n\nplotasymptotic = 0;\n\n% Set the problem dimensions and the maximum discretization levels\n% for each dimension.\nswitch lower(gridtype)\n case 'clenshaw-curtis'\n if isempty(d)\n d = [1,2,4,8,16];\n n = [17,13,10,6,4];\n end\n if strcmpi(sparseIndices, 'off')\n plotasymptotic = 1;\n end\n case 'noboundary'\n if isempty(d)\n d = [1,2,4,8,16];\n n = [15,11,8,5,4];\n end\n case 'maximum'\n\tif isempty(d)\n d = [1,2,4,8];\n n = [16,12,7,2];\n end\n case 'chebyshev'\n if isempty(d)\n d = [1,2,4,8,16];\n if strcmpi(enableFFT, 'on')\n n = [17,13,10,6,4];\n else\n n = [15,13,10,6,4];\n end\n end\n otherwise\n\terror('Unknown grid type.');\nend\n\nndims = length(n);\nmarkers = ['s', '.', 'd', '+', 'o', 'x', '*', 'v', '^'];\n\n% Compute random constants w and c for Gerz' test functions.\nw = rand(d(end),1);\nc = rand(d(end),1);\nsumc = sum(c,1);\nsumw = sum(w,1);\nc = 1.5.*c/sumc;\nw = w/sumw;\n\ntime = NaN*ones(ndims,n(1)+1);\nnpoints = zeros(ndims,n(1)+1);\n\nfor m = 1:ndims\n\tdisp(['Current dim: ' num2str(d(m))]);\n\tz = [];\n\tfor l = 0:n(m)\n\t\tdisp(['Current level n = ' num2str(l) '...']);\n\t\toptions = spset('MinDepth',l,'MaxDepth',l,'Vectorized','on', ...\n\t\t\t\t\t\t\t\t\t\t'GridType', gridtype, 'EnableDCT', enableDCT, ...\n\t\t\t\t\t\t\t\t\t\t'SparseIndices', sparseIndices, 'PrevResults', z);\n\t\tz = spvals('testfunctions',d(m),[],options,1,c(1:d(m)),w(1: ...\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\td(m)));\n\t\tt = z.surplusCompTime;\n\t\tdisp(['Computing sparse grid points and evaluating function took ' ...\n\t\t\t\t\tnum2str(z.fevalTime) ' [s].']);\n\t\ttime(m,l+1) = t;\n\t\tdisp(['Computing hierarchical surpluses took ' num2str(t) ' [s].']);\n\t\tdisp(' ');\n\t\tnpoints(m,l+1) = z.nPoints;\n\tend\nend\n\n% Plot results\nh = loglog(npoints(:,2:end)', time(:,2:end)', 'LineWidth', 1);\naxis tight;\nfor k = 1:ndims\n\tset(h(k), 'Marker', markers(k));\n\thold on;\nend\naxis manual;\n\n% Plot assymtotic curves for two cases\nif plotasymptotic\n\tfor nd = [1 ndims]\n\t\tasymptotic = zeros(n(nd),1);\n\t\tfor k = 0:n(nd)\n\t\t\tlevelseq = double(spgetseq(k,d(nd))');\n\t\t\tseqpoints = prod((levelseq <= 1) .* 2.^levelseq + ...\n\t\t\t\t\t\t\t\t\t\t\t (levelseq > 1) .* 2.^(levelseq-1));\n\t\t\t\n\t\t\tasymptotic(k+1) = sum((prod(levelseq+1)-1).*seqpoints)*min(n(nd),d(nd));\n\t\t\tif k > 0\n\t\t\t\tasymptotic(k+1) = asymptotic(k+1) + asymptotic(k);\n\t\t\tend\n\t\tend\n\t\tconst = 1./asymptotic(end).*time(nd,n(nd)+1);\n\t\tplot(npoints(nd,1:n(nd)+1),asymptotic.*const,'k--'); \n\tend\nend\n\n% Add legend and axis labels\nhold off;\ntitle(['Time to compute hierarchical surpluses for ' gridtype ' grid']);\nylabel('time [s]');\nxlabel('number of nodes N');\ns = {};\nfor k = 1:ndims\n s{k} = ['d = ' num2str(d(k))];\nend\n\nif plotasymptotic\n\ts{ndims+1} = 'asymptotic';\nend\nlegend(s,2);\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/spinterp/examples/timespvals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.6970523744056469}} {"text": "function h = heaviside(f)\n%HEAVISIDE Heaviside function of a CHEBFUN.\n% HEAVISIDE(F) returns a CHEBFUN which is 0 when F < 0, +1 when F > 0, and\n% 0.5 when F == 0.\n%\n% See also DIRAC, SIGN.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\n% HEAVISIDE() is basically a wrapper for SIGN().\nh = .5*(sign(f) + 1);\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/@chebfun/heaviside.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.6970523711488208}} {"text": "function kmph = ftps2kmph(ftps)\n%FTPS2KMPH Convert speed from feet per second to kilometers per hour\n%\n% kmph = FTPS2KMPH(ftps) converts speeds from feet per second to \n% kilometers per hour.\n%\n% See also FTPS2KTS, FTPS2MPH, FTPS2MPS, KMPH2FTPS.\n\n% Jonathan Sullivan\n% Original: May 2011\n% jonathan.sullivan@ll.mit.edu\n\nkmph = ftps*1.09728;", "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/31665-velocity-conversion-toolbox/ftps2kmph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6970523695869647}} {"text": "function pass = test_parSimp(varargin)\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\nS = loadtests;\n\npass = zeros(numel(S), 1);\nfor k = 1:numel(S)\n str = stringParser.parSimp(S{k}{1});\n pass(k) = strcmp(str,S{k}{2});\nend\n\n\nfunction S = loadtests\n% BVPs\nS{1} = {'((0.02.*diff(u,2)+diff(u))+u)',\n '0.02.*diff(u,2)+diff(u)+u'};\nS{2} = {'((0.01.*diff(u,2)-x.*u)-1)',\n '0.01.*diff(u,2)-x.*u-1'};\nS{3} = {'((x.^(2).*diff(u,2)+x.*diff(u))+(x.^(2)-3.^(2)).*u)',\n 'x.^2.*diff(u,2)+x.*diff(u)+(x.^2-3.^2).*u'};\nS{4} = {'(((0.01.*diff(u,2)+2.*(1-x.^(2)).*u)+u.^(2))-1)',\n '0.01.*diff(u,2)+2.*(1-x.^2).*u+u.^2-1'};\nS{5} = {'((diff(u,2)+(1.2+sign((10-abs(x)))).*u)-1)',\n 'diff(u,2)+(1.2+sign((10-abs(x)))).*u-1'};\nS{6} = {'((diff(u,2)+u)-u.^(2))',\n 'diff(u,2)+u-u.^2'};\nS{7} = {'(diff(u,4)-(diff(u).*diff(u,2)-u.*diff(u,3)))',\n 'diff(u,4)-diff(u).*diff(u,2)+u.*diff(u,3)'};\nS{8} = {'(diff(u,2)+.87.*exp(u))',\n 'diff(u,2)+.87.*exp(u)'};\nS{9} = {'((.0005.*diff(u,2)+x.*(x.^(2)-0.5).*diff(u))+3.*(x.^(2)-0.5).*u)',\n '.0005.*diff(u,2)+x.*(x.^2-0.5).*diff(u)+3.*(x.^2-0.5).*u'};\nS{10} = {'((.01.*diff(u,2)+u.*diff(u))-u)',\n '.01.*diff(u,2)+u.*diff(u)-u'};\nS{11} = {'(diff(u,2)+sin(u))',\n 'diff(u,2)+sin(u)'};\nS{12} = {'((0.05.*diff(u,2)+diff(u).^(2))-1)',\n '0.05.*diff(u,2)+diff(u).^2-1'};\nS{13} = {'(diff(u,2)-8.*sinh(8.*u))',\n 'diff(u,2)-8.*sinh(8.*u)'};\nS{14} = {'(diff(u,2)-(u-1).*(1+diff(u).^(2)).^(1.5))',\n 'diff(u,2)-(u-1).*(1+diff(u).^2).^1.5'};\nS{15} = {'((diff(u,2)-x.*sin(u))-1)',\n 'diff(u,2)-x.*sin(u)-1'};\nS{16} = {'((diff(u,2)-(1-u.^(2)).*diff(u))+u)',\n 'diff(u,2)-(1-u.^2).*diff(u)+u'};\nS{17} = {'(diff(u,2)-sin(v))',\n 'diff(u,2)-sin(v)'};\nS{18} = {'(diff(u,2)-sin(v))',\n 'diff(u,2)-sin(v)'};\nS{19} = {'(cos(u)+diff(v,2))',\n 'cos(u)+diff(v,2)'};\n\n% PDEs\nS{20} = {'+(0.1.*diff(u,2)+diff(u))',\n '0.1.*diff(u,2)+diff(u)'};\nS{21} = {'+((.01.*diff(u,2)+u)-u.^(3))',\n '.01.*diff(u,2)+u-u.^3'};\nS{22} = {'+(-diff(u.^(2))+.02.*diff(u,2))',\n '-diff(u.^2)+.02.*diff(u,2)'};\nS{23} = {'+(-.003.*diff(u,4)+diff((u.^(3)-u),2))',\n '-.003.*diff(u,4)+diff(u.^3-u,2)'};\nS{24} = {'+0.1.*diff(u,2)',\n '0.1.*diff(u,2)'};\nS{25} = {'+(.02.*diff(u,2)+cumsum(u).*sum(u))',\n '.02.*diff(u,2)+cumsum(u).*sum(u)'};\nS{26} = {'+((u.*diff(u)-diff(u,2))-0.006.*diff(u,4))',\n 'u.*diff(u)-diff(u,2)-0.006.*diff(u,4)'};\n\n% Systems\nS{27} = {'+((-u+(x+1).*v)+0.1.*diff(u,2))',\n '-u+(x+1).*v+0.1.*diff(u,2)'};\nS{28} = {'+((u-(x+1).*v)+0.2.*diff(v,2))',\n 'u-(x+1).*v+0.2.*diff(v,2)'};\nS{29} = {'+(0.1.*diff(u,2)-100.*u.*v)',\n '0.1.*diff(u,2)-100.*u.*v'};\nS{30} = {'+(.2.*diff(v,2)-100.*u.*v)',\n '.2.*diff(v,2)-100.*u.*v'};\nS{31} = {'+(0.001.*diff(w,2)+200.*u.*v)',\n '0.001.*diff(w,2)+200.*u.*v'};\nS{32} = {'+(diff(u,2)-v)',\n 'diff(u,2)-v'};\nS{33} = {'(diff(v,2)-u)',\n 'diff(v,2)-u'};\nS{34} = {'+(diff(u,2)+exp(-100.*x.^(2)).*sin(pi.*t))',\n 'diff(u,2)+exp(-100.*x.^2).*sin(pi.*t)'};\n\n% EIGs\nS{35} = {'(diff(u,2)+diff(u))',\n 'diff(u,2)+diff(u)'};\nS{36} = {'(-diff(u,2)+1i.*x.^(2).*u)',\n '-diff(u,2)+1i.*x.^2.*u'};\nS{37} = {'(-.1.*diff(u,2)+4.*(sign((x+1))-sign((x-1))).*u)',\n '-.1.*diff(u,2)+4.*(sign((x+1))-sign((x-1))).*u'};\nS{38} = {'(-diff(u,2)+x.^(2).*u)',\n '-diff(u,2)+x.^2.*u'};\nS{39} = {'(-diff(u,2)+5.*cos(2.*x).*u)',\n '-diff(u,2)+5.*cos(2.*x).*u'};\nS{40} = {'((diff(u,2)+u.*x)+v)',\n 'diff(u,2)+u.*x+v'};\nS{41} = {'(diff(v,2)+sin(x).*u)',\n 'diff(v,2)+sin(x).*u'};\n\n% MISC\n\n% Check exponential notation\nS{42} = {'(diff(v,2)-1e-2*u)',\n 'diff(v,2)-1e-2*u'};\nS{43} = {'(diff(v,2)-1e+2*u)',\n 'diff(v,2)-1e+2*u'};\nS{44} = {'(diff(v,2)+1e-2*u)',\n 'diff(v,2)+1e-2*u'};\nS{45} = {'(diff(v,2)+1e+2*u)',\n 'diff(v,2)+1e+2*u'};\n\n% Check division (see GitHub #2357).\nS{46} = {'diff(y)-(2/3)/4',\n 'diff(y)-2/3/4'};\nS{47} = {'diff(y)-2/(3/4)',\n 'diff(y)-2/(3/4)'};\nS{48} = {'diff(y)-1/(2*(y-1))',\n 'diff(y)-1/(2*(y-1))'};\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebgui/test_parSimp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6970523639873543}} {"text": "% StackExchange Signal Processing Q86094\n% https://dsp.stackexchange.com/questions/86094\n% Analyzing 2 2D Kernels Which Approximates a Gaussian Kernel\n% References:\n% 1. \n% Remarks:\n% 1. B\n% TODO:\n% \t1. C\n% Release Notes Royi Avital RoyiAvital@yahoo.com\n% - 1.0.000 10/01/2023\n% * First release.\n\n\n%% General Parameters\n\nsubStreamNumberDefault = 79;\n\nrun('InitScript.m');\n\nfigureIdx = 0;\nfigureCounterSpec = '%04d';\n\ngenerateFigures = ON;\n\n%% Constants\n\nKERNEL_A = 1; % http://homepages.cwi.nl/~pauldz/\n% Last Revision: December 11, 2000.\n% 2000 Stichting CWI, Amsterdam\n%------------------------------------------------------------------------------\ndenomina = m00(F);\nif denomina == 0\n error(' masscenter - demoninator vanishes ')\nelse\n cx = m10(F)/denomina;\n cy = m01(F)/denomina; \nend\n% whether cx, cy < 0 etc. could be checked here (see above warning).\nif nargout == 1\n c = [cx cy];\nelseif nargout == 2\n c = [cx cy];\n mass = denomina;\nelse\n error(' masscenter - wrong number of output arguments ')\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/13507-lisq-a-toolbox-for-the-lifting-scheme-on-2d-quincunx-grids/LISQ/masscenter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6967998950837969}} {"text": "%% Testing OOQP\nclc\nclear\n\n%% QP1 -2.83333333301227;\nH = speye(3);\nf = -[2 3 1]';\nA = sparse([1 1 1;3 -2 -3; 1 -3 2]); \nb = [1;1;1]; \n\nopts = [];\nopts.display = 2;\n\n[x,fval,e,i,l] = ooqp(H,f,A,-Inf(size(b)),b,[],[],[],[],opts) \n\n%% QP2 -8.22222220552525 \nclc\nH = (sparse([1 -1; -1 2]));\nf = -[2 6]';\nA = sparse([1 1; -1 2; 2 1]);\nb = [2; 2; 3]; \nlb = [0;0];\n\nopts = [];\nopts.display = 2;\n\n[~,fval,e,i] = ooqp(tril(H),f,A,-Inf(size(b)),b,[],[],lb,[],opts)\n\n%% QP3 -6.41379310344827\nH = tril(sparse([1 -1; -1 2]));\nf = -[2 6]';\nA = sparse([1 1; -1 2; 2 1]);\nb = [2; 2; 3];\nAeq = sparse([1 1.5]);\nbeq = 2;\nlb = [0;0];\nub = [10;10]; \n\nopts = [];\nopts.display = 2;\nopts.linear_solver = 'pardiso';\n[x,f,e,i] = ooqp(H,f,A,-Inf(size(b)),b,Aeq,beq,lb,ub,opts)\n\n%% LP1 -3.75\nclc\nH = [];\nf = -[-1, 2]';\nA = sparse([2, 1;-4, 4]);\nb = [5, 5]';\n \nopts = [];\nopts.display = 2;\n[x,f,e,i] = ooqp(H,f,A,-Inf(size(b)),b,[],[],[],[],opts) \n\n%% LP2 3\nclc\nH = [];\nf = [1, 2, 3, 7, 8, 8];\nA = -sparse([5, -3, 2, -3, -1, 2; -1, 0, 2, 1, 3, -3;1, 2, -1, 0, 5, -1]);\nb = -[-5, -1, 3]';\nlb = zeros(6,1);\nub = 10*ones(6,1); \n\nopts = [];\nopts.display = 2;\n[x,f,e,i,l] = ooqp(H,f,-A,-Inf(size(b)),-b,[],[],lb,ub,opts) \n\n%% LP3 4\nclc\nn = 40;\nt = (0:n-1)';\ny = 3.5 -.2*t;\nb = y + 0.5*ones(size(y));\nm = [ones(n,1),t(:)];\nA = sparse([m,-m,eye(n)]);\nH = [];spalloc(44,44,0);\nf = [sum(m),sum(-m),2*ones(1,n)];\nlb = zeros(n+4,1);\nub = [10, 10, 10, 10, 5*ones(1,n)]; \n\nopts = [];\nopts.display = 2;\n[~,f,e,i,l] = ooqp(H,f,-A,-Inf(size(b)),-b,[],[],lb,ub,opts) \n\n%% LARGE LP\nclc\nprob = coinRead('maros-r7.mps');\nopts = optiset('solver','ooqp','display','iter');\nOpt = opti(prob,opts);\n%Solve\n[~,f,e,i] = solve(Opt)\n\n%%\nqp1 = qp_prob(1);\nopts = optiset('solver','ooqp','display','iter');\nOpt = opti(qp1,opts);\n%Solve\n[~,f,e,i] = solve(Opt)\n\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/math/opti/Test Problems/Development/test_ooqp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896132, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6967998882061925}} {"text": "function [nu, U, llh, Ezz, Ezy] = kalmanSmoother(model, X)\n% Kalman smoother (forward-backward algorithm for linear dynamic system)\n% NOTE: This is the exact implementation of the Kalman smoother algorithm in PRML.\n% However, this algorithm is not practical. It is numerical unstable. \n% Input:\n% X: d x n data matrix\n% model: model structure\n% Output:\n% nu: q x n matrix of latent mean mu_t=E[z_t] w.r.t p(z_t|x_{1:T})\n% U: q x q x n latent covariance U_t=cov[z_t] w.r.t p(z_t|x_{1:T})\n% Ezz: q x q matrix E[z_tz_t^T]\n% Ezy: q x q matrix E[z_tz_{t-1}^T]\n% llh: loglikelihood\n% Written by Mo Chen (sth4nth@gmail.com).\nA = model.A; % transition matrix \nG = model.G; % transition covariance\nC = model.C; % emission matrix\nS = model.S; % emision covariance\nmu0 = model.mu0; % prior mean\nP0 = model.P0; % prior covairance\n\nn = size(X,2);\nq = size(mu0,1);\nmu = zeros(q,n);\nV = zeros(q,q,n);\nP = zeros(q,q,n); % C_{t+1|t}\nAmu = zeros(q,n); % u_{t+1|t}\nllh = zeros(1,n);\n\n% forward\nPC = P0*C';\nR = C*PC+S;\nK = PC/R;\nmu(:,1) = mu0+K*(X(:,1)-C*mu0);\nV(:,:,1) = (eye(q)-K*C)*P0;\nP(:,:,1) = P0; % useless, just make a point\nAmu(:,1) = mu0; % useless, just make a point\nllh(1) = logGauss(X(:,1),C*mu0,R);\nfor i = 2:n \n [mu(:,i), V(:,:,i), Amu(:,i), P(:,:,i), llh(i)] = ...\n forwardUpdate(X(:,i), mu(:,i-1), V(:,:,i-1), A, G, C, S);\nend\nllh = sum(llh);\n% backward\nnu = zeros(q,n);\nU = zeros(q,q,n);\nEzz = zeros(q,q,n);\nEzy = zeros(q,q,n-1);\n\nnu(:,n) = mu(:,n);\nU(:,:,n) = V(:,:,n);\nEzz(:,:,n) = U(:,:,n)+nu(:,n)*nu(:,n)';\nfor i = n-1:-1:1 \n [nu(:,i), U(:,:,i), Ezz(:,:,i), Ezy(:,:,i)] = ...\n backwardUpdate(nu(:,i+1), U(:,:,i+1), mu(:,i), V(:,:,i), Amu(:,i+1), P(:,:,i+1), A);\nend\n\nfunction [mu1, V1, Amu, P, llh] = forwardUpdate(x, mu0, V0, A, G, C, S)\nk = numel(mu0);\nP = A*V0*A'+G; % 13.88\nPC = P*C';\nR = C*PC+S;\nK = PC/R; % 13.92\nAmu = A*mu0;\nCAmu = C*Amu;\nmu1 = Amu+K*(x-CAmu); % 13.89\nV1 = (eye(k)-K*C)*P; % 13.90\nllh = logGauss(x,CAmu,R); % 13.91\n\n\nfunction [nu0, U0, E00, E10] = backwardUpdate(nu1, U1, mu, V, Amu, P, A)\nJ = V*A'/P; % 13.102\nnu0 = mu+J*(nu1-Amu); % 13.100\nU0 = V+J*(U1-P)*J'; % 13.101\nE00 = U0+nu0*nu0'; % 13.107\nE10 = U1*J'+nu1*nu0'; % 13.106 \n", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter13/LDS/kalmanSmoother.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6967998724312255}} {"text": "function K = compute_cubic_spline_kernel(x,y);\nnx = size(x,1);\nny = size(y,1);\nKmax = max(repmat(abs(x),1,ny),repmat(abs(y)',nx,1) );\nKmin = min(repmat(abs(x),1,ny),repmat(abs(y)',nx,1) );\nK = Kmin .* Kmin .* ( 3 * Kmax - Kmin );\nK = K .* ( x*y' > 0 );\n \n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/hkl-3.0/compute_cubic_spline_kernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6967788706393471}} {"text": "% Degree-preserving random rewiring.\n% Every rewiring decreases the assortativity (pearson coefficient).\n%\n% Note 1: There are rare cases of neutral rewiring (pearson coefficient stays the same within numerical error).\n% Note 2: Assume unweighted undirected graph.\n%\n% INPUTS: edge list, el and number of rewirings, k (integer)\n% OUTPUTS: rewired edge list\n%\n% Other routines used: degrees.m, edgeL2adj.m\n% GB: last updated, Sep 27 2012\n\nfunction el = rewireDisassort(el,k)\n\n[deg,~,~]=degrees(edgeL2adj(el));\n\nrew=0;\n\nwhile rew0; continue; end % the two edges cannot overlap\n\n nodes=[edge1(1) edge1(2) edge2(1) edge2(2)];\n [~,Y]=sort(deg(nodes));\n \n % connect nodes(Y(1))-nodes(Y(4)) and nodes(Y(2))-nodes(Y(3))\n if ismember([nodes(Y(1)),nodes(Y(4)),1],el,'rows') || ismember([nodes(Y(2)),nodes(Y(3)),1],el,'rows'); continue; end \n \n el(ind(1),:)=[nodes(Y(1)),nodes(Y(4)),1];\n el(ind(2),:)=[nodes(Y(2)),nodes(Y(3)),1];\n \n [~,inds1] = ismember([edge1(2),edge1(1),1],el,'rows');\n el(inds1,:)=[nodes(Y(4)),nodes(Y(1)),1];\n \n [~,inds2] = ismember([edge2(2),edge2(1),1],el,'rows');\n el(inds2,:)=[nodes(Y(3)),nodes(Y(2)),1];\n \n rew=rew+1;\n \nend", "meta": {"author": "aeolianine", "repo": "octave-networks-toolbox", "sha": "e70f79eb62a54ef96934d900830f9177caf732c9", "save_path": "github-repos/MATLAB/aeolianine-octave-networks-toolbox", "path": "github-repos/MATLAB/aeolianine-octave-networks-toolbox/octave-networks-toolbox-e70f79eb62a54ef96934d900830f9177caf732c9/rewireDisassort.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6967788658441529}} {"text": "function [s_true,e_spat,e_interf,e_artif]=bss_decomp_mtifilt(se,S,j,L)\n\n% BSS_DECOMP_MTIFILT Decomposition of an estimated source image into four\n% components representing respectively the true source image, spatial (or\n% filtering) distortion, interference and artifacts, derived from the true\n% source images using multichannel time-invariant filters.\n%\n% [s_true,e_spat,e_interf,e_artif]=bss_decomp_mtifilt(se,S,j,L)\n%\n% Inputs:\n% se: I x T matrix containing the estimated source image (one row per channel)\n% S: I x T x J matrix containing the true source images\n% j: source index corresponding to the estimated source image in S\n% L: length of the multichannel time-invariant filters in samples\n%\n% Outputs:\n% s_true: I x T matrix containing the true source image, i.e. S(:,:,j) (one row per channel)\n% e_spat: I x T matrix containing the spatial (or filtering) distortion component\n% e_interf: I x T matrix containing the interference component\n% e_artif: I x T matrix containing the artifacts component\n\n%%% Errors %%%\nif nargin<4, error('Not enough input arguments.'); end\n[Ie,Te]=size(se);\n[I,T,J]=size(S);\nif I~=Ie, error('The number of channels of the true source images and the estimated source image must be equal.'); end\nif T~=Te, error('The duration of the true source images and the estimated source image must be equal.'); end\n\n%%% Decomposition %%%\n% True source image\ns_true=[S(:,:,j),zeros(I,L-1)];\n% Spatial (or filtering) distortion\ne_spat=project(se,S(:,:,j),L)-s_true;\n% Interference\ne_interf=project(se,S,L)-s_true-e_spat;\n% Artifacts\ne_artif=[se,zeros(I,L-1)]-s_true-e_spat-e_interf;\n\nreturn;\n\n\n\nfunction sproj=project(se,S,L)\n\n% Least-squares projection of each channel of se on the subspace spanned by\n% delayed versions of the channels of S, with delays between 0 and L-1\n\n[I,T,J]=size(S);\nS=reshape(permute(S,[1 3 2]),I*J,T);\n\n%%% Computing coefficients of least squares problem via FFT %%%\n% Zero padding and FFT of input data\nS=[S,zeros(I*J,L-1)];\nse=[se,zeros(I,L-1)];\nN=2^nextpow2(T+L-1);\nSf=fft(S,N,2);\nsef=fft(se,N,2);\n% Inner products between delayed versions of S\nG=zeros(I*J*L);\nfor k1=0:I*J-1\n for k2=0:k1\n SSf=Sf(k1+1,:).*conj(Sf(k2+1,:));\n SSf=real(ifft(SSf));\n SS=toeplitz(SSf([1 N:-1:N-L+2]),SSf(1:L));\n G(k1*L+1:k1*L+L,k2*L+1:k2*L+L)=SS;\n G(k2*L+1:k2*L+L,k1*L+1:k1*L+L)=SS.';\n end\nend\n% Inner products between se and delayed versions of S\nD=zeros(I*J*L,I);\nfor k=0:I*J-1\n for i=1:I\n Ssef=Sf(k+1,:).*conj(sef(i,:));\n Ssef=real(ifft(Ssef,[],2));\n D(k*L+1:k*L+L,i)=Ssef(:,[1 N:-1:N-L+2]).';\n end\nend\n\n%%% Computing projection %%%\n% Distortion filters\nC=G\\D;\nC=reshape(C,L,I*J,I);\n% Filtering\nsproj=zeros(I,T+L-1);\nfor k=1:I*J\n for i=1:I\n sproj(i,:)=sproj(i,:)+fftfilt(C(:,k,i).',S(k,:));\n end\nend\n\nreturn;", "meta": {"author": "KyleZhang1118", "repo": "Voice-Separation-and-Enhancement", "sha": "77d16c120356dbbca3ee768d293df5d743d343ad", "save_path": "github-repos/MATLAB/KyleZhang1118-Voice-Separation-and-Enhancement", "path": "github-repos/MATLAB/KyleZhang1118-Voice-Separation-and-Enhancement/Voice-Separation-and-Enhancement-77d16c120356dbbca3ee768d293df5d743d343ad/bss_decomp_mtifilt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6967788647828054}} {"text": "function [steep] = steep(B,V,C,s,o,d)\n%Steepest ascent/descent is a simple and efficient optimization method based on\n% statistical design of experiments.\n% In order to optimize a response with respect to a set of quantitative variables,\n% often by using sequential experimentation, we use polynomial models to approximate\n% the response surface. The process often begins by using a 2^p factorial design with\n% additional center points, then fitting a first-order model. If curvature is detected\n% (lack of fit to the first-order model), then we conclude that we are near the optimum\n% and add points to obtain a second-order design. If curvature is not detected, we are\n% far from the optimum and use the method of steepest ascent/descent to get points \n% headed (hopefully) toward to optimum. As we recognize that we are near the optimum, \n% we use a second-order design. \n% If there is no lack-of-fit then the linear model seems to approximate the response \n% surface in this region, which means we are far from an optimum. In this case we want\n% to obtain additional responses (design points) that go closer to the optimum. To do\n% this we use the method of steepest ascent/descent, which just means that future design\n% points should increase/decrease the levels of IV's (factors) in proportion to b's until\n% we are near the optimum response (maximum or minimum).\n% We know that to maximize/minimize a response, the movement of the design center must \n% be in the direction of the directional derivatives of the response function, that is,\n% in the direction of\n%\n% df/dx = df/dx_1, . . .,df/dx_p .\n%\n% We then multiply by a constant A so that\n%\n% Dx = A*df/dx,\n% where\n%\n% A = R/sqrt(Sum(df/dx_i)^2) .\n%\n% Thus,\n%\n% Sum(Dx_i^2) = R^2 .\n%\n% For a first order model,\n%\n% df/dx_i = b_i .\n%\n% So,\n%\n% Dx_i = A*b_i and A = R/sqrt(Sum(b_i^2)) .\n%\n% From this we see that the movement of x_i up the path of steepest ascent/descent \n% is proportional to b_i. Since this is the case it is easier not to pick particular \n% values of R but rather fix a value of b_i and make the other changes proportional\n% to it. \n%\n% Gradient vector\n% | ^\n% | \\ \\ \\/ O\n% |\\ \\ \\ /\\ New\\\n% | \\ \\ \\ / O trials\n% x_2 | \\ \\ / \\ \\\n% | \\ O--\\----\\O \\ \\\n% | \\| Start | \\ \\\n% | | design |\\ \\ \\\n% | O\\----\\--O \\ \\ \\\n% |_ _ _ _\\_ _ \\_ _ \\_ _ \\_ _ \\_ _ \n% x_1\n% \n% First-order response surface and path of steepest ascent. \n%\n% Thus, the goal is to optimize the response variable Y. It is assumed that the\n% factors are continuous and controllable by the experimenter with negligible error.\n% If b_1, b_2,...,b_p are the parameters and observed response is Y then the parameter\n% of the polynomial is estimated by method of least squares.\n% The method of steepest ascent/descent is followed to reach the optimun point where\n% best surface is obtained. That is direction of the maximum increase/minimum decrease\n% of the response in the case of surface finish cosiderations. Direction of steep Y is \n% increasing/decreasing. Experiments are conducted along the path of steepest \n% ascent/descent until no further decrease in response is observed. Then a new \n% first-order model may be fit, a new path of steepest ascent/descent determined the\n% procedure continues. Eventually the vicinity of optimum is arrived. \n% \n% Syntax: steep(B,V,C,s,o,d) \n% \n% Inputs:\n% B - vector of regression coefficients (parameters) of the fitted linear equation\n% (first order): [intercept (1), linear (p)]. It must to be enter in that \n% strictly order.\n% V - vector of the factor values at starting point (current factor setting).\n% C - vector of units increment chosen between the low and medium levels and \n% between the medium and high levels for each parameter.\n% s - number of interested steps.\n% o - change relative to one unit change regarding to the maximum absolute \n% parameter [o = 1 (default)] or parameter choice by experimenter (o = 2).\n% d - steepest ascent [d = 1 (default)] or descent (d = 2) procedure. \n%\n% Outputs:\n% A complete summary of the estimation of the selected direction of the\n% selected steepest method.\n%\n% To see the procedure consider the following example taken from Montgomery DOX 5E \n% (Example 11-1, pg. 431). Based on the fitted first-order model,\n% y = 40.44 + 0.775*x1 + 0.325*x2\n% with actual factor-values on the origin of 35 and 155 for time-reaction (min) and\n% temperature (oF) and step size of 5 and 5, respectively. We are interested to obtain\n% the predicted response by the steepest ascent metod for 12 steps.\n%\n% Input data must be:\n% B=[40.44 0.775 0.325];\n% V=[35 155];\n% C=[5 2];\n% s = 12;\n% o = 1;\n% d = 1;\n%\n% Calling on Matlab the function: \n% steep(B,V,C,s,o,d)\n%\n% Answer is:\n%\n% Estimation of the selected direction of steepest ascent.\n% The interested steps were 12\n% Leading from the center of the design region the operating point for the IV, 2\n% --------------------------------------------------------------------------------------------------------------\n% Run Operating point Predicted response \n% --------------------------------------------------------------------------------------------------------------\n% 0 35.000 155.000 40.440\n% 1 40.000 157.097 41.351\n% 2 45.000 159.194 42.263\n% 3 50.000 161.290 43.174\n% 4 55.000 163.387 44.085\n% 5 60.000 165.484 44.996\n% 6 65.000 167.581 45.908\n% 7 70.000 169.677 46.819\n% 8 75.000 171.774 47.730\n% 9 80.000 173.871 48.642\n% 10 85.000 175.968 49.553\n% 11 90.000 178.065 50.464\n% 12 95.000 180.161 51.375\n% --------------------------------------------------------------------------------------------------------------\n%\n% Created by A. Trujillo-Ortiz, R. Hernandez-Walls, A. Castro-Perez and\n% F.J. Marquez-Rocha\n% Facultad de Ciencias Marinas\n% Universidad Autonoma de Baja California\n% Apdo. Postal 453\n% Ensenada, Baja California\n% Mexico.\n% atrujo@uabc.mx\n% And the special collaboration of the post-graduate students of the 2005:1\n% Multivariate Statistics Course: Cesar Orlando Chavira-Ortega, Alfredo Frias-Velasco,\n% and Herlinda Gomez-Villa.\n% Copyright (C) May 20, 2005.\n%\n% To cite this file, this would be an appropriate format:\n% Trujillo-Ortiz, A., R. Hernandez-Walls, A. Castro-Perez, F.J Marquez-Rocha,\n% C.O. Chavira-Ortega, A. Frias-Velasco and H. Gomez-Villa. (2005). steep:\n% Steepest ascent/descent as a simple and efficient optimization method based\n% on statistical design of experiments. A MATLAB file. [WWW document]. URL \n% http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=7737\n%\n% References:\n% \n% Box, G. E. P. and Draper, N. R. (1987), Empirical Model-Building and Response Surfaces. \n% John Wiley & Sons: New York.\n% Box, G. E. P. and Wilson, K. B. (1951), On the Experimental Attainment of Optimum\n% Conditions. J. Royal Stat. Soc. Ser. B., 13:1-45.\n% Montgomery, D. C. (2001), Design and Analysis of Experiments, 5th Ed., John Wiley & Sons: New York.\n% Myers, R. H. and Montgomery, D. C. (2002), Response Surface Methodology: Process and\n% Product Optimization Using Designed Experiments. 2nd. Ed., John Wiley & Sons: New York.\n%\n\nif nargin < 6,\n d = 1 %(deafault);\nend;\n\nif nargin < 5,\n o = 1 %(deafault);\nend;\n\nb = B(2:end);\nb = b(:); %vector of from coded regression model\nV = V(:); %base level (center point)\nC = C(:); %unit change\ns = s; %\nv = length(B)-1; %number of independent variables\n\nif o == 1,\n f = max(abs(b));\nelse (o == 2),\n l = input('Give me the interested factor: ');\n f = b(l);\nend;\n\nS = [];\nfor i = 0:s,\n if d == 1; %steepest ascent\n x = [V + i*diag(b./f*C')];\n else (d == 2); %steepest descent\n x = [V - i*diag(b./f*C')];\n end;\n S = [S x];\nend;\n\nS = S';\nV = V';\n[m n] = size(S);\nO = (S - repmat(V,m,1))./repmat(C',m,1);\n\nY = B(1)+O*b;\n\nT = [];\nfor i = 0:s,\n T = [T;i];\nend;\n\nif d == 1;\n d = 'ascent.';\nelse (d == 2);\n d = 'descent.';\nend;\n \n[nul,fs] = size(S);\nform = ['%12.3f '];\nform2 = [' Run '];\nform3 = [' Predicted response '];\nfor k = 2:fs,\n form = [form '%12.3f '];\n form2 = [form2 ' '];\n form3 = [' ' form3];\nend;\nRR = [T S Y];\n\ndisp(' ')\nfprintf('Estimation of the selected direction of steepest %s\\n',d);\nfprintf('The interested steps were %i\\n',s);\nfprintf('Leading from the center of the design region the operating point for the IV, %i\\n',v);\nfprintf('--------------------------------------------------------------------------------------------------------------\\n');\ndisp([form2 ' Operating point ' form3])\nfprintf('--------------------------------------------------------------------------------------------------------------\\n');\nffa=['%4i ' form ' %16.3f\\n'];\nfprintf(ffa,RR');\nfprintf('--------------------------------------------------------------------------------------------------------------\\n');\ndisp(' ')\n\nreturn,", "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/7737-steep/steep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6967788582059453}} {"text": "% This is a demo for segmentation using local gaussian distribution (LGD)\n% fitting energy\n%\n% Reference:
  • \n%\n% Please DO NOT distribute this code to anybody.\n% Copyright (c) by Li Wang\n%\n% Author: Li Wang\n% E-mail: li_wang@med.unc.edu\n% URL: http://www.unc.edu/~liwa/\n%\n% 2010-01-02 PM\n\n\nclc;clear all;close all;\n\nImg=imread('2.bmp');\nImg = double(Img(:,:,1));\n\nNumIter = 1000; %iterations\ntimestep=0.1; %time step\nmu=0.1/timestep;% level set regularization term, please refer to \"Chunming Li and et al. Level Set Evolution Without Re-initialization: A New Variational Formulation, CVPR 2005\"\nsigma = 5;%size of kernel\nepsilon = 1;\nc0 = 2; % the constant value \nlambda1=1.05;%outer weight, please refer to \"Chunming Li and et al, Minimization of Region-Scalable Fitting Energy for Image Segmentation, IEEE Trans. Image Processing, vol. 17 (10), pp. 1940-1949, 2008\"\nlambda2=1.0;%inner weight\n%if lambda1>lambda2; tend to inflate\n%if lambda1=tt(i))');\n conc=bsxfun(@times,bsxfun(@gt,crit(:,i),crit(:,i)'),comp);\n at(i,1)=sum(conc(:))./sum(comp(:));\nend\n\nend\n\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/diag/auct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6967749988835749}} {"text": "close all;\nclear all;\nclc;\n\n\nload('bin/omp_vs_gomp_comparison.mat');\n\nmf = spx.graphics.Figures();\n\nmf.new_figure('Iterations');\n\nlengends = cell(5, 1);\nlengends{1} = 'OMP';\nfor nl=1:num_ls\n lengends{nl+1} = sprintf('GOMP-%d', Ls(nl));\nend\nhold all;\n\nplot(Ks, omp_average_iterations_with_k(Ks));\nfor nl=1:num_ls\n plot(Ks, gomp_average_iterations_with_k(Ks, nl));\nend\nxlabel('Sparsity level');\nylabel('Average iterations');\nlegend(lengends);\ngrid on;\n\nmf.new_figure('Success rate');\nhold all;\nplot(Ks, omp_success_rates_with_k(Ks));\nfor nl=1:num_ls\n plot(Ks, gomp_success_rates_with_k(Ks, nl));\nend\nxlabel('Sparsity level');\nylabel('Success rates');\nlegend(lengends);\ngrid on;\n\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/experiments/gomp/print_compare_algorithms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.6967393520353263}} {"text": "function len = edgeLength3d(edge, varargin)\n%EDGELENGTH3D Return the length of a 3D edge.\n%\n% L = edgeLength3D(EDGE); \n% Returns the length of a 3D edge, with following representation:\n% [x1 y1 z1 x2 y2 z2].\n%\n% Example\n% p1 = [1 1 1];\n% p2 = [3 4 5];\n% edge = createEdge3d(p1, p2);\n% edgeLength3d(edge)\n% ans =\n% 5.3852\n% \n% See also\n% edges3d, createEdge3d, drawEdge3d\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2018-08-29, using Matlab 9.4.0.813654 (R2018a)\n% Copyright 2018 INRA - Cepia Software Platform.\n\nif nargin == 1\n dp = edge(:, 4:6) - edge(:, 1:3);\nelse\n dp = varargin{1} - edge;\nend\n\nlen = hypot(hypot(dp(:,1), dp(:,2)), dp(:,3));\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/edgeLength3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.6967393462073161}} {"text": "function checkNNGradients(lambda)\n%CHECKNNGRADIENTS Creates a small neural network to check the\n%backpropagation gradients\n% CHECKNNGRADIENTS(lambda) Creates a small neural network to check the\n% backpropagation gradients, it will output the analytical gradients\n% produced by your backprop code and the numerical gradients (computed\n% using computeNumericalGradient). These two gradient computations should\n% result in very similar values.\n%\n\nif ~exist('lambda', 'var') || isempty(lambda)\n lambda = 0;\nend\n\ninput_layer_size = 3;\nhidden_layer_size = 5;\nnum_labels = 3;\nm = 5;\n\n% We generate some 'random' test data\nTheta1 = debugInitializeWeights(hidden_layer_size, input_layer_size);\nTheta2 = debugInitializeWeights(num_labels, hidden_layer_size);\n% Reusing debugInitializeWeights to generate X\nX = debugInitializeWeights(m, input_layer_size - 1);\ny = 1 + mod(1:m, num_labels)';\n\n% Unroll parameters\nnn_params = [Theta1(:) ; Theta2(:)];\n\n% Short hand for cost function\ncostFunc = @(p) nnCostFunction(X,y,p,input_layer_size, hidden_layer_size, ...\n num_labels,lambda);\n\n[cost, grad] = costFunc(nn_params);\nnumgrad = computeNumericalGradient(costFunc, nn_params);\n\n% Visually examine the two gradient computations. The two columns\n% you get should be very similar. \ndisp([numgrad grad]);\nfprintf(['The above two columns you get should be very similar.\\n' ...\n '(Left-Your Numerical Gradient, Right-Analytical Gradient)\\n\\n']);\n\n% Evaluate the norm of the difference between two solutions. \n% If you have a correct implementation, and assuming you used EPSILON = 0.0001 \n% in computeNumericalGradient.m, then diff below should be less than 1e-9\ndiff = norm(numgrad-grad)/norm(numgrad+grad);\n\nfprintf(['If your backpropagation implementation is correct, then \\n' ...\n 'the relative difference will be small (less than 1e-9). \\n' ...\n '\\nRelative Difference: %g\\n'], diff);\n\nend\n", "meta": {"author": "ShiMengjie", "repo": "Machine-Learning-Andrew-Ng", "sha": "2f54790e33dc538aea1534f40342791fb7c3abb1", "save_path": "github-repos/MATLAB/ShiMengjie-Machine-Learning-Andrew-Ng", "path": "github-repos/MATLAB/ShiMengjie-Machine-Learning-Andrew-Ng/Machine-Learning-Andrew-Ng-2f54790e33dc538aea1534f40342791fb7c3abb1/matlab/ex4/checkNNGradients.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.6967393392830682}} {"text": "function linplus_test48 ( )\n\n%*****************************************************************************80\n%\n%% TEST48 tests R8PBU_ML.\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 n = 10;\n mu = 3;\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST48\\n' );\n fprintf ( 1, ' R8PBU_ML computes A*x\\n' );\n fprintf ( 1, ' where A has been factored by R8PBU_FA.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix order N = %d\\n', n );\n fprintf ( 1, ' Upper bandwidth MU = %d\\n', mu );\n%\n% Set the matrix.\n%\n [ a, seed ] = r8pbu_random ( n, mu, seed );\n%\n% Set the desired solution.\n%\n x = r8vec_indicator ( n );\n%\n% Compute the corresponding right hand side.\n%\n b = r8pbu_mxv ( n, mu, a, x );\n%\n% Factor the matrix.\n%\n [ a_lu, info ] = r8pbu_fa ( n, mu, a );\n\n if ( info ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Fatal error!\\n' );\n fprintf ( 1, ' R8PBU_FA declares the matrix is singular!\\n' );\n fprintf ( 1, ' The value of INFO is %d\\n', info );\n return\n end\n%\n% Now multiply factored matrix times solution to get right hand side again.\n%\n b2 = r8pbu_ml ( n, mu, a_lu, x );\n\n r8vec2_print_some ( n, b, b2, 10, ' A*x and PLU*x' );\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/linplus_test48.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.6967393325836445}} {"text": "function fem2d_scalar_display ( prefix )\n\n%*****************************************************************************80\n%\n%% FEM2D_SCALAR_DISPLAY creates surface plots of 2D FEM scalar data.\n%\n% Discussion:\n%\n% This program assumes that you have computed the value of some scalar\n% quantity (such as pressure or temperature) at a set of nodes.\n%\n% You may have determined an order 3 triangulation of these nodes,\n% but if you have not, the program will work that out internally.\n%\n% This program can read that data, and display a color contour of the \n% solution data.\n%\n% Usage:\n%\n% fem2d_scalar_display ( 'prefix' )\n%\n% where\n%\n% * 'prefix'_nodes.txt contains the node coordinates;\n% * 'prefix'_elements.txt contains the element definitions \n% (this file is optional, and if missing, the elements will be generated\n% by the program);\n% * 'prefix'_values.txt contains the nodal values.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 November 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string PREFIX, the common file prefix.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM2D_SCALAR_DISPLAY:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Surface plot of a scalar U(X,Y) on a triangulated region.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' This program expects three input files:\\n' );\n fprintf ( 1, ' * a node file, the node coordinates,\\n' );\n fprintf ( 1, ' * an element file, triples of nodes that form elements,\\n' );\n fprintf ( 1, ' * a value file, solution values.\\n' );\n%\n% The command line argument is the common filename prefix.\n%\n if ( nargin < 1 )\n\n fprintf ( 1, '\\n' );\n\n prefix = input ( ...\n 'Please enter the filename prefix:' );\n\n end\n%\n% Create the filenames.\n%\n node_filename = strcat ( prefix, '_nodes.txt' );\n element_filename = strcat ( prefix, '_elements.txt' );\n value_filename = strcat ( prefix, '_values.txt' );\n%\n% Read the node data.\n%\n [ dim_num, node_num ] = r8mat_header_read ( node_filename );\n\n% fprintf ( 1, '\\n' );\n% fprintf ( 1, ' Read the header of \"%s\".', node_filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial dimension DIM_NUM = %d\\n', dim_num );\n fprintf ( 1, ' Number of points NODE_NUM = %d\\n', node_num );\n\n if ( dim_num ~= 2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM2D_SCALAR_DISPLAY - Fatal error!\\n' );\n fprintf ( 1, ' Dataset must have spatial dimension 2.\\n' );\n error ( 'FEM2D_SCALAR_DISPLAY - Fatal error!' );\n end\n\n node_xy = r8mat_data_read ( node_filename, dim_num, node_num );\n\n% fprintf ( 1, '\\n' );\n% fprintf ( 1, ' Read the data in \"%s\".\\n', node_filename );\n\n% r8mat_transpose_print_some ( dim_num, node_num, node_xy, 1, 1, dim_num, 5, ...\n% ' First 5 nodes:' );\n%\n% Read or create the element data.\n%\n if ( file_exist ( element_filename ) )\n\n [ element_order, element_num ] = i4mat_header_read ( ...\n element_filename );\n\n if ( element_order ~= 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM2D_SCALAR_DISPLAY - Fatal error!\\n' );\n fprintf ( 1, ' Data is not for a 3-node triangulation.\\n' );\n error ( 'FEM2D_SCALAR_DISPLAY - Fatal error!' );\n end\n\n% fprintf ( 1, '\\n' );\n% fprintf ( 1, ' Read the header of \"%s\".\\n', ...\n% element_filename );\n% fprintf ( 1, '\\n' );\n fprintf ( 1, ' Element order = %d\\n', element_order );\n fprintf ( 1, ' Number of elements ELEMENT_NUM = %d\\n', ...\n element_num );\n\n element_node = i4mat_data_read ( element_filename, ...\n element_order, element_num );\n\n% fprintf ( 1, '\\n' );\n% fprintf ( 1, ' Read the data in \"%s\".\\n', element_filename );\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Creating triangulation for data.\\n' );\n element_node = delaunayn ( node_xy' );\n element_node = element_node';\n [ element_order, element_num ] = size ( element_node );\n i4mat_write ( element_filename, element_order, element_num, element_node );\n fprintf ( 1, ' Triangulation data written to \"%s\".\\n', element_filename );\n end\n\n% i4mat_transpose_print_some ( element_order, element_num, ...\n% element_node, 1, 1, element_order, 10, ...\n% ' First 10 elements:' );\n%\n% Detect and correct 0-based indexing.\n%\n element_node = mesh_base_one ( node_num, element_order, element_num, ...\n element_node );\n%\n% Read the values.\n%\n [ value_dim, value_num ] = r8mat_header_read ( value_filename );\n\n% fprintf ( 1, '\\n' );\n% fprintf ( 1, ' Read the header of \"%s\".', value_filename );\n% fprintf ( 1, '\\n' );\n% fprintf ( 1, ' Spatial dimension = %d\\n', value_dim );\n% fprintf ( 1, ' Number of values = %d\\n', value_num );\n\n if ( value_dim ~= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM2D_SCALAR_DISPLAY - Fatal error!\\n' );\n fprintf ( 1, ' VALUE data must be scalar.\\n' );\n error ( 'FEM2D_SCALAR_DISPLAY - Fatal error!' );\n end\n\n value = r8mat_data_read ( value_filename, value_dim, value_num );\n%\n% Call TRISURF to plot the data.\n%\n trisurf ( element_node', node_xy(1,:)', node_xy(2,:)', value', ...\n 'Edgecolor', 'None' )\n\n xlabel ( '<---X--->', 'Fontsize', 16 );\n ylabel ( '<---Y--->', 'Fontsize', 16 );\n zlabel ( '<---U(X,Y)--->', 'Fontsize', 16 );\n title ( prefix, 'Fontsize', 24 );\n%\n% Save it as a PNG file.\n%\n png_filename = strcat ( prefix, '.png' );\n print ( '-dpng', png_filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Saving a PNG version of plot as \"%s\"\\n', png_filename );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM2D_SCALAR_DISPLAY:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction column_num = file_column_count ( input_file_name )\n\n%*****************************************************************************80\n%\n%% FILE_COLUMN_COUNT counts the columns in the first line of a file.\n%\n% Discussion:\n%\n% The file is assumed to be a simple text file.\n%\n% Most lines of the file are presumed to consist of COLUMN_NUM words,\n% separated by spaces. There may also be some blank lines, and some \n% comment lines, which have a \"#\" in column 1.\n%\n% The routine tries to find the first non-comment non-blank line and\n% counts the number of words in that line.\n%\n% If all lines are blanks or comments, it goes back and tries to analyze\n% a comment line.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 21 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILE_NAME, the name of the file.\n%\n% Output, integer COLUMN_NUM, the number of columns in the file.\n%\n FALSE = 0;\n TRUE = 1;\n%\n% Open the file.\n%\n input_unit = fopen ( input_file_name );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_COLUMN_COUNT - Error!\\n' );\n fprintf ( 1, ' Could not open the file \"%s\".\\n', input_file_name );\n error ( 'FILE_COLUMN_COUNT - Error!' );\n end\n%\n% Read one line, but skip blank lines and comment lines.\n% Use FGETL so we drop the newline character!\n%\n got_one = FALSE;\n\n while ( 1 )\n\n line = fgetl ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n if ( s_len_trim ( line ) == 0 )\n\n elseif ( line(1) == '#' )\n\n else\n got_one = TRUE;\n break;\n end\n\n end\n\n fclose ( input_unit );\n\n if ( got_one == FALSE ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_COLUMN_COUNT - Warning!\\n' );\n fprintf ( 1, ' The file does not seem to contain any data.\\n' );\n column_num = -1;\n return;\n end\n\n column_num = s_word_count ( line );\n\n return\nend\nfunction value = file_exist ( file_name )\n\n%*****************************************************************************80\n%\n%% FILE_EXIST reports whether a file exists.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, character FILE_NAME, the name of the file.\n%\n% Output, logical FILE_EXIST, is TRUE if the file exists.\n%\n fid = fopen ( file_name );\n\n if ( fid == -1 ) \n value = 0;\n else\n fclose ( fid );\n value = 1;\n end\n\n return\nend\nfunction row_num = file_row_count ( input_file_name )\n\n%*****************************************************************************80\n%\n%% FILE_ROW_COUNT counts the number of row records in a file.\n%\n% Discussion:\n%\n% Each input line is a \"RECORD\".\n%\n% The records are divided into three groups:\n% \n% * BLANK LINES (nothing but blanks)\n% * COMMENT LINES (begin with a '#')\n% * DATA RECORDS (anything else)\n%\n% The value returned by the function is the number of data records.\n%\n% By the way, if the MATLAB routine FGETS is used, instead of\n% FGETL, then the variable LINE will include line termination \n% characters, which means that a blank line would not actually\n% have zero characters.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 31 December 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILE_NAME, the name of the input file.\n%\n% Output, integer ROW_NUM, the number of rows found. \n%\n input_unit = fopen ( input_file_name );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_ROW_COUNT - Error!\\n' );\n fprintf ( 1, ' Could not open the file \"%s\".\\n', input_file_name );\n error ( 'FILE_ROW_COUNT - Error!' );\n end\n\n blank_num = 0;\n comment_num = 0;\n row_num = 0;\n \n record_num = 0;\n\n while ( 1 )\n\n line = fgetl ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n record_num = record_num + 1;\n record_length = s_len_trim ( line );\n \n if ( record_length <= 0 )\n blank_num = blank_num + 1;\n elseif ( line(1) == '#' )\n comment_num = comment_num + 1;\n else\n row_num = row_num + 1;\n end\n\n end\n\n fclose ( input_unit );\n\n return\nend\nfunction table = i4mat_data_read ( input_filename, m, n )\n\n%*****************************************************************************80\n%\n%% I4MAT_DATA_READ reads data from an I4MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 January 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Input, integer M, N, the number of rows and columns in the data.\n%\n% Output, integer TABLE(M,N), the point coordinates.\n%\n table = zeros ( m, n );\n%\n% Build up the format string for reading M real numbers.\n%\n string = ' ';\n\n for i = 0 : m\n string = strcat ( string, ' %d' );\n end\n\n input_unit = fopen ( input_filename );\n\n if ( input_unit < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_DATA_READ - Error!\\n' );\n fprintf ( 1, ' Could not open the input file.\\n' );\n error ( 'I4MAT_DATA_READ - Error!' );\n end\n\n i = 0;\n\n while ( i < n )\n\n line = fgets ( input_unit );\n\n if ( line == -1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_DATA_READ - Error!\\n' );\n fprintf ( 1, ' End of input while reading data.\\n' );\n error ( 'I4MAT_DATA_READ - Error!' );\n end\n\n if ( line(1) == '#' )\n\n elseif ( s_len_trim ( line ) == 0 )\n \n else\n\n [ x, count ] = sscanf ( line, string );\n\n if ( count == m )\n i = i + 1;\n table(1:m,i) = x(1:m);\n end\n\n end\n\n end\n\n fclose ( input_unit );\n\n return\nend\nfunction [ m, n ] = i4mat_header_read ( input_filename )\n\n%*****************************************************************************80\n%\n%% I4MAT_HEADER_READ reads the header from an I4MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Output, integer M, the spatial dimension.\n%\n% Output, integer N, the number of points.\n%\n m = file_column_count ( input_filename );\n\n if ( m <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data columns in\\n' );\n fprintf ( 1, ' the file %s.\\n', input_filename );\n end\n\n n = file_row_count ( input_filename );\n\n if ( n <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data rows in\\n' );\n fprintf ( 1, ' the file %s\\n', input_filename );\n end\n\n return\nend\nfunction i4mat_transpose_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )\n\n%*****************************************************************************80\n%\n%% I4MAT_TRANSPOSE_PRINT_SOME prints some of an I4MAT, transposed.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 June 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, integer A(M,N), an M by N matrix to be printed.\n%\n% Input, integer ILO, JLO, the first row and column to print.\n%\n% Input, integer IHI, JHI, the last row and column to print.\n%\n% Input, string TITLE, a title.\n%\n incx = 10;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, '%s\\n', title );\n\n for i2lo = max ( ilo, 1 ) : incx : min ( ihi, m )\n\n i2hi = i2lo + incx - 1;\n i2hi = min ( i2hi, m );\n i2hi = min ( i2hi, ihi );\n\n inc = i2hi + 1 - i2lo;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Row: ' );\n for i = i2lo : i2hi\n fprintf ( 1, '%7d ', i );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Col\\n' );\n fprintf ( 1, '\\n' );\n\n j2lo = max ( jlo, 1 );\n j2hi = min ( jhi, n );\n\n for j = j2lo : j2hi\n\n fprintf ( 1, '%5d ', j );\n for i2 = 1 : inc\n i = i2lo - 1 + i2;\n fprintf ( 1, '%7d ', a(i,j) );\n end\n fprintf ( 1, '\\n' );\n\n end\n\n end\n\n return\nend\nfunction i4mat_write ( output_filename, m, n, table )\n\n%*****************************************************************************80\n%\n%% I4MAT_WRITE writes an I4MAT file.\n%\n% Discussion:\n%\n% An I4MAT is an array of I4's.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 August 2009\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, integer TABLE(M,N), the points.\n%\n% Input, logical HEADER, is TRUE if the header is to be included.\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, 'I4MAT_WRITE - Error!\\n' );\n fprintf ( 1, ' Could not open the output file.\\n' );\n error ( 'I4MAT_WRITE - Error!' );\n end\n%\n% Write the data.\n%\n for j = 1 : n\n for i = 1 : m\n fprintf ( output_unit, ' %12d', round ( 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 element_node = mesh_base_one ( node_num, element_order, ...\n element_num, element_node )\n\n%*****************************************************************************80\n%\n%% MESH_BASE_ONE ensures that the element definition is one-based.\n%\n% Discussion:\n%\n% The ELEMENT_NODE array contains nodes indices that form elements.\n% The convention for node indexing might start at 0 or at 1.\n% Since a MATLAB program will naturally assume a 1-based indexing, it is\n% necessary to check a given element definition and, if it is actually\n% 0-based, to convert it.\n%\n% This function attempts to detect 0-based node indexing and correct it.\n%\n% Thanks to Feifei Xu for pointing out that I was subtracting 1 when I\n% should have been adding 1! 29 November 2012.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 29 November 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, integer ELEMENT_ORDER, the order of the elements.\n%\n% Input, integer ELEMENT_NUM, the number of elements.\n%\n% Input/output, integer ELEMENT_NODE(ELEMENT_ORDE,ELEMENT_NUM), the element\n% definitions.\n%\n node_min = min ( min ( element_node(1:element_order,1:element_num) ) );\n node_max = max ( max ( element_node(1:element_order,1:element_num) ) );\n\n if ( node_min == 0 && node_max == node_num - 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MESH_BASE_ONE:\\n' );\n fprintf ( 1, ' The element indexing appears to be 0-based!\\n' );\n fprintf ( 1, ' This will be converted to 1-based.\\n' );\n element_node(1:element_order,1:element_num) = ...\n element_node(1:element_order,1:element_num) + 1;\n elseif ( node_min == 1 && node_max == node_num )\n% fprintf ( 1, '\\n' );\n% fprintf ( 1, 'MESH_BASE_ONE:\\n' );\n% fprintf ( 1, ' The element indexing appears to be 1-based!\\n' );\n% fprintf ( 1, ' No conversion is necessary.\\n' );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MESH_BASE_ONE - Warning!\\n' );\n fprintf ( 1, ' The element indexing is not of a recognized type.\\n' );\n fprintf ( 1, ' NODE_MIN = %d\\n', node_min );\n fprintf ( 1, ' NODE_MAX = %d\\n', node_max );\n fprintf ( 1, ' NODE_NUM = %d\\n', node_num );\n end\n\n return\nend\nfunction table = r8mat_data_read ( input_filename, m, n )\n\n%*****************************************************************************80\n%\n%% R8MAT_DATA_READ reads data from an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 January 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Input, integer M, N, the number of rows and columns of data.\n%\n% Output, real TABLE(M,N), the point coordinates.\n%\n table = zeros ( m, n );\n%\n% Build up the format string for reading M real numbers.\n%\n string = ' ';\n\n for i = 0 : m\n string = strcat ( string, ' %f' );\n end\n\n input_unit = fopen ( input_filename );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_DATA_READ - Error!\\n' );\n fprintf ( 1, ' Could not open the file.\\n' );\n error ( 'R8MAT_DATA_READ - Error!' );\n end\n\n i = 0;\n\n while ( i < n )\n\n line = fgets ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n if ( line(1) == '#' )\n\n elseif ( s_len_trim ( line ) == 0 )\n \n else\n\n [ x, count ] = sscanf ( line, string );\n\n if ( count == m )\n i = i + 1;\n table(1:m,i) = x(1:m);\n end\n\n end\n\n end\n\n fclose ( input_unit );\n\n return\nend\nfunction [ m, n ] = r8mat_header_read ( input_filename )\n\n%*****************************************************************************80\n%\n%% R8MAT_HEADER_READ reads the header from an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Output, integer M, the spatial dimension.\n%\n% Output, integer N, the number of points.\n%\n m = file_column_count ( input_filename );\n\n if ( m <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data columns in\\n' );\n fprintf ( 1, ' the file %s.\\n', input_filename );\n end\n\n n = file_row_count ( input_filename );\n\n if ( n <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data rows in\\n' );\n fprintf ( 1, ' the file %s\\n', input_filename );\n end\n\n return\nend\nfunction r8mat_transpose_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )\n\n%*****************************************************************************80\n%\n%% R8MAT_TRANSPOSE_PRINT_SOME prints some of an R8MAT, transposed.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, real A(M,N), an M by N matrix to be printed.\n%\n% Input, integer ILO, JLO, the first row and column to print.\n%\n% Input, integer IHI, JHI, the last row and column to print.\n%\n% Input, string TITLE, an optional title.\n%\n incx = 5;\n\n if ( 0 < s_len_trim ( title ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, '%s\\n', title );\n end\n\n for i2lo = max ( ilo, 1 ) : incx : min ( ihi, m )\n\n i2hi = i2lo + incx - 1;\n i2hi = min ( i2hi, m );\n i2hi = min ( i2hi, ihi );\n\n inc = i2hi + 1 - i2lo;\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Row: ' );\n for i = i2lo : i2hi\n fprintf ( 1, '%7d ', i );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Col\\n' );\n\n j2lo = max ( jlo, 1 );\n j2hi = min ( jhi, n );\n\n for j = j2lo : j2hi\n\n fprintf ( 1, '%5d ', j );\n for i2 = 1 : inc\n i = i2lo - 1 + i2;\n fprintf ( 1, '%12f', a(i,j) );\n end\n fprintf ( 1, '\\n' );\n\n end\n\n end\n\n return\nend\nfunction len = s_len_trim ( s )\n\n%*****************************************************************************80\n%\n%% S_LEN_TRIM returns the length of a character string to the last nonblank.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2003\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string S, the string to be measured.\n%\n% Output, integer LEN, the length of the string up to the last nonblank.\n%\n len = length ( s );\n\n while ( 0 < len )\n if ( s(len) ~= ' ' )\n return\n end\n len = len - 1;\n end\n\n return\nend\nfunction word_num = s_word_count ( s )\n\n%*****************************************************************************80\n%\n%% S_WORD_COUNT counts the number of \"words\" in a string.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 January 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string S, the string to be examined.\n%\n% Output, integer WORD_NUM, the number of \"words\" in the string.\n% Words are presumed to be separated by one or more blanks.\n%\n FALSE = 0;\n TRUE = 1;\n\n word_num = 0;\n s_length = length ( s );\n\n if ( s_length <= 0 )\n return;\n end\n\n blank = TRUE;\n\n for i = 1 : s_length\n\n if ( s(i) == ' ' )\n blank = TRUE;\n elseif ( blank == TRUE )\n word_num = word_num + 1;\n blank = FALSE;\n end\n\n end\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/fem2d_scalar_display/fem2d_scalar_display.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.6967393314874073}} {"text": "function [J,lambdaOpt,T] = ridgeSVD(Y,Ut, s2,V,nlambda,plotGCV,verb)\n%[J,lambdaOpt,T] = ridgeSVD(Y,Ut, s2,V,nlambda,plotGCV)\n%\n% Estimates a ridge regression model, also know as Tikhonov regularization, \n% or minimum norm with L2 prior (or Loreta in the EEG inverse solution literature). \n% For an implementation of sLORETA model see the function inverseSolutionLoreta.\n%\n% Y: measurements (Nsensors X 1)\n% Ut, s2,V are defined as the SVD decomposition of the standardized lead field matrix\n% nlambda: maximum size of the grid for the hyperparameter lambda, default: 100\n% plotGCV: plot the GCV curve (true/false), default: false\n% Jest: estimated parapeters\n% T: estimated inverse operatormaximum size of the grid for the hyperparameter lambda, default: 100\n% \n% Jest = argmin(J) ||Y-K*J||^2 + lambda*||L*J||^2 == argmin(J) ||Y-K/L*Jst||^2 + lambda*||I||^2, s.t. J = L/Jst \n% and lambda > 0\n%\n% This code is based on a previous implementation used in Valdes-Hernandez \n% et al. (2009), written by Alejandro Ojeda and Pedro Valdez-Hernandez at \n% the Cuban Neuroscience Center in 2009.\n% \n% Author: Alejandro Ojeda, SCCN/INC/UCSD, Jul-2012\n%\n% References:\n% Pedro A. Vald\u00e9s-Hern\u00e1ndez, Alejandro Ojeda, Eduardo Mart\u00ednez-Montes, Agust\u00edn\n% Lage-Castellanos, Trinidad Viru\u00e9s-Alba, Lourdes Vald\u00e9s-Urrutia, Pedro A.\n% Valdes-Sosa, 2009. White matter White matter architecture rather than \n% cortical surface area correlates with the EEG alpha rhythm. NeuroImage 49\n% (2010) 2328\u20132339\n\nif nargin < 4, error('Not enough input arguments.'); end\nif nargin < 5 || isempty(nlambda) nlambda = 100; end\nif nargin < 6 || isempty(plotGCV) plotGCV = false; end\nif nargin < 7 || isempty(verb) verb = false; end\n\nn = size(Ut,1);\np = size(V,1);\ns = sqrt(s2);\nUtY = Ut*Y;\n\ntol = max([n p])*eps(max(s));\nlambda = logspace(log10(tol),log10(max(s)),nlambda);\ngcv = zeros(nlambda,1);\n\nbeta2 = mean(norms(Y).^2 - norms(UtY).^2);\n[n,m] = size(Ut);\ndelta0 = 0;\n if (m > n && beta2 > 0)\n if verb\n fprintf('m>n criterion met\\n');\n fprintf('m=%d, n=%d\\n',m,n);\n end\n delta0 = beta2; \n end\nfor it=1:nlambda\n gcv(it) = gcvfun2(lambda(it),s2,UtY,delta0,m-n);\nend\n\nloc = getMinima(gcv);\nif verb\n fprintf('GCV min found at loc=%d | lambda=%0.5g\\n',loc,lambda(loc)); end\nif isempty(loc), \n fprintf('GCV did not find a minimum.\\n');\n loc = length(lambda);\nend\nloc = loc(end);\nlambdaOpt = lambda(loc);\n\nT = V*diag(s./(s2+lambdaOpt.^2))*Ut;\nJ = T*Y; % J = (K'*K+lambda*L'*L)\\K'*Y\n\n% J = bsxfun(@minus,J,median(J));\n% J = bsxfun(@rdivide,J,(std(J)+eps));\n\nif plotGCV\n figure;\n semilogx(lambda,gcv)\n xlabel('log-lambda');\n ylabel('GCV');\n hold on;\n plot(lambdaOpt,gcv(loc),'rx','linewidth',2)\n grid on;\nend\n\n%---\nfunction indmin = getMinima(x)\nfminor = diff(x)>=0;\nfminor = ~fminor(1:end-1) & fminor(2:end);\nfminor = [0; fminor; 0];\nindmin = find(fminor);\n\n\nfunction G = gcvfun2(lambda,s2,beta,delta0,mn,dsvd)\n\n% Auxiliary routine for gcv. PCH, IMM, Feb. 24, 2008.\n\n% Note: f = 1 - filter-factors.\nif (nargin==5)\n f = (lambda^2)./(s2 + lambda^2);\nelse\n f = lambda./(s2 + lambda);\nend\nG = mean((norms(bsxfun(@times,f,beta)).^2 + delta0)/(mn + sum(f))^2);\n\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/filters/in_development/private/ridgeSVD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6967293963911554}} {"text": "function TFM = createRotationVectorPoint3d(A,B,P)\n%CREATEROTATIONVECTORPOINT3D Calculates the rotation between two vectors.\n% around a point\n% \n% TFM = createRotationVectorPoint3d(A,B,P) returns the transformation \n% to rotate the vector A in the direction of vector B around point P\n% \n% Example\n% A=-5+10.*rand(1,3);\n% B=-10+20.*rand(1,3);\n% P=-50+100.*rand(1,3);\n% ROT = createRotationVectorPoint3d(A,B,P);\n% C = transformVector3d(A,ROT);\n% figure('color','w'); hold on; view(3)\n% drawPoint3d(P,'k')\n% drawVector3d(P, A,'r')\n% drawVector3d(P, B,'g')\n% drawVector3d(P, C,'r')\n%\n% See also\n% transformPoint3d, createRotationVector3d\n%\n% ---------\n% Author: oqilipo\n% Created: 2017-08-07\n% Copyright 2017\n\nP = reshape(P,3,1);\n\n% Translation from P to origin\ninvtrans = [eye(3),-P; [0 0 0 1]];\n\n% Rotation from A to B\nrot = createRotationVector3d(A, B);\n\n% Translation from origin to P\ntrans = [eye(3),P; [0 0 0 1]];\n\n% Combine\nTFM = trans*rot*invtrans;\n\nend", "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/createRotationVectorPoint3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.7853085834000791, "lm_q1q2_score": 0.696729392046428}} {"text": "clear all, close all, clc\n\n% J = @(u,t)(25-(5-(u-t))^2);\n\nJ = @(u,t)(25-(5-(u)).^2);\ny0 = J(0,0); % u = 0\n\n% Extremum Seeking Control Parameters\nfreq = 10*2*pi; % sample frequency\ndt = 1/freq;\nT = 10; % total period of simulation (in seconds)\nA = .2; % amplitude\nomega = 10*2*pi; % 10 Hz\nphase = 0;\nK = 5; % integration gain\n\n% High pass filter (Butterworth filter)\nbutterorder=1;\nbutterfreq=2; % in Hz for 'high'\n[b,a] = butter(butterorder,butterfreq*dt*2,'high')\nys = zeros(1,butterorder+1)+y0;\nHPF=zeros(1,butterorder+1);\n\nuhat=u;\nfor i=1:T/dt\n t = (i-1)*dt;\n yvals(i)=J(u,t);\n \n for k=1:butterorder\n ys(k) = ys(k+1);\n HPF(k) = HPF(k+1);\n end\n ys(butterorder+1) = yvals(i); \n HPFnew = 0;\n for k=1:butterorder+1\n HPFnew = HPFnew + b(k)*ys(butterorder+2-k);\n end\n for k=2:butterorder+1\n HPFnew = HPFnew - a(k)*HPF(butterorder+2-k);\n end\n HPF(butterorder+1) = HPFnew;\n \n xi = HPFnew*sin(omega*t + phase);\n uhat = uhat + xi*K*dt;\n u = uhat + A*sin(omega*t + phase);\n uhats(i) = uhat;\n uvals(i) = u; \nend\n\n%%\nfigure\nsubplot(2,1,1)\nplot(t,uvals,t,uhats,'LineWidth',1.2)\nl1=legend('$u$','$\\hat{u}$')\nset(l1,'interpreter','latex','Location','NorthWest')\ngrid on\nsubplot(2,1,2)\nplot(t,yvals,'LineWidth',1.2)\nylim([-1 26])\ngrid on\n\nset(gcf,'Position',[100 100 500 350])\nset(gcf,'PaperPositionMode','auto')\n% print('-depsc2', '-loose', '../../../figures/ESC_Response');", "meta": {"author": "dynamicslab", "repo": "databook_matlab", "sha": "d390d39d18489a4804ee87a143ae8db8a1f3010b", "save_path": "github-repos/MATLAB/dynamicslab-databook_matlab", "path": "github-repos/MATLAB/dynamicslab-databook_matlab/databook_matlab-d390d39d18489a4804ee87a143ae8db8a1f3010b/CH10/CH10_SEC03_ESCfixed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6967293759911953}} {"text": "function [ TreeMatric,Cost ] = DirectedMaximumSpanningTree( OriginalCostMatric,Root )\n% MST on a directed graph\n% Chu-Liu/Edmonds Algorithm:\n%1 Discard the arcs entering the root if any; For each node other than the root, select the entering arc with the highest cost; Let the selected n-1 arcs be the set S. \n% If no cycle is formed, G( N,S ) is a MST. Otherwise, continue. \n%2 For each cycle formed, contract the nodes in the cycle into a pseudo-node (k), and modify the cost of each arc which enters a node (j) in the cycle from some node (i)\n% outside the cycle according to the following equation. c(i,k)=c(i,j)-(c(x(j),j)-min_{j}(c(x(j),j)) where c(x(j),j) is the cost of the arc in the cycle which enters j. \n%3 For each pseudo-node, select the entering arc which has the smallest modified cost; Replace the arc which enters the same real node in S by the new selected arc. \n%4 Go to step 2 with the contracted graph.\n\n% This code is written by Lowell Guangdi, Email: lowellli121@gmail.com\nDim = size( OriginalCostMatric,2 );\nfor p = 1:Dim, OriginalCostMatric( p,p ) = 0;end\n\nMin = min(min(OriginalCostMatric));\nOriginalCostMatric = OriginalCostMatric - Min;\n\nCostMatric = OriginalCostMatric;\nCostMatric( :,Root )= zeros( Dim,1 ); \nwhile 1\n TreeMatric = CostMatric;\n % select out the maximal weights of arcs upon each node. \n for p = 1 : Dim\n if p ~= Root\n [ LocalMax,Index ] = max( TreeMatric( :,p ) ); \n TreeMatric( :,p ) = zeros( Dim,1 );\n TreeMatric( Index,p ) = LocalMax;\n end \n end \n % test the existence of cycle\n [ CNumber, Component ] = conncomp( biograph( TreeMatric ),'Weak', true );\n if CNumber == 1,break; end\n % Cycle exists\n RootCluster = Component( Root );\n RootSharedNode = find( Component == RootCluster );\n if RootCluster == 1\n CaredCluster = 2;\n elseif RootCluster > 1\n CaredCluster = 1;\n end\n % change the weight here\n ClusterNode = find( Component == CaredCluster );\n CostMatric = SearchCycleNode(ClusterNode,TreeMatric, CostMatric,OriginalCostMatric,RootSharedNode); \nend\nTreeMatric = CostMatric;\nCost = sum(sum( TreeMatric ));\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/24327-maximumminimum-weight-spanning-tree-directed/DirectedSpanningTree/DirectedMaximumSpanningTree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6966560589826445}} {"text": "function points=Cart2Ellipse(cartPoints,algorithm,a,f)\n%%CART2ELLIPSE Convert Cartesian coordinates to ellipsoidal (latitude,\n% longitude, and altitude) coordinates.\n%\n%INPUTS: cartPoints A matrix of the points in ECEF Cartesian coordinates\n% that are to be transformed into ellipsoidal\n% coordinates. Each column of cartPoints is of the\n% format [x;y;z].\n% algorithm This specified the algorithm to use for the conversion.\n% Note that none work at the origin. Possible values are:\n% 0 (The default if this parameter is omitted or an empty\n% matrix is passed and f<0.01) Use the algorithm of\n% Olson in [1]. \n% 1 Use the Algorithm of Sofair in [2], which is a\n% modification of [3]. This will not work close to the\n% center of the Earth.\n% 2 (The default if this parameter is omitted or an empty\n% matrix is passed and f>=0.01) Use the algorithm of\n% Fukushima in [4]. This should work close to the\n% center of the Earth.\n% a The semi-major axis of the reference ellipsoid. If this\n% argument is omitted, the value in\n% Constants.WGS84SemiMajorAxis is used.\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: points A matrix of the converted points. Each column of the\n% matrix has the format [latitude;longitude;altitude], with\n% latitude and longitude given in radians.\n%\n%The algorithm of Olson in [1] appears to be the most precise non-iterative\n%method available for targets far above the Earth. The method of Sofair in\n%[2] and [3] is also a non-iterative algorithm, but tends to have\n%significantly worse accuracy for such targets. Fukushima's algorithm in\n%[4] is iterative and typically converges in six or fewer iterations. It is\n%set to run for a maximum number of 500 iterations. More than 6 iterations\n%can be necessary when a large flattening is used and the point in question\n%is near the center of the Earth. Its accuracy appears to be marginally\n%better than [1] for things not near the surface of the Earth/ reference\n%ellipsoid, but it is slower.\n%\n%REFERENCES:\n%[1] D. K. Olson, \"Converting Earth-centered, Earth-fixed coordinates to\n% geodetic coordinates,\" IEEE Transactions on Aerospace and Electronic\n% Systems, vol. 32, no. 1, pp. 473-476, Jan. 1996.\n%[2] I. Sofair \"Improved method for calculating exact geodetic latitude and\n% altitude revisited,\" Journal of Guidance, Control, and Dynamics, vol.\n% 23, no. 2, p. 369, Mar. 2000.\n%[3] I. Sofair, \"Improved method for calculating exact geodetic latitude\n% and altitude,\" Journal of Guidance, Control, and Dynamics, vol. 20,\n% no. 4, pp. 824-826, Jul.-Aug. 1997.\n%[4] Fukushima, T., \"Transformation from Cartesian to geodetic coordinates\n% accelerated by Halley's method\", Journal of Geodesy, vol. 79, no. 12,\n% pp. 689-693, Mar. 2006.\n%\n%October 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<4||isempty(f))\n f=Constants.WGS84Flattening;\nend\n\nif(nargin<3||isempty(a))\n a=Constants.WGS84SemiMajorAxis;\nend\n\nif(nargin<2||isempty(algorithm))\n if(f<0.01)\n algorithm=0;\n else\n algorithm=2;\n end\nend\n\nswitch(algorithm)\n case 0%Olson's algorithm\n [lambda,phi,h]=OlsonAlg(cartPoints,a,f);\n \n if(any(imag(lambda)~=0)||any(imag(phi)~=0)||any(imag(phi)~=0))\n error('The point given is too close to the center of the Earth for the algorithm of Olson.')\n end\n \n case 1%Sofair's algorithm\n [lambda,phi,h]=SofairAlg(cartPoints,a,f);\n case 2%Fukushima's algorithm\n [lambda,phi,h]=FukishimaAlg(cartPoints,a,f);\n otherwise\n error('Unknown algorithm specified.')\nend\n\npoints=[phi;lambda;h];\n\nend\n\nfunction [lambda,phi,h]=SofairAlg(cartPoints,a,f)\n%%SOFAIRALG This implements the algorithm of [1], which is a modified\n% version of the algorithm of [2]. Both techniques will fail if\n% the point in question is too close to the origin (deep within\n% the Earth). If the algorithm fails, then this function wil have\n% an error.\n%\n%REFERENCES:\n%[1] I. Sofair \"Improved method for calculating exact geodetic latitude and\n% altitude revisited,\" Journal of Guidance, Control, and Dynamics, vol.\n% 23, no. 2, p. 369, Mar. 2000.\n%[2] I. Sofair, \"Improved method for calculating exact geodetic latitude\n% and altitude,\" Journal of Guidance, Control, and Dynamics, vol. 20,\n% no. 4, pp. 824-826, Jul.-Aug. 1997.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumPoints=size(cartPoints,2);\n\n%The semi-minor axis of the reference ellipsoid.\nb=a*(1-f);\n\n%The square of the first numerical eccentricity. \ne2=2*f-f^2;\n\n%The square of the second numerical eccentricity.\neps2=a^2/b^2-1;\n\n%Allocate space for the results.\nphi=zeros(1,numPoints);\nlambda=zeros(1,numPoints);\nh=zeros(1,numPoints);\nfor curPoint=1:numPoints\n %Extract the coordinates\n x0=cartPoints(1,curPoint);\n y0=cartPoints(2,curPoint);\n z0=cartPoints(3,curPoint);\n \n r0=sqrt(x0.^2+y0.^2);\n p=abs(z0)/eps2;\n s=r0.^2/(e2*eps2);\n q=p.^2-b.^2+s;\n \n lambda(curPoint)=atan2(y0,x0);\n \n if(q<0)\n error('The point given is too close to the center of the Earth for the algorithm of Sofair.')\n end\n\n u=p./sqrt(q);\n v=b^2*u.^2./q;\n P=27*v.*s./q;\n Q=(sqrt(P+1)+sqrt(P)).^(2/3);\n t=(1+Q+1./Q)/6;\n %The max command prevents finite precision problems due to\n %subtraction within the square root.\n c=max(0,u.^2-1+2*t);\n c=sqrt(c);\n w=(c-u)/2;\n\n %The z coordinate of the closest point projected on the ellipsoid.\n %The max command deals with precision problems when the argument\n %is nearly zero. The problems arise due to the subtraction within\n %the square root.\n z=max(0,sqrt(t.^2+v)-u.*w-t/2-1/4);\n z=sign(z0).*sqrt(q).*(w+sqrt(z));\n Ne=a*sqrt(1+eps2.*z.^2/b^2);\n\n %The min and max terms deals with finite precision problems.\n val=min(z*(eps2+1)./Ne,1);\n val=max(val,-1);\n phi(curPoint)=asin(val);\n h(curPoint)=r0.*cos(phi(curPoint))+z0.*sin(phi(curPoint))-a^2./Ne;\nend\n \nend\n\nfunction [lambda,phi,h]=FukishimaAlg(cartPoints,a,f)\n%%FUKUSHIMAALG This function implements the algorithm of [1] with minor\n% modifications.\n%\n%If one lets the algorithm run for an arbitrary number of iterations, there\n%will generally be underflows, since the ratio of S and C matter, but both\n%terms can drift by a constant factor during the iterations. Thus, after\n%each iterative step, the values are normalized so that C=1 (it takes one\n%division). Convergence of Fukushima's method is assumed to occur after\n%six iterations.\n%\n%REFERENCES:\n%[1] Fukushima, T., \"Transformation from Cartesian to geodetic coordinates\n% accelerated by Halley's method\", J.Geodesy (2006) 79: 689-693.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumPoints=size(cartPoints,2);\n\n%The semi-minor axis of the reference ellipsoid.\nb=a*(1-f);\n\n%The square of the first numerical eccentricity. \ne2=2*f-f^2;\n\nec=sqrt(1-e2);\n\n%Allocate space for the results.\nphi=zeros(1,numPoints);\nlambda=zeros(1,numPoints);\nh=zeros(1,numPoints);\nfor curPoint=1:numPoints\n %Extract the coordinates\n x0=cartPoints(1,curPoint);\n y0=cartPoints(2,curPoint);\n z0=cartPoints(3,curPoint);\n \n lambda(curPoint)=atan2(y0,x0);\n\n p=sqrt(x0^2+y0^2);\n P=p/a;\n Z=(ec/a)*abs(z0);\n\n S=Z;\n C=ec*P;\n\n %Loop until convergence. Normally, only 6 iterations or fewer is\n %required. When some points are near the surface of the Earth and f is\n %close to 1, the required number of iterations can be higher.\n for curIter=1:500\n A=sqrt(S^2+C^2);\n B=1.5*e2*S*C^2*((P*S-Z*C)*A-e2*S*C);\n F=P*A^3-e2*C^3;\n D=Z*A^3+e2*S^3;\n\n SNew=D*F-B*S;\n CNew=F^2-B*C;\n \n SOld=S;\n COld=C;\n\n SNew=SNew/CNew;\n if(~isfinite(SNew))\n S=SNew;\n break;\n else\n S=SNew;\n C=1;\n end\n \n if(S==SOld&&C==COld)\n break;\n end\n end\n Cc=ec*C;\n\n %If the point is along the z-axis, then SNew and CNew will\n %both be zero, leading to a non-finite result.\n if(~isfinite(S))\n phi(curPoint)=sign(z0)*(pi/2);\n h(curPoint)=abs(z0)-b;\n else\n phi(curPoint)=sign(z0)*atan(S/Cc);\n h(curPoint)=(p*Cc+abs(z0)*S-b*A)/sqrt(Cc^2+S^2);\n end\nend\n \nend\n\nfunction [lambda,phi,h]=OlsonAlg(cartPoints,a,f)\n%%OLSONALG This function implements the algorithm of [1], removing a test\n% for a radius being too small as the function will still work at\n% smaller radii.\n%\n%REFERENCES:\n%[1] D. K. Olson, \"Converting Earth-centered, Earth-fixed coordinates to\n% geodetic coordinates,\" IEEE Transactions on Aerospace and Electronic\n% Systems, vol. 32, no. 1, pp. 473-476, Jan. 1996.\n%\n%October 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumPoints=size(cartPoints,2);\n\n%The square of the eccentricity.\ne2=2*f-f^2;\n\na1=a*e2;\na2=a1^2;\na3=a1*e2/2;\na4=(5/2)*a2;\na5=a1+a3;\na6=1-e2;\n\n%Allocate space for the results.\nphi=zeros(1,numPoints);\nlambda=zeros(1,numPoints);\nh=zeros(1,numPoints);\nfor curPoint=1:numPoints\n %Extract the coordinates\n x=cartPoints(1,curPoint);\n y=cartPoints(2,curPoint);\n z=cartPoints(3,curPoint);\n \n zp=abs(z);\n w2=x^2+y^2;\n w=sqrt(w2);\n z2=z^2;\n r2=w2+z2;\n %The algorithm will work with points close to the origin. Thus, there\n %is no need to have a test for r being too small as is the case in [1].\n r=sqrt(r2);\n\n lambda(curPoint)=atan2(y,x);\n s2=z2/r2;\n c2=w2/r2;\n u=a2/r;\n v=a3-a4/r;\n if(c2>0.3)\n s=(zp/r)*(1+c2*(a1+u+s2*v)/r);\n phi(curPoint)=asin(s);\n ss=s^2;\n c=sqrt(1-ss);\n else\n c=(w/r)*(1-s2*(a5-u-c2*v)/r);\n phi(curPoint)=acos(c);\n ss=1-c^2;\n s=sqrt(ss);\n end\n\n g=1-e2*ss;\n rg=a/sqrt(g);\n rf=a6*rg;\n u=w-rg*c;\n v=zp-rf*s;\n f=c*u+s*v;\n m=c*v-s*u;\n p=m/(rf/g+f);\n phi(curPoint)=phi(curPoint)+p;\n h(curPoint)=f+m*p/2;\n if(z<0)\n phi(curPoint)=-phi(curPoint);\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/Coordinate_Systems/Cart2Ellipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361533336451, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6966301981708932}} {"text": "clear all\n % Declararea variabilei simbolice k\nsyms k\n % Calcularea primei sume\nS1=symsum(k,1,k)\n % Afisarea rezultatului nesimplificat\npretty(S1)\n % Simplificarea rezultatului\nS1=simple(S1)\n % Afisarea rezultatului simplificat\npretty(S1)\n % Calcularea sumei a doua\nS2=symsum(1/(k*(k+1)),1,inf)", "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/8416-widely-used-programming-environments-in-electrical-engineering-matlab/12/Ex_12_6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065459, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6966105653754198}} {"text": "function [m,s] = mean_std_robust(x);\n\nx = x(:);\n\nm = median(x);\n\ns = median(abs(x - m))*1.4836;\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/EKF_monoSLAM_1pRANSAC/matlab_code/matlabcalibration2ourcalibration/TOOLBOX_calib/mean_std_robust.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.696610559918662}} {"text": "function pde = Stokesdata1\n%% STOKESDATA1 data for Stokes equations\n%\n% A simple model of colliding flow. The force f = 0, the velocity u1 =\n% 20xy^3, u2 = 5x^4-5y^4, p = 60x^2y - 20y^3.\n%\n% Dirichlet boundary condition is imposed.\n%\n% Reference: page 237 in Finite Elements and Fast Iterative Solvers with\n% Applications in Incompressible Fluid Dynamics. by Howard C. Elman, David\n% J. Silvester, and Andrew J. Wathen.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\npde = struct('f', 0, 'exactp', @exactp, 'exactu', @exactu,'g_D',@exactu, 'exactw', @exactw);\n\n % exact velocity\n function z = exactu(p)\n x = p(:,1); y = p(:,2);\n z(:,1) = 20*x.*y.^3;\n z(:,2) = 5*x.^4-5*y.^4;\n end\n % exact pressure\n function z = exactp(p)\n x = p(:,1); y = p(:,2);\n z = 60*x.^2.*y-20*y.^3-5;\n end\n % exact vorticity\n function z = exactw(p)\n x = p(:,1); y = p(:,2);\n z = 20*x.^3-60*x.*y.^2;\n end\nend\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/data/Stokesdata1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6965920553615336}} {"text": "function F = ...\n check_frequency_response(x,frequency_20,frequency_100, method)\n% Checks the result of optimization by plotting phase characteristics at\n% optimal parameters and computing the frequencies at -pi/2 phase shift.\n% The frequency responses of a nonlinear system are obtained by processing\n% the pulse transient characteristics with the FFT algorithm. \n% Copyright 2010 MathWorks, Inc.\n\n% frequency_20 - frequency (Hz) at phase shift in -pi/2 at 20% input signal\n% frequency_100 - frequency (Hz) at phase shift in -pi/2 at 100% input signal\n% method - method to check the results, can be set to 'FFT' or 'direct'.\n\nif strcmpi(method, 'FFT')\n model = 'actuator_freq_testrig_pulse_FFT_method';\nelseif strcmpi(method, 'direct')\n model = 'actuator_freq_testrig_direct_method';\nelse\n error('Unspecified method');\nend\n\nload_system(model);\n\nassignin('base','gain', x(1));\nassignin('base','time_const', x(2));\nassignin('base','saturation', x(3));\n\nsim(model);\n\nif strcmpi(method, 'FFT')\n \n y_20 = yout(:,2); % Pulse transient characteristic at 20% input\n y_100 = yout(:,1); % Pulse transient characteristic at 100% input\n fs = 1000; % Sampling frequency\n n = length(y_20); % Window length = Transform length\n y_20_fft = fft(y_20,n); % Discrete Fourier Transform\n y_100_fft = fft(y_100,n); % Discrete Fourier Transform\n f0 = (0:n/2-1)*(fs/n); % Shifted frequency range, positive region\n y_20_0 = fftshift(y_20_fft); % Shifted DFT at 20% input\n y_100_0 = fftshift(y_100_fft); % Shifted DFT at 100% input\n % Phase characteristic at 20% input for positive frequencies after unwrap\n phase_20 = unwrap(angle(y_20_0(257:end))); \n % Phase characteristic at 100% input for positive frequencies after unwrap\n phase_100 = unwrap(angle(y_100_0(257:end)));\n\n % Computing frequency at 90 deg phase shift by interpolation of phase\n % characteristics\n frq_20 = interp1(phase_20,f0,-pi/2);\n frq_100 = interp1(phase_100,f0,-pi/2);\n\n\n % Computing frequency at phase shift in -pi/2 by interpolation of phase\n % characteristics\n frq_20 = interp1(phase_20,f0,-pi/2);\n frq_100 = interp1(phase_100,f0,-pi/2);\n % Computing errors\n error_20 = (frequency_20 - frq_20)/frequency_20 * 100;\n error_100 = (frequency_100 - frq_100)/frequency_100 * 100;\n\n\n disp(['******************************************************************']); \n disp([' System Characteristics with FFT at Obtained Parameters']);\n disp([' Frequencies at -90 deg phase shift and 20% input:']);\n disp(['Target: ', num2str(frequency_20),' Hz', ...\n ' Found: ',num2str(frq_20),' Hz', ...\n ' Error : ',num2str(error_20),'%']);\n disp([' Frequencies at -90 deg phase shift and 100% input']);\n disp(['Target: ', num2str(frequency_100),' Hz', ...\n ' Found: ',num2str(frq_100),' Hz', ...\n ' Error: ',num2str(error_100),'%']);\n\n \n % Plotting the phase frequency characterictics\n semilogx(f0,phase_20*180/pi,'LineWidth',3);\n hold on\n semilogx(f0,phase_100*180/pi,'r--','LineWidth',3), grid on;\n xlabel('Frequency (Hz)','FontSize',14)\n ylabel('Phase (degrees)','FontSize',14)\n title('Frequency Response (Phase)','FontWeight','Bold','FontSize',16)\n legend({'20% Input' '100% Input'},'FontSize',12);\n axis([2 40 -100 0]);\n plot(frq_100,-90,'ro','MarkerSize',10,'MarkerFaceColor','r')\n plot(frq_20,-90,'bo','MarkerSize',10,'MarkerFaceColor','b')\n hold off\n \n\nelse % Direct measurement. yout contains input and output values of\n % both signals\n \n % Phase angle at specified frequency and input signal in 100%\n phase_100 = phase_computation(yout(:,[1,2]), tout, frequency_100,4);\n % Phase angle at specified frequency and input signal in 20%\n phase_20 = phase_computation(yout(:,[3,4]), tout, frequency_20,6);\n\n error_20 = (phase_20 + 90)/90 * 100;\n error_100 = (phase_100 +90)/90 * 100;\n\n\n disp(['******************************************************************']); \n disp([' System Characteristics after Direct Measurement at Obtained Parameters']);\n disp([' Phase shift at ',num2str(frequency_20),'Hz',' and 20% input:']);\n disp(['Target: ',' -90 deg', ...\n ' Found: ',num2str(phase_20),' deg', ...\n ' Error : ',num2str(error_20),'%']);\n disp([' Phase shift at ',num2str(frequency_100),'Hz',' and 100% input']);\n disp(['Target: ',' -90 deg', ...\n ' Found: ',num2str(phase_100),' deg', ...\n ' Error: ',num2str(error_100),'%']);\n disp(['******************************************************************']); \n\nend\nend\n\nfunction [phase] = phase_computation(yout, tout, freq_at_90, N)\n% Function computes phase angle by processing sinusoids stored in yout\n\n% yout(:,1)- input; yout(:,2) - output\n% tout - simulation step time\n% freq_at_90 - frequency at which phase angle equals -90 deg\n% N - number of periods to settle the transients\n\n% Measurement time. Time in N periods is assumed to be enough to settle\n% down the transients. The input signal at this time is equal zero\n\nt_s = 1/freq_at_90 * N; % Start time\nt_end = t_s + 1/freq_at_90; % End time\n\n% yout index at measurement time\nfor j = 1:length(tout)- 1\n if t_s >= tout(j) && t_s < tout(j+1)\n k_start = j; % First array index after start time\n t_corr_1 = tout(j) - t_s; % Correction due to discretization\n end\n if t_end >= tout(j) && t_end < tout(j+1)\n k_end = j-1; % Last array index within period\n end\nend\n% Computing time the output signal crosses zero\nfor j = k_start : k_end\n if yout(j,2) <= 0 && yout(j+1,2) > 0\n t_tab_cross = tout(j); % First value in the table after crossing\n % Approximating real crossing time\n t_corr_2 = -yout(j,2) / (yout(j+1,2) - yout(j,2)) * ...\n (tout(j+1) - tout(j));\n end\nend\n% Crossing time for the output signal\nt_cross = t_tab_cross + t_corr_1 + t_corr_2;\n% Phase angle\nphase = -(t_cross - t_s) / (1/freq_at_90) * 360;\n\nend\n\n\n% EOF", "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/27260-hydraulic-valve-parameters-from-data-sheets-and-experimental-data/Valve_Params_SH/Ex8_Prop_Servo_Freq_Resp_Direct/check_frequency_response.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6965920461818991}} {"text": "function y = goertzel_classic(x,indvec)\n% GOERTZEL_CLASSIC(X,INDVEC) computes DFT of one-dimensional signal X at indices\n% contained in INDVEC, using the traditional second-order Goertzel algorithm.\n% The indices must be integer values from 0 to N-1, where N is the length of\n% X. (Index 0 corresponds to the DC component.)\n%\n% The output is a column complex vector of length LENGTH(INDVEC) containing\n% the desired DFT coefficients.\n%\n% See also: goertzel_general_shortened.\n \n% (c) 2009-2012, Pavel Rajmic, Brno University of Technology, Czech Rep.\n\n\n%% Check the input arguments\nif nargin < 2\n error('Not enough input arguments')\nend\nif ~isvector(x) || isempty(x)\n error('X must be a nonempty vector')\nend\n\nif ~isvector(indvec) || isempty(indvec)\n error('INDVEC must be a nonempty vector')\nend\nif ~isreal(indvec)\n error('INDVEC must contain real numbers')\nend\n% if ~isinteger(indvec)\n% error('INDVEC must contain only integer values')\n% end\n\nlx = length(x);\nx = reshape(x,lx,1); %forcing x to be column\n\n\n%% Initialization\nno_freq = length(indvec); %number of frequencies to compute\ny = zeros(no_freq,1); %memory allocation for the output coefficients\n\n\n%% Computation via second-order system\n% loop over the particular frequencies\nfor cnt_freq = 1:no_freq\n \n %for a single frequency:\n %a/ precompute the constants\n pik_term = 2*pi*(indvec(cnt_freq))/(lx);\n cos_pik_term2 = cos(pik_term) * 2;\n cc = exp(-1i*pik_term); % complex constant\n %b/ state variables\n s0 = 0;\n s1 = 0;\n s2 = 0;\n %c/ 'main' loop\n for ind = 1:lx %number of loops is the same as the length of signal\n %new state\n s0 = x(ind) + cos_pik_term2*s1 - s2; % (*)\n %shifting the state variables\n s2 = s1;\n s1 = s0;\n end\n %d/ final computations\n s0 = cos_pik_term2*s1 - s2; %correspond to one extra performing of (*), where we set x(N+1)=0\n y(cnt_freq) = s0 - s1*cc; %resultant complex DFT coefficient\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/35103-generalized-goertzel-algorithm/goertzel_classic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.78793120560257, "lm_q1q2_score": 0.6965621394734303}} {"text": "function K = rbfhKernCompute(kern, x1, x2)\n\n% RBFHKERNCOMPUTE Compute the RBFH kernel given the parameters and X.\n% FORMAT\n% DESC computes the kernel parameters for the radial basis function heat\n% kernel given inputs associated with rows and columns.\n% ARG kern : the kernel structure for which the matrix is computed.\n% ARG x1 : the input matrix associated with the rows of the kernel.\n% ARG x2 : the input matrix associated with the columns of the kernel.\n% RETURN K : the kernel matrix computed at the given points.\n%\n% FORMAT\n% DESC computes the kernel matrix for the radial basis function heat\n% kernel given a design matrix of inputs.\n% ARG kern : the kernel structure for which the matrix is computed.\n% ARG x1 : input data matrix in the form of a design matrix.\n% RETURN K : the kernel matrix computed at the given points.\n%\n% SEEALSO : rbfhKernParamInit, kernCompute, \n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n\n% KERN\n\nif nargin < 3\n x2 = x1;\nend\n\nif size(x1, 2) ~= 2 || size(x2, 2) ~= 2\n error('Input can only have two columns');\nend\n\n\n% Split the domain into time domain and spatial domain and account for\n% missing values. If there are no missing values the computation of the\n% kernel is a pointwise prodruct, otherwise it is a kronecker product.\nt1 = x1(x1(:,1)~=Inf,1);\nt2 = x2(x2(:,1)~=Inf,1);\ns1 = x1(x1(:,2)~=Inf,2);\ns2 = x2(x2(:,2)~=Inf,2);\nif (length(t1) == length(s1)) && (length(t2) == length(s2))\n ut1 = unique(t1);\n ut2 = unique(t2);\n us1 = unique(s1);\n us2 = unique(s2);\n if (length(ut1)*length(us1) == length(t1)) && ...\n (length(ut2)*length(us2) == length(t2))\n t1 = ut1; s1 = us1; t2 = ut2; s2 = us2;\n isPointwise = false; \n else\n isPointwise = true;\n end\nelse\n isPointwise = false;\nend\n\nkern.rbf.inverseWidth = kern.inverseWidthTime;\nKt = rbfKernCompute(kern.rbf, t1, t2);\nkern.rbf.inverseWidth = kern.inverseWidthSpace;\nKs = rbfKernCompute(kern.rbf, s1, s2);\n \nif isPointwise\n K = Kt.*Ks;\nelse\n K = kron(Kt, Ks); \nend\n\n\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/rbfhKernCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6965621282614378}} {"text": "function y=sigpower(x)\n\n% y=sigpower(x)\n%\n% Return the average signal power of signal x or mean(abs(x).^2);\n\n% Copyright 2012 Evrytania LLC (http://www.evrytania.com)\n%\n% Written by James Peroulas \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\nerror(nargchk(1,1,nargin));\n\ny=sum(real(x).*real(x)+imag(x).*imag(x))/length(x);\n\n", "meta": {"author": "JiaoXianjun", "repo": "rtl-sdr-LTE", "sha": "037a25f164f17b1a1d82e2eb02285550f50af9b9", "save_path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE", "path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE/rtl-sdr-LTE-037a25f164f17b1a1d82e2eb02285550f50af9b9/matlab/sigpower.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.6965348714912296}} {"text": "function w = ymdf_to_weekday_common ( y, m, d, f )\n\n%*****************************************************************************80\n%\n%% YMDF_TO_WEEKDAY_COMMON returns the weekday of a Common YMDF date.\n%\n% Discussion:\n%\n% The \"common\" calendar is meant to be the calendar which is Julian up to\n% day JED = 2299160, and Gregorian from day JED = 2299161 and after.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 June 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer Y, M, D, real F, the YMDF date.\n%\n% Output, integer W, is the week day number of the date, with\n% 1 for Sunday, through 7 for Saturday.\n%\n jed = ymdf_to_jed_common ( y, m, d, f );\n\n [ w, f2 ] = jed_to_weekday ( jed );\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/calpak/ymdf_to_weekday_common.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.6965348695978025}} {"text": "function [ point_num, edge_num, face_num, face_order_max ] = ...\n truncated_octahedron_size_3d ( )\n\n%*****************************************************************************80\n%\n%% TRUNCATED_OCTAHEDRON_SIZE_3D gives \"sizes\" for a truncated octahedron in 3D.\n%\n% Discussion:\n%\n% The truncated octahedron is \"space-filling\".\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 July 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, integer POINT_NUM, the number of points.\n%\n% Output, integer EDGE_NUM, the number of edges.\n%\n% Output, integer FACE_NUM, the number of faces.\n%\n% Output, integer FACE_ORDER_MAX, the maximum order of any face.\n%\n point_num = 24;\n edge_num = 36;\n face_num = 14;\n face_order_max = 6;\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/truncated_octahedron_size_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.696534856700632}} {"text": "function ccff_asymptotic ( n_min, n_inc, n_max, f, f_integral )\n\n%*****************************************************************************80\n%\n%% CCFF_ASYMPTOTIC computes asymptotic errors for the Legendre integral.\n%\n% Discussion:\n%\n% The Legendre integral being approximated is:\n% integral ( -1 <= x <= +1 ) f(x) dx\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 May 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N_MIN, N_INC, N_MAX, the minimum, increment, and maximum\n% for the number of points in the rule.\n%\n% Input, function pointer F(x), returns the value of the integrand\n% at the N points X.\n%\n% Input, real F_INTEGRAL, the exact value of the integral.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N |Quad error|\\n' );\n fprintf ( 1, '\\n' );\n for n = n_min : n_inc : n_max\n [ x, w ] = ccff ( n );\n fx = f ( x );\n q = w' * fx;\n e = abs ( f_integral - q );\n fprintf ( 1, ' %4d %8.2e\\n', n, e );\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/cc_project/ccff_asymptotic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.6965348516246548}} {"text": " function [Cone,EndPlate1,EndPlate2] = Cone(hAxis,X1,X2,R,n,cyl_color,closed,lines)\n%\n% This function constructs a cylinder connecting two center points \n% \n% Usage :\n% [Cone,EndPlate1,EndPlate2] = Cone(X1,X2,R,n,cyl_color,closed,lines)\n% \n% Cone-------Handle of the cone\n% EndPlate1------Handle of the Starting End plate\n% EndPlate2------Handle of the Ending End plate\n% X1 and X2 are the 3x1 vectors of the two points\n% R is the radius of the cylinder/cone R(1) = start radius, R(2) = end radius\n% n is the no. of elements on the cylinder circumference (more--> refined)\n% cyl_color is the color definition like 'r','b',[0.52 0.52 0.52]\n% closed=1 for closed cylinder or 0 for hollow open cylinder\n% lines=1 for displaying the line segments on the cylinder 0 for only\n% surface\n% \n% Typical Inputs\n% X1=[10 10 10];\n% X2=[35 20 40];\n% r=[1 5];\n% n=20;\n% cyl_color='b';\n% closed=1;\n% \n% NOTE: There is a MATLAB function \"cylinder\" to revolve a curve about an\n% axis. This \"Cylinder\" provides more customization like direction and etc\n\n\n% Calculating the length of the Cone\nlength_cyl=norm(X2-X1);\n\n% Creating 2 circles in the YZ plane\nt=linspace(0,2*pi,n)';\nxa2=R(1)*cos(t);\nxa3=R(1)*sin(t);\nxb2=R(2)*cos(t);\nxb3=R(2)*sin(t);\n\n% Creating the points in the X-Direction\nx1=[0 length_cyl];\n\n% Creating (Extruding) the cylinder points in the X-Directions\nxx1=repmat(x1,length(xa2),1);\nxx2=[xa2 xb2];%xx2=repmat(x2,1,2);\nxx3=[xa3 xb3];%xx3=repmat(x3,1,2);\n\n% Drawing two filled cirlces to close the cylinder\nif closed==1\n EndPlate1=fill3(xx1(:,1),xx2(:,1),xx3(:,1),'r', 'Parent', hAxis);\n EndPlate2=fill3(xx1(:,2),xx2(:,2),xx3(:,2),'r', 'Parent', hAxis);\nend\n\n% Plotting the cylinder along the X-Direction with required length starting\n% from Origin\nCone=mesh(hAxis,xx1,xx2,xx3, 'Parent', hAxis);\n\n% Defining Unit vector along the X-direction\nunit_Vx=[1 0 0];\n\n% Calulating the angle between the x direction and the required direction\n% of Cone through dot product\nangle_X1X2=acos( dot( unit_Vx,(X2-X1) )/( norm(unit_Vx)*norm(X2-X1)) )*180/pi;\n\n% Finding the axis of rotation (single rotation) to roate the Cone in\n% X-direction to the required arbitrary direction through cross product\naxis_rot=cross([1 0 0],(X2-X1) );\n\n% Rotating the plotted Cone and the end plate circles to the required\n% angles\nif angle_X1X2~=0 % Rotation is not needed if required direction is along X\n rotate(Cone,axis_rot,angle_X1X2,[0 0 0])\n if closed==1\n rotate(EndPlate1,axis_rot,angle_X1X2,[0 0 0])\n rotate(EndPlate2,axis_rot,angle_X1X2,[0 0 0])\n end\nend\n\n% Till now Cone has only been aligned with the required direction, but\n% position starts from the origin. so it will now be shifted to the right\n% position\nif closed==1\n set(EndPlate1,'XData',get(EndPlate1,'XData')+X1(1))\n set(EndPlate1,'YData',get(EndPlate1,'YData')+X1(2))\n set(EndPlate1,'ZData',get(EndPlate1,'ZData')+X1(3))\n \n set(EndPlate2,'XData',get(EndPlate2,'XData')+X1(1))\n set(EndPlate2,'YData',get(EndPlate2,'YData')+X1(2))\n set(EndPlate2,'ZData',get(EndPlate2,'ZData')+X1(3))\nend\nset(Cone,'XData',get(Cone,'XData')+X1(1))\nset(Cone,'YData',get(Cone,'YData')+X1(2))\nset(Cone,'ZData',get(Cone,'ZData')+X1(3))\n\n% Setting the color to the Cone and the end plates\nset(Cone,'AmbientStrength',1,'FaceColor',cyl_color,'FaceLighting','gouraud', 'Parent', hAxis);%,'EdgeColor','none')\nif closed==1\n set([EndPlate1 EndPlate2],'AmbientStrength',1,'FaceColor',cyl_color,'FaceLighting','gouraud', 'Parent', hAxis);%,'EdgeColor','none')\nelse\n EndPlate1=[];\n EndPlate2=[];\nend\n\n% If lines are not needed making it disapear\nif lines==0\n set(Cone,'EdgeAlpha',0)\nend\n\n%shading faceted % faceted flat interp;\n%camlight; \n%light;\n%lighting gouraud; %flat gouraud phong none\n% material shiny; %shiny dull metal\n%colormap(bone)\n\n%camlight headlight;\n%light('Style','local','Position',[720 0 500]);\n%light('Style','local','Position',[0 480 500]);", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/gui_setup/plot/Cone.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.8031737869342624, "lm_q1q2_score": 0.6963804056457625}} {"text": "% Rounds a scalar, matrix or vector to a specified number of decimal places\n% Format is roundoff(number,decimal_places)\n\nfunction y = roundoff(number,decimal_places)\n\n[INeg,JNeg] = find( number<0 ); % Negative numbers\n\nif ~isempty(INeg)\n IndNeg = sub2ind(size(number),INeg,JNeg);\n Number = abs(number);\nelse\n Number = number;\nend\n\ndecimals = 10.^decimal_places;\ny1 = fix(decimals * Number + 0.5)./decimals;\n\nif ~isempty(INeg)\n y1(IndNeg) = -y1(IndNeg);\nend\n\ny = y1;", "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/1374-roundoff/Roundoff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.6963804001267488}} {"text": "function [thr, q, obj, im] = gmthr_seg(im, nobj, nsubs)\n% GMTHR_SEG Segment an image estimating threshold as intersection of two\n% Gaussians from Gaussian mixture model\n%\n% THR = gmthr_seg(IM)\n%\n% IM is an input n-dim image. This function assumes that IM contains a\n% darker object over a brighter background.\n%\n% THR is a scalar with the estimated threshold value between dark\n% voxels (object) and lighter voxels (background). A Gaussian mixture\n% model is fitted to the image intensities, and the intersection point\n% between the Gaussian maxima is computed. The object in the image is\n% segmented using this intersection value as the segmentation threshold.\n%\n% If the object and the background are too similar compared to the number\n% of samples in the image (i.e. the Gaussians intersect outside of the\n% interval between the Gaussian maxima), then this method cannot provide\n% a threshold to separate object and background. In that case, THR is\n% returned as NaN. This is the case, for example, if the image only\n% contains background, or only object voxels.\n%\n% [THR, Q, OBJ, BW] = gmthr_seg(IM, NOBJ, NSUBS)\n%\n% NOBJ is a scalar. Only the largest NOBJ are kept in the segmentation.\n% This last step is useful to remove segmentation noise. By default,\n% NOBJ=1.\n%\n% NSUBS is a scalar. For large images, the variance estimate will be too\n% small for the Gaussian mixture fitting function, which will return an\n% error. This problem can be solved doing a random subsampling of the\n% image to estimate the Gaussian mixture model. NSUBS is the subsampling\n% factor. E.g. NSUBS=100 will randomly sample numel(IM)/NSUBS voxels in\n% the image. By default, NSUBS=1 and no subsampling is performed.\n%\n% Q is a quality measure of the threshold. Q takes values in [0, 1].\n% Values close to 0 mean that both Gaussians have a lot of overlap, so\n% the threshold between object and background cannot be trusted very\n% much. Values close to 1 mean that both Gaussians are well separated,\n% and the threshold value can be trusted to provide a good segmentation.\n%\n% OBJ is the Gaussian mixture object. See help('gmdistribution.fit') for\n% details. The mean and variance of the Gaussians can be extracted as\n% obj.mu and obj.Sigma, respectively.\n%\n% BW is an output segmentation mask, where voxels == true correspond to\n% the darker object.\n\n% Author: Ramon Casero \n% Copyright \u00a9 2012 University of Oxford\n% Version: 0.5.2\n% \n% University of Oxford means the Chancellor, Masters and Scholars of\n% the University of Oxford, having an administrative office at\n% Wellington Square, Oxford OX1 2JD, UK. \n%\n% This file is part of Gerardus.\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. The offer of this\n% program under the terms of the License is subject to the License\n% being interpreted in accordance with English Law and subject to any\n% action against the University of Oxford being under the jurisdiction\n% of the English Courts.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\n% check arguments\nnarginchk(1, 3);\nnargoutchk(0, 4);\n\n% defaults\nif (nargin < 2 || isempty(nobj))\n nobj = 1;\nend\nif (nargin < 3 || isempty(nsubs))\n nsubs = 1;\nend\n\n% % DEBUG: approximate pdf of whole image\n% [ftot, xout] = hist(im(:), 100);\n% inc = xout(2) - xout(1);\n% ftot = ftot / numel(im) / inc;\n\n% compute gaussian mixture model. Note that we need to randomly subsample\n% the image so that the variance of the Gaussians is not too small\n% (otherwise, gmdistribution.fit() gives an error)\nif (nsubs > 1)\n idx = randi(numel(im), round(numel(im)/nsubs), 1);\n obj = gmdistribution.fit(im(idx), 2);\nelse\n obj = gmdistribution.fit(im(:), 2);\nend\n\n% get mixture of Gaussians parameters\n[mutis, idx] = min(obj.mu);\nvartis = obj.Sigma(idx);\n[mubak, idx] = max(obj.mu);\nvarbak = obj.Sigma(idx);\n\n% % DEBUG: create Gaussian curves for display purposes\n% ftis = normpdf(xout, mutis, sqrt(vartis));\n% fbak = normpdf(xout, mubak, sqrt(varbak));\n\n% compute intersection points between two gaussians\nthr = intersect_gaussians(mutis, mubak, sqrt(vartis), sqrt(varbak));\n\n% keep the one that is between both mean values\nthr = thr(thr > mutis & thr < mubak);\n\n% if there's no intersection point between the maxima, then returning a\n% threshold is meaningless, and instead we return NaN. This is the case,\n% e.g. if there's only background and no object\nif isempty(thr)\n thr = nan;\nend\n\n% quality of the clustering measure. Integral under the tissue Gaussian\n% in [thr, Inf] and integral under the background Gaussian in [-Inf, thr]:\n% the sum represents the Gaussian overlap area. This overlap has a value in\n% [0, 1], with 0 for a lot of overlap, and 1 for no overlap. The quality\n% measure is then 1-overlap\nif (nargout < 2)\n return\nend\nif (isnan(thr))\n q = nan;\nelse\n q = 1 - normcdf(2*mutis-thr, mutis, sqrt(vartis))...\n - normcdf(thr, mubak, sqrt(varbak));\nend\n\n% % DEBUG: plot histogram curves\n% hold off\n% plot(xout, ftot)\n% hold on\n% plot(xout, ftis, 'r')\n% plot(xout, fbak, 'g')\n% plot([thr, thr], [0 max([ftis(:); fbak(:)])], 'k')\n% legend('all', 'tissue', 'background')\n% xlabel('intensity')\n\n% no need to waste time segmenting the image if the user doesn't ask for\n% the output segmentation\nif (nargout < 4)\n return\nend\n\n% threshold segmentation\nim = (im <= thr);\n\n%% remove segmentation noise\n% we could use function bwrmsmallcomp() here, but we don't want having to\n% replicate the segmentation data too many times. That could create memory\n% problems for very large volumes. Instead, we have copied the code in\n% bwrmsmallcomp() directly here:\n\n% get connected components\ncc = bwconncomp(im);\n\n% keep only the largest components to remove background noise\n%\n% note: it's better to clear the whole image, and then add the largest\n% components, than trying to delete the smaller components. The latter\n% doesn't remove all the noise, for some reason.\nlen = cellfun(@length, cc.PixelIdxList);\n[~, idx] = sort(len, 2, 'descend');\nim = zeros(size(im), 'uint8');\nif ~isempty(idx)\n idx = cat(1, cc.PixelIdxList{idx(1:nobj)});\n im(idx) = 1;\nend\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/FiltersToolbox/gmthr_seg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6963803986926176}} {"text": "function printTensor(tensor,order)\n%-fanDTasia ToolBox------------------------------------------------------------------\n% This Matlab script is part of the fanDTasia ToolBox: a Matlab library for Diffusion \n% Weighted MRI (DW-MRI) Processing, Diffusion Tensor (DTI) Estimation, High-order \n% Diffusion Tensor Analysis, Tensor ODF estimation, Visualization and more.\n%\n% A Matlab Tutorial on DW-MRI can be found in:\n% http://www.cise.ufl.edu/~abarmpou/lab/fanDTasia/tutorial.php\n%\n%-CITATION---------------------------------------------------------------------------\n% If you use this software please cite the following work:\n% A. Barmpoutis and B.C. Vemuri, \"A Unified Framework for Estimating Diffusion Tensors \n% of any order with Symmetric Positive-Definite Constraints\", \n% In the Proceedings of ISBI, 2010\n%\n%-DESCRIPTION------------------------------------------------------------------------\n% This function prints in the command line the tensor coefficients of a given tensor\n% (in 3 variables) of a specific order.\n%\n%-USE--------------------------------------------------------------------------------\n% printTensor(tensor,order);\n%\n% tensor: is a vector that contains all the unique coefficients of a symmetric tensor\n% order: is the order of the tensor\n%\n%-DISCLAIMER-------------------------------------------------------------------------\n% You can use this source code for non commercial research and educational purposes \n% only without licensing fees and is provided without guarantee or warrantee expressed\n% or implied. You cannot repost this file without prior written permission from the \n% authors. If you use this software please cite the following work:\n% A. Barmpoutis and B.C. Vemuri, \"A Unified Framework for Estimating Diffusion Tensors \n% of any order with Symmetric Positive-Definite Constraints\", In Proc. of ISBI, 2010.\n%\n%-AUTHOR-----------------------------------------------------------------------------\n% Angelos Barmpoutis, PhD\n% Computer and Information Science and Engineering Department\n% University of Florida, Gainesville, FL 32611, USA\n% abarmpou at cise dot ufl dot edu\n%------------------------------------------------------------------------------------\n\n c=1;\n for i=0:order\n\t\tfor j=0:order-i\n\t\t\tfprintf(1,'D%d%d%d = %.8f\\n',i,j,order-i-j,tensor(c));\n\t\t\tc=c+1;\n end\n end\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/31838-diffusion-kurtosis-tensor-estimation/DKI_Estimation/printTensor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.696380398583861}} {"text": "function [m] = cellssq(x, dim)\n\n% [S] = CELLSSQ(X, DIM) computes the sum of squares, across all cells in x along \n% the dimension dim.\n% \n% X should be an linear cell-array of matrices for which the size in at \n% least one of the dimensions should be the same for all cells \n\nnx = size(x);\nif ~iscell(x) || length(nx)>2 || all(nx>1),\n error('incorrect input for cellssq');\nend\n\nif nargin==1,\n scx1 = cellfun('size', x, 1);\n scx2 = cellfun('size', x, 2);\n if all(scx2==scx2(1)), dim = 2; %let second dimension prevail\n elseif all(scx1==scx1(1)), dim = 1;\n else error('no dimension to compute sum of squares for');\n end\nend\n\nnx = max(nx);\nssmp = cellfun(@sumsq, x, repmat({dim},1,nx), 'UniformOutput', 0);\nm = sum(cell2mat(ssmp), dim); \n\nfunction [s] = sumsq(x, dim)\n\ns = sum(x.^2, dim);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/cellfunction/cellssq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.6963803966501763}} {"text": "function fpc = eci2fpc1(gast, reci, veci)\n\n% convert inertial state vector to flight path coordinates\n\n% input\n\n% gast = greenwich apparent sidereal time (radians)\n% reci = inertial position vector (kilometers)\n% veci = inertial velocity vector (kilometers/second)\n\n% output\n\n% fpc(1) = east longitude (radians)\n% fpc(2) = geocentric declination (radians)\n% fpc(3) = flight path angle (radians)\n% fpc(4) = azimuth (radians)\n% fpc(5) = position magnitude (kilometers)\n% fpc(6) = velocity magnitude (kilometers/second)\n\n% global\n\n% omega = inertial rotation rate (radians/second)\n\n% Orbital Mechanics with MATLAB\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nglobal omega\n\n% compute geocentric radius\n\nrmag = norm(reci);\n\n% compute earth-relative position vector\n\nc(1, 1) = cos(gast);\nc(1, 2) = sin(gast);\nc(1, 3) = 0.0d0;\n\nc(2, 1) = -sin(gast);\nc(2, 2) = cos(gast);\nc(2, 3) = 0.0d0;\n\nc(3, 1) = 0.0d0;\nc(3, 2) = 0.0d0;\nc(3, 3) = 1.0d0;\n\nrecf = c * reci';\n\n% add earth rotation effect\n\nvtmp(1) = veci(1) + reci(2) * omega;\n\nvtmp(2) = veci(2) - reci(1) * omega;\n\nvtmp(3) = veci(3);\n\n% compute relative velocity vector and magnitude\n\nvecf = c * vtmp';\n\nvrel = norm(vecf);\n\n% compute east longitude and geocentric declination\n\nxlong = atan3(recf(2), recf(1));\n\ndecl = asin(recf(3) / rmag);\n\n% compute flight path angle and azimuth\n\nc(1, 1) = -sin(decl) * cos(xlong);\nc(1, 2) = -sin(decl) * sin(xlong);\nc(1, 3) = cos(decl);\n\nc(2, 1) = -sin(xlong);\nc(2, 2) = cos(xlong);\nc(2, 3) = 0.0d0;\n\nc(3, 1) = -cos(decl) * cos(xlong);\nc(3, 2) = -cos(decl) * sin(xlong);\nc(3, 3) = -sin(decl);\n\nvr = c * vecf;\n\nfpa = asin(-vr(3) / vrel);\n\nazimuth = atan3(vr(2), vr(1));\n\n% flight path coordinates\n\nfpc(1) = xlong;\n\nfpc(2) = decl;\n\nfpc(3) = fpa;\n\nfpc(4) = azimuth;\n\nfpc(5) = rmag;\n\nfpc(6) = vrel;\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/38907-a-matlab-script-for-optimal-single-impulse-de-orbit-from-earth-orbits/eci2fpc1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.696348448784079}} {"text": "function sphere_monte_carlo_test01 ( )\n\n%*****************************************************************************80\n%\n%% SPHERE_MONTE_CARLO_TEST01 tests SPHERE01_SAMPLE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n e_test(1:3,1:7) = [ ...\n 0, 0, 0; ...\n 2, 0, 0; ...\n 0, 2, 0; ...\n 0, 0, 2; ...\n 4, 0, 0; ...\n 2, 2, 0; ...\n 0, 0, 4 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST01\\n' );\n fprintf ( 1, ' Use SPHERE01_SAMPLE to estimate integrals over \\n' );\n fprintf ( 1, ' the surface of the unit sphere.\\n' );\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N 1 X^2 Y^2' )\n fprintf ( 1, ' Z^2 X^4 X^2Y^2 Z^4\\n' );\n fprintf ( 1, '\\n' );\n\n n = 1;\n\n while ( n <= 65536 )\n\n [ x, seed ] = sphere01_sample ( n, seed );\n\n fprintf ( 1, ' %8d', n );\n\n for j = 1 : 7\n\n e(1:3,1) = e_test(1:3,j);\n\n value(1:n,1) = monomial_value ( 3, n, e, x );\n\n result = sphere01_area ( ) * sum ( value(1:n) ) / n;\n\n fprintf ( 1, ' %14f', result );\n\n end\n\n fprintf ( 1, '\\n' );\n\n n = 2 * n;\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Exact' );\n for j = 1 : 7\n\n e(1:3,1) = e_test(1:3,j);\n\n result = sphere01_monomial_integral ( e );\n\n fprintf ( 1, ' %14f', result );\n\n end\n fprintf ( 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/sphere_monte_carlo/sphere_monte_carlo_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6962968018577756}} {"text": "function x = inv_triu(U)\n% INV_TRIU Invert upper triangular matrix.\n\nx = solve_triu(U,eye(size(U)));\n%x = inv(U);\n", "meta": {"author": "FuzhenZhuang", "repo": "Transfer-Learning-Toolkit", "sha": "24b5323b354aee844b8b7df9fcad17fdfb191dc4", "save_path": "github-repos/MATLAB/FuzhenZhuang-Transfer-Learning-Toolkit", "path": "github-repos/MATLAB/FuzhenZhuang-Transfer-Learning-Toolkit/Transfer-Learning-Toolkit-24b5323b354aee844b8b7df9fcad17fdfb191dc4/utilities/TLLibrary64/LR/lightspeed/inv_triu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6962967891894893}} {"text": "\nfunction [data g] = pre_diffData(varargin)\n%\n% Apply a difference filter to data. Differencing is a standard operation\n% to improve stationarity of a time series. A first-order difference filter\n% for input X is given by Y(t) = X(t) - X(t-1). This operation can be\n% applied repeatedly to obtain an nth-order difference filter [1]\n%\n% Inputs:\n%\n% EEG: EEG data structure\n%\n% Optional: <'Name',Value> pairs\n%\n% VerbosityLevel: Verbosity level. 0 = no output, 1 = text, 2 = graphical \n% Possible values: 0,1,2 \n% Default value : 1 \n% Input Data Type: real number (double) \n% \n% DifferencingOrder: Differencing order \n% Number of times to difference data \n% Input Range : [0 10] \n% Default value: 1 \n% Input Data Type: real number (double) \n% Outputs:\n%\n% EEG: processed EEG structure\n% g: argument specification structure\n%\n% See Also: pop_pre_prepData(), pre_prepData(), diff()\n%\n% References:\n%\n% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):\n% Theoretical Handbook and User Manual. Section 6.5.1 \n% Available at: http://www.sccn.ucsd.edu/wiki/Sift\n% \n% Author: Tim Mullen 2010, SCCN/INC, UCSD. \n% Email: tim@sccn.ucsd.edu\n\n% This function is part of the Source Information Flow Toolbox (SIFT)\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, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\ng = arg_define([0 1], varargin, ...\n arg_norep('data',mandatory), ...\n arg({'verb','VerbosityLevel'},int32(1),{int32(0) int32(1) int32(2)},'Verbosity level. 0 = no output, 1 = text, 2 = graphical'), ...\n arg({'difforder','DifferencingOrder'},1,[0 10],'Differencing order. Number of times to difference data')); \n\n% commit data to workspace\ndata = g.data;\ng = rmfield(g,'data');\n \n[nchs npnt ntr] = size(data);\n\nif g.difforder==0\n return;\nend\n\nif g.verb\n disp(['Differencing ' num2str(g.difforder) ' times...']); \nend\n\nif g.verb==2\n multiWaitbar('Differencing','Reset','Color',hlp_getNextUniqueColor);\nend\n \ndatmp = zeros(nchs,npnt-g.difforder,ntr);\n\n% difference each trial\nfor tr=1:ntr\n if g.verb==2\n multiWaitbar('Differencing',tr/ntr);\n end\n datmp(:,:,tr) = diff(data(:,:,tr),g.difforder,2);\nend\n\n% differencing reduces the number of datapoints by difforder\n% so here we insert difforder random samples at the beginning \n% of each time-series\nnoiseVar = 0.01*var(datmp(:));\ndata = cat(2,noiseVar*randn(nchs,g.difforder,ntr),datmp);\n\nif g.verb==2\n multiWaitbar('Differencing','Close');\nend\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/pre/pre_diffData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.6962967860436533}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n% \n%\n% \tProblem 4- Step responses \n\n\nz1=[];\np1=[-1 -.2+10j -.2-10j];\nk1=10; \n\nH=zpk(z1,p1,k1);\n\nt=0:.1:20\ny1=step(H,t) \n\n\n\nz2=-3\np2=[-1 -.2+10j -.2-10j];\nk2=10; \n\n[num,den]=zp2tf(z2,p2,k2);\n\ny2=step(num,den,t)\n\nplot(t,y1,t,y2, ':')\nlegend('Step1', 'Step2')\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/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/11/c1115d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.6962961480108691}} {"text": "function [y,f]=v_zoomfft(x,n,m,s,d)\n%V_ZOOMFFT DTFT evaluated over a linear frequency range Y=(X,N,M,S,D)\n% Inputs:\n% x vector (or matrix)\n% n reciprocal of normalized frequency increment (can be non-integer).\n% The frequency increment is fs/n where fs is the sample frequency\n% [default n=size(x,d)]\n% m mumber of output points is floor(m) [default m=n]\n% s starting frequency index (can be non-integer).\n% The starting frequency is s*fs/n [default s=0]\n% d dimension along which to do fft [default d=first non-singleton]\n%\n% Outputs:\n% y Output dtft coefficients. y has the same dimensions as x except\n% that size(y,d)=floor(m).\n% f(1,m) normalized frequencies (1 corresponds to fs)\n%\n% This routine allows the evaluation of the DFT over an arbitrary range of\n% frequencies; as its name implies this lets you zoom into a narrow portion\n% of the spectrum.\n% The DTFT of X will be evaluated along dimension D at the M frequencies\n% f=fs*(s+(0:m-1))/n where fs is the sample frequency. Note that N and S\n% need not be integers although M will be rounded down to an integer.\n% Thus v_zoomfft(x,n,n,0,d) is equivalent to fft(x,n,d) for n>=length(x).\n\n% [1] L.R.Rabiner, R.W.Schafer and C.M.Rader, \"The chirp z-transform algorithm\"\n% IEEE Trans. Audio Electroacoustics 17 (2), 86\ufffd92 (1969). \n\n% Copyright (C) Mike Brookes 2007\n% Version: $Id: v_zoomfft.m 10865 2018-09-21 17:22:45Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\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 can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\npersistent n0 k0 s0 m0 b c h g\ne=size(x);\np=prod(e);\nif nargin<5\n d=find(e>1);\n if ~isempty(d)\n d=d(1);\n else\n d=1;\n end\nend\nk=e(d);\nq=p/k;\nif d==1\n z=reshape(x,k,q);\nelse\n z=shiftdim(x,d-1);\n r=size(z);\n z=reshape(z,k,q);\nend\nif nargin<2 || isempty(n)\n n=k;\nend\nif nargin<3 || isempty(m)\n m=floor(n);\nelse\n m=floor(m);\nend\nif nargin<4 || isempty(s)\n s=0;\nend\nl=pow2(nextpow2(m+k-1)); % round up to next power of 2\nif n==fix(n) && s==fix(s) && n<2*l && n>=k\n a=fft(z,n,1); % quickest to do a normal fft\n y=a(1+mod(s:s+m-1,n),:);\nelse\n % can precaluclate all this for fixed n, k, s and m\n if isempty(b) || n~=n0 || k~=k0 || s~=s0 || m~=m0\n n0=n;\n k0=k;\n s0=s;\n m0=m;\n b=exp(1i*pi*mod((s+(1-k:m-1)').^2,2*n)/n);\n c=conj(b(k:k+m-1));\n h=fft(b,l,1);\n g=exp(-1i*pi*mod(((0:k-1)').^2,2*n)/n);\n end\n a=ifft(fft(z.*repmat(g,1,q),l,1).*repmat(h,1,q)); % calculate correlation\n y=a(k:k+m-1,:).*repmat(c,1,q);\nend\nif d==1\n e(d)=m;\n y=reshape(y,e);\nelse\n r(1)=m;\n y=shiftdim(reshape(y,r),length(e)+1-d);\nend\nf=(s+(0:m-1))/n;", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_zoomfft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.6962961374150672}} {"text": "function varargout = rodr(varargin)\n% VL_RODR Rodrigues' formula\n% R = VL_RODR(OM) where OM a 3-dimensional column vector computes the\n% Rodrigues' formula of OM, returning the rotation matrix R =\n% expm(vl_hat(OM)).\n%\n% [R,DR] = VL_RODR(OM) computes also the derivative of the Rodrigues\n% formula. In matrix notation this is the expression\n%\n% d(vec expm(vl_hat(OM)) )\n% dR = ----------------------.\n% d om^T\n%\n% [R,DR]=VL_RODR(OM) when OM is a 3xK matrix repeats the operation for\n% each column (or equivalently matrix with 3*K elements). In this\n% case R and DR are arrays with K slices, one per rotation.\n%\n% See also: VL_IRODR(), VL_HELP().\n[varargout{1:nargout}] = vl_rodr(varargin{:});\n", "meta": {"author": "yihui-he", "repo": "panorama", "sha": "0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b", "save_path": "github-repos/MATLAB/yihui-he-panorama", "path": "github-repos/MATLAB/yihui-he-panorama/panorama-0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b/lib/vlfeat-0.9.20/toolbox/noprefix/rodr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.6962961336560902}} {"text": "% VGG MultiView Compute Library\n%\n% Conversions \n% vgg_KR_from_P - extract K, R from P such that P = K*R*[eye(3) -t]\n% vgg_F_from_P - fundamental matrix from 2 cameras\n% vgg_P_from_F - 2 camera matrices from fundamental matrix\n% vgg_T_from_P - trifocal tensor from 3 cameras\n% vgg_H_from_2P_plane - inter-image homography from 2 cameras and 3D plane\n% vgg_H_from_P_plane - projection matrix from image onto 3D plane\n% vgg_plane_from_2P_H - 3D plane from 2 cameras and inter-image homography\n%\n% Multiview tensors from image correspondences\n% vgg_H_from_x_lin - homography from points in 2 images, linear method\n% vgg_H_from_x_nonlin - MLE of the above, by nonlinear method\n% vgg_Haffine_from_x_MLE - MLE of affine transformation from points in 2 images, linear\n% vgg_F_from_7pts_2img - fundamental matrix from 7 points in 2 images\n% vgg_PX_from_6pts_3img - cameras and world points from 6 points in 3 images\n%\n% Preconditioning for estimation\n% vgg_conditioner_from_image - conditioning shift+scaling from image dimensions\n% vgg_conditioner_from_pts - conditioning shift+scaling from image points\n%\n% Self-calibration and similar\n% vgg_signsPX_from_x - swaps signs of P and X so that projection scales are positive\n% vgg_selfcalib_qaffine - quasi-affine from projective reconstruction\n% vgg_selfcalib_metric_vansq - metric from projective and 3 orthogonal principal directions and square pixels\n%\n% Estimation\n% vgg_X_from_xP_lin - 3D point from image projections and cameras, linear\n% vgg_X_from_xP_nonlin - MLE of that, non-linear method\n% vgg_line3d_from_lP_lin - 3D line segment from image line segments and cameras, linear\n% vgg_line3d_from_lP_nonlin - MLE of that, non-linear method\n%\n% 3D lines representations\n% vgg_line3d_pv_from_XY - Pluecker vector from 2 points on the line\n% vgg_line3d_pv_from_pm - Pluecker matrix from Pluecker vector\n% vgg_line3d_pm_from_pv - Pluecker vector from Pluecker matrix\n% vgg_line3d_Ppv - rearrange camera matrix to project Pluecker vector to image line\n% vgg_line3d_pv_from_2planes - Pluecker vector from 2 planes meeting in the line\n% vgg_line3d_XY_from_pm - 2 points on 3D line from Pluecker matrix\n% vgg_line3d_XY_from_pv - 2 points on 3D line from Pluecker vector\n% (vgg_contreps - dual of Pluecker matrix of 3D line)\n%\n% Auxiliary & miscellaneous\n% vgg_get_homg - adding row of ones\n% vgg_get_nonhomg - dividing by the final coordinates\n% vgg_projective_basis_2d\n% vgg_rms_error\n% vgg_scatter_plot_homg\n% vgg_scatter_plot\n", "meta": {"author": "jmmanley", "repo": "VGG-Multiple-View-Geometry", "sha": "f114712de03082bb97229eaf2a65981908b64127", "save_path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry", "path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry/VGG-Multiple-View-Geometry-f114712de03082bb97229eaf2a65981908b64127/vgg_multiview/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.6962961210924653}} {"text": "function mtx = CreateMatrixFromPrimaries(R, G, B, Wp)\n%\n% mtx = CreateMatrixFromPrimaries(R, G, B, Wp)\n%\n%\n% Input:\n% -R: the red primary for the given color space expressed as an\n% XYZ color.\n% -G: the green primary for the given color space expressed as an\n% XYZ color.\n% -B: the blue primary for the given color space expressed as an\n% XYZ color.\n% -Wp: the white-point primary for the given color space expressed as an\n% XYZ color.\n%\n% Output:\n% -mtx: a conversion matrix from XYZ color space to the color\n% space defined by the three input primaries (R, G, and B) and\n% white point (Wp).\n%\n% Copyright (C) 2018 Francesco Banterle\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%\n\nA_R = [R(1) R(2) R(3) 0 0 0 0 0 0; ...\n 0 0 0 R(1) R(2) R(3) 0 0 0; ...\n 0 0 0 0 0 0 R(1) R(2) R(3)];\nb_R = [1; 0; 0];\n\nA_G = [G(1) G(2) G(3) 0 0 0 0 0 0; ...\n 0 0 0 G(1) G(2) G(3) 0 0 0; ...\n 0 0 0 0 0 0 G(1) G(2) G(3)];\nb_G = [0; 1; 0];\n\nA_B = [B(1) B(2) B(3) 0 0 0 0 0 0; ...\n 0 0 0 B(1) B(2) B(3) 0 0 0; ...\n 0 0 0 0 0 0 B(1) B(2) B(3)];\nb_B = [0; 0; 1];\n\nA_Wp = [Wp(1) Wp(2) Wp(3) 0 0 0 0 0 0; ...\n 0 0 0 Wp(1) Wp(2) Wp(3) 0 0 0; ...\n 0 0 0 0 0 0 Wp(1) Wp(2) Wp(3)];\n \nb_Wp = [1; 1; 1];\n\nA = [A_R; A_G; A_B; A_Wp];\nb = [b_R; b_G; b_B; b_Wp];\n\nmtx = A \\ b;\n\nmtx = reshape(mtx, 3, 3)';\n\nend\n", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/ColorSpace/CreateMatrixFromPrimaries.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347124, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6962681108288967}} {"text": "function [X,freq] = absoluteValFFT(x,Fs)\nN = length(x); %get the number of points\nk = 0:N-1; %create a vector from 0 to N-1\nT = N/Fs; %get the frequency interval\nfreq = k/T; %create the frequency range\nX = fft(x)/N*2; % normalize the data\n\n%only want the first half of the FFT, since it is redundant\ncutOff = ceil(N/2);\n\n%take only the first half of the spectrum\nX = X(1:cutOff,:,:);\nX = abs(X/N);\nfreq = freq(1:cutOff);\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_RobotArm/absoluteValFFT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6962319195701443}} {"text": "\nfunction Y=EWMASTD(X,d)\n\n\n% Y=EWMASTD(X,d) returns the EWMA (Exponentially Weighted Moving Average)\n% standard deviation using the historical returns in vector X and a decay\n% factor, d.\n% % ======================================================================\n%\n% Author: Lorenzo Brancali\n% E-mail: lbrancali@gmail.com\n% Date: 20th Febryary 2012\n%\n% % ======================================================================\n\n\n\n\nt=length(X);\n\nfor i=1:length(X)-1\n \n F(i,:)=((d^(i-1))*(X(t-i,:)-mean(X))^2);\n \n \nend\n \n\nY=sqrt((1-d)*sum(F));\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/35539-ewma-st-dev/ewmastd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6962319189201591}} {"text": "function chebyshev_polynomial_test05 ( )\n\n%*****************************************************************************80\n%\n%% CHEBYSHEV_POLYNOMIAL_TEST05 tests T_QUADRATURE_RULE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 March 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHEBYSHEV_POLYNOMIAL_TEST05:\\n' );\n fprintf ( 1, ' T_QUADRATURE_RULE computes the quadrature rule\\n' );\n fprintf ( 1, ' associated with T(n,x);\\n' );\n\n n = 7;\n [ x, w ] = t_quadrature_rule ( n );\n\n r8vec2_print ( n, x, w, ' X W' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Use the quadrature rule to estimate:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Q = Integral ( -1 <= X <= +1 ) X^E / sqrt ( 1-x^2) dx\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' E Q_Estimate Q_Exact\\n' );\n fprintf ( 1, '\\n' );\n\n for e = 0 : 2 * n - 1\n if ( e == 0 )\n f = ones ( n, 1 );\n else\n f(1:n) = x(1:n).^e;\n end\n q = w' * f;\n q_exact = t_integral ( e );\n fprintf ( 1, ' %2d %14g %14g\\n', e, q, q_exact );\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/chebyshev_polynomial/chebyshev_polynomial_test05.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.6962289787173852}} {"text": "%MODESEEK Clustering by mode-seeking\n% \n% \t[LAB,J] = MODESEEK(D,K)\n% \n% INPUT\n% D Distance matrix or distance dataset (square)\n% K Number of neighbours to search for local mode (default: 10)\n%\n% OUTPUT\n% LAB Cluster assignments, 1..K\n% J Indices of modal samples\n%\n% DESCRIPTION\n% A K-NN modeseeking method is used to assign each object to its nearest mode.\n%\n% REFERENCES\n% 1. Cheng, Y. \"Mean shift, mode Seeking, and clustering\", IEEE Transactions\n% on Pattern Analysis and Machine Intelligence, vol. 17, no. 8, pp. 790-799,\n% 1995.\n% \n% SEE ALSO (PRTools Guide)\n% MAPPINGS, DATASETS, PRKMEANS, HCLUST, KCENTRES, PROXM\n\n% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com\n% Faculty EWI, Delft University of Technology\n% P.O. Box 5031, 2600 GA Delft, The Netherlands\n\n% $Id: modeseek.m,v 1.2 2006/03/08 22:06:58 duin Exp $\n\nfunction [assign,J] = modeseek (d,k)\n\n\t\tif (nargin < 2)\n\t\tprwarning(1,'No k supplied, assuming k = 10'); \n\t\tk = 10;\n end\n \n\t[m,n] = size(d);\n \n if numel(k) > 1\n assign = zeros(m,numel(k));\n for j = 1:numel(k)\n assign(:,j) = feval(mfilename,d,k(j));\n end\n return\n end\n \n d = d'; % correction to analyse asymmetric matrices horizontally\n \n\tif (m ~= n), error('distance matrix should be square'); end\n\tif (k < 2), error('neighborhood size should be at least 2'); end\n\tif (k > n), error('k too large for this dataset'); end\n\n\t[d,J] = sort(+d,1);\t\t % Find neighbours.\n\tf = 1./(d(k,:)+realmin); % Calculate densities.\n\tJ(k+1:end,:) = []; \t % Just retain indices of neighbours.\n\n\t% Find indices of local modes in neighbourhood.\n\t[dummy,I] = max(reshape(f(J),size(J)));\n\n\t% Translate back to indices in all the data. N now contains the\n\t% index of the nearest neighbour in the K-neighbourhood.\n\tN = J(I+[0:k:k*(m-1)]);\n\n\t% Re-assign samples to the sample their nearest neighbour is assigned to.\n\t% Iterate until assignments don't change anymore. Samples that then point \n\t% to themselves are modes; all other samples point to the closest mode.\n\n\tM = N(N);\n\twhile (any(M~=N))\n\t\tN = M; M = N(N);\n\tend\n\n\t% Use renumlab to obtain assignments 1, 2, ... and the list of unique\n\t% assignments (the modes).\n\n\t[assign,J] = renumlab(M');\n\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/modeseek.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.6961820212649973}} {"text": "function [Z] = MCWNNM_ADMM1( Y, NSig, Par )\n% This routine solves the following weighted nuclear norm optimization problem with column weights,\n%\n% min_{X, Z} ||W(Y-X)||_F^2 + ||Z||_w,* s.t. X = Z\n%\n% Inputs:\n% Y -- 3p^2 x M dimensional noisy matrix, D is the data dimension, and N is the number of image patches.\n% NSig -- 3p^2 x 1 dimensional vector of weights\n% Par -- structure of parameters\n% Output:\n% Z -- 3p^2 x M dimensional denoised matrix\n\n% tol = 1e-8;\nif ~isfield(Par, 'maxIter')\n Par.maxIter = 10;\nend\nif ~isfield(Par, 'rho')\n Par.rho = 1;\nend\nif ~isfield(Par, 'mu')\n Par.mu = 1;\nend\nif ~isfield(Par, 'display')\n Par.display = true;\nend\n% Initializing optimization variables\n% Intialize the weight matrix W\nmNSig = min(NSig);\nW = (mNSig+eps) ./ (NSig+eps);\n% Initializing optimization variables\nX = zeros(size(Y));\nZ = zeros(size(Y));\nA = zeros(size(Y));\n%% Start main loop\niter = 0;\nPatNum = size(Y,2);\nTempC = Par.Constant * sqrt(PatNum) * mNSig^2;\n% TempC = Par.Constant * sqrt(PatNum);\n% Par.rho = Par.rho * (mNSig+eps)^2;\n\nwhile iter < Par.maxIter\n iter = iter + 1;\n \n % update X, fix Z and A\n % min_{X} ||W * Y - W * X||_F^2 + 0.5 * rho * ||X - Z + 1/rho * A||_F^2\n X = diag(1 ./ (W.^2 + 0.5 * Par.rho)) * (diag(W.^2) * Y + 0.5 * Par.rho * Z - 0.5 * A);\n \n % update Z, fix X and A\n % min_{Z} ||Z||_*,w + 0.5 * rho * ||Z - (X + 1/rho * A)||_F^2\n Temp = X + A/Par.rho;\n [U, SigmaTemp, V] = svd(full(Temp), 'econ');\n [SigmaZ, svp] = ClosedWNNM(diag(SigmaTemp), 2/Par.rho*TempC, eps);\n Z = U(:, 1:svp) * diag(SigmaZ) * V(:, 1:svp)';\n % % check the convergence conditions\n % stopC = max(max(abs(X - Z)));\n % if Par.display && (iter==1 || mod(iter,10)==0 || stopC1\n edges = zeros([0 4]);\n x0 = origin(1);\n y0 = origin(2);\n\n % find all x coordinate\n x1 = bounds(1) + mod(x0-bounds(1), dx);\n x2 = bounds(3) - mod(bounds(3)-x0, dx);\n lx = (x1:dx:x2)';\n\n % horizontal edges : first find y's\n y1 = bounds(2) + mod(y0-bounds(2), dy);\n y2 = bounds(4) - mod(bounds(4)-y0, dy);\n ly = (y1:dy:y2)';\n \n % number of points in each coord, and total number of points\n ny = length(ly);\n nx = length(lx);\n \n if bounds(1)-x1+dx0\n varargout{1} = pts;\n \n if nargout>1\n varargout{2} = edges;\n end\nend", "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/hexagonalGrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.696137421194878}} {"text": "function prob_test070 ( )\n\n%*****************************************************************************80\n%\n%% TEST070 tests FACTORIAL_STIRLING, I4_FACTORIAL;\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST070\\n' );\n fprintf ( 1, ' FACTORIAL_STIRLING computes Stirling''s\\n' );\n fprintf ( 1, ' approximate factorial function;\\n' );\n fprintf ( 1, ' I4_FACTORIAL evaluates the factorial function;\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N Stirling N!\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 0 : 20\n value = factorial_stirling ( i );\n fprintf ( 1, ' %6d %14f %20d\\n', i, value, i4_factorial ( i ) );\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/prob_test070.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.6961374100962742}} {"text": "%points2contour\n%Tristan Ursell\n%Sept 2013\n%\n%[Xout,Yout]=points2contour(Xin,Yin,P,direction)\n%[Xout,Yout]=points2contour(Xin,Yin,P,direction,dlim)\n%[Xout,Yout,orphans]=points2contour(Xin,Yin,P,direction,dlim)\n%[Xout,Yout,orphans,indout]=points2contour(Xin,Yin,P,direction,dlim)\n%\n%Given any list of 2D points (Xin,Yin), construct a singly connected\n%nearest-neighbor path in either the 'cw' or 'ccw' directions. The code \n%has been written to handle square and hexagon grid points, as well as any\n%non-grid arrangement of points. \n%\n%'P' sets the point to begin looking for the contour from the original\n%ordering of (Xin,Yin), and 'direction' sets the direction of the contour, \n%with options 'cw' and 'ccw', specifying clockwise and counter-clockwise, \n%respectively. \n%\n%The optional input parameter 'dlim' sets a distance limit, if the distance\n%between a point and all other points is greater than or equal to 'dlim',\n%the point is left out of the contour.\n%\n%The optional output 'orphans' gives the indices of the original (Xin,Yin)\n%points that were not included in the contour.\n%\n%The optional output 'indout' is the order of indices that produces\n%Xin(indout)=Xout and Yin(indout)=Yout.\n%\n%There are many (Inf) situations where there is no unique mapping of points\n%into a connected contour -- e.g. any time there are more than 2 nearest \n%neighbor points, or in situations where the nearest neighbor matrix is \n%non-symmetric. Picking a different P will result in a different contour.\n%Likewise, in cases where one point is far from its neighbors, it may be\n%orphaned, and only connected into the path at the end, giving strange\n%results.\n%\n%The input points can be of any numerical class.\n%\n%Note that this will *not* necessarily form the shortest path between all\n%the points -- that is the NP-Hard Traveling Salesman Problem, for which \n%there is no deterministic solution. This will, however, find the shortest\n%path for points with a symmetric nearest neighbor matrix.\n%\n%see also: bwtraceboundary\n%\n%Example 1: continuous points\n%N=200;\n%P=1;\n%theta=linspace(0,2*pi*(1-1/N),N);\n%[~,I]=sort(rand(1,N));\n%R=2+sin(5*theta(I))/3;\n%\n%Xin=R.*cos(theta(I));\n%Yin=R.*sin(theta(I));\n%\n%[Xout,Yout]=points2contour(Xin,Yin,P,'cw');\n%\n%figure;\n%hold on\n%plot(Xin,Yin,'b-')\n%plot(Xout,Yout,'r-','Linewidth',2)\n%plot(Xout(2:end-1),Yout(2:end-1),'k.','Markersize',15)\n%plot(Xout(1),Yout(1),'g.','Markersize',15)\n%plot(Xout(end),Yout(end),'r.','Markersize',15)\n%xlabel('X')\n%ylabel('Y')\n%axis equal tight\n%title(['Black = original points, Blue = original ordering, Red = new ordering, Green = starting points'])\n%box on\n%\n%\n%Example 2: square grid\n%P=1;\n%\n%Xin=[1,2,3,4,4,4,4,3,2,1,1,1];\n%Yin=[0,0,0,0,1,2,3,3,2,2,1,0];\n%\n%[Xout,Yout]=points2contour(Xin,Yin,P,'cw');\n%\n%figure;\n%hold on\n%plot(Xin,Yin,'b-')\n%plot(Xout,Yout,'r-','Linewidth',2)\n%plot(Xout(2:end-1),Yout(2:end-1),'k.','Markersize',15)\n%plot(Xout(1),Yout(1),'g.','Markersize',15)\n%plot(Xout(end),Yout(end),'r.','Markersize',15)\n%xlabel('X')\n%ylabel('Y')\n%axis equal tight\n%box on\n%\n%Example 3: continuous points, pathological case\n%N=200;\n%P=1;\n%theta=linspace(0,2*pi*(1-1/N),N);\n%[~,I]=sort(rand(1,N));\n%R=2+sin(5*theta(I))/3;\n%\n%Xin=(1+rand(1,N)/2).*R.*cos(theta(I));\n%Yin=(1+rand(1,N)/2).*R.*sin(theta(I));\n%\n%[Xout,Yout]=points2contour(Xin,Yin,P,'cw');\n%\n%figure;\n%hold on\n%plot(Xin,Yin,'b-')\n%plot(Xout,Yout,'r-','Linewidth',2)\n%plot(Xout(2:end-1),Yout(2:end-1),'k.','Markersize',15)\n%plot(Xout(1),Yout(1),'g.','Markersize',15)\n%plot(Xout(end),Yout(end),'r.','Markersize',15)\n%xlabel('X')\n%ylabel('Y')\n%axis equal tight\n%title(['Black = original points, Blue = original ordering, Red = new ordering, Green = starting points'])\n%box on\n%\n%Example 4: continuous points, distance limit applied\n%N=200;\n%P=1;\n%theta=linspace(0,2*pi*(1-1/N),N);\n%[~,I]=sort(rand(1,N));\n%R=2+sin(5*theta(I))/3;\n%R(2)=5; %the outlier\n%\n%Xin=(1+rand(1,N)/16).*R.*cos(theta(I));\n%Yin=(1+rand(1,N)/16).*R.*sin(theta(I));\n%\n%[Xout,Yout,orphans,indout]=points2contour(Xin,Yin,P,'cw',1);\n%\n%figure;\n%hold on\n%plot(Xin,Yin,'b-')\n%plot(Xin(orphans),Yin(orphans),'kx')\n%plot(Xin(indout),Yin(indout),'r-','Linewidth',2)\n%plot(Xout(2:end-1),Yout(2:end-1),'k.','Markersize',15)\n%plot(Xout(1),Yout(1),'g.','Markersize',15)\n%plot(Xout(end),Yout(end),'r.','Markersize',15)\n%xlabel('X')\n%ylabel('Y')\n%axis equal tight\n%title(['Black = original points, Blue = original ordering, Red = new ordering, Green = starting points'])\n%box on\n%\n\nfunction [Xout,Yout,varargout]=points2contour(Xin,Yin,P,direction,varargin)\n\n%check to make sure the vectors are the same length\nif length(Xin)~=length(Yin)\n error('Input vectors must be the same length.')\nend\n\n%check to make sure point list is long enough\nif length(Xin)<2\n error('The point list must have more than two elements.')\nend\n\n%check distance limit\nif ~isempty(varargin)\n dlim=varargin{1};\n if dlim<=0\n error('The distance limit parameter must be greater than zero.')\n end\nelse\n dlim=-1;\nend\n\n%check direction input\nif and(~strcmp(direction,'cw'),~strcmp(direction,'ccw'))\n error(['Direction input: ' direction ' is not valid, must be either \"cw\" or \"ccw\".'])\nend\n\n%check to make sure P is in the right range\nP=round(P);\nnpts=length(Xin);\n\nif or(P<1,P>npts)\n error('The starting point P is out of range.')\nend\n\n%adjust input vectors for starting point\nif size(Xin,1)==1\n Xin=circshift(Xin,[0,1-P]);\n Yin=circshift(Yin,[0,1-P]);\nelse\n Xin=circshift(Xin,[1-P,0]);\n Yin=circshift(Yin,[1-P,0]);\nend\n\n%find distances between all points\nD=zeros(npts,npts);\nfor q1=1:npts\n D(q1,:)=sqrt((Xin(q1)-Xin).^2+(Yin(q1)-Yin).^2);\nend\n\n%max distance\nmaxD=max(D(:));\n\n%avoid self-connections\nD=D+eye(npts)*maxD;\n\n%apply distance contraint by removing bad points and starting over\nif dlim>0\n D(D>=dlim)=-1;\n \n %find bad points\n bad_pts=sum(D,1)==-npts;\n orphans=find(bad_pts);\n \n %check starting point\n if sum(orphans==P)>0\n error('The starting point index is a distance outlier, choose a new starting point.')\n end\n \n %get good points\n Xin=Xin(~bad_pts);\n Yin=Yin(~bad_pts);\n \n %number of good points\n npts=length(Xin);\n \n %find distances between all points\n D=zeros(npts,npts);\n for q1=1:npts\n D(q1,:)=sqrt((Xin(q1)-Xin).^2+(Yin(q1)-Yin).^2);\n end\n \n %max distance\n maxD=max(D(:));\n \n %avoid self-connections\n D=D+eye(npts)*maxD;\nelse\n orphans=[];\n bad_pts=zeros(size(Xin));\nend\n\n%tracking vector (has this original index been put into the ordered list?)\ntrack_vec=zeros(1,npts);\n\n%construct directed graph\nXout=zeros(1,npts);\nYout=zeros(1,npts);\nindout0=zeros(1,npts);\n\nXout(1)=Xin(1);\nYout(1)=Yin(1);\nindout0(1)=1;\n\np_now=1;\ntrack_vec(p_now)=1;\nfor q1=2:npts \n %get current row of distance matrix\n curr_vec=D(p_now,:);\n \n %remove used points\n curr_vec(track_vec==1)=maxD;\n \n %find index of closest non-assigned point\n p_temp=find(curr_vec==min(curr_vec),1,'first');\n \n %reassign point\n Xout(q1)=Xin(p_temp);\n Yout(q1)=Yin(p_temp);\n \n %move index\n p_now=p_temp;\n \n %update tracking\n track_vec(p_now)=1;\n \n %update index vector\n indout0(q1)=p_now;\nend\n\n%undo the circshift\ntemp1=find(~bad_pts);\nindout=circshift(temp1(indout0),[P,0]);\n\n%%%%%%% SET CONTOUR DIRECTION %%%%%%%%%%%%\n%contour direction is a *global* feature that cannot be determined until\n%all the points have been sequentially ordered.\n\n%calculate tangent vectors\ntan_vec=zeros(npts,3);\nfor q1=1:npts\n if q1==npts\n tan_vec(q1,:)=[Xout(1)-Xout(q1),Yout(1)-Yout(q1),0];\n tan_vec(q1,:)=tan_vec(q1,:)/norm(tan_vec(q1,:));\n else\n tan_vec(q1,:)=[Xout(q1+1)-Xout(q1),Yout(q1+1)-Yout(q1),0];\n tan_vec(q1,:)=tan_vec(q1,:)/norm(tan_vec(q1,:));\n end\nend\n\n%determine direction of contour\nlocal_cross=zeros(1,npts);\nfor q1=1:npts\n if q1==npts\n cross1=cross(tan_vec(q1,:),tan_vec(1,:));\n else\n cross1=cross(tan_vec(q1,:),tan_vec(q1+1,:));\n end\n local_cross(q1)=asin(cross1(3));\nend\n\n%figure out current direction\nif sum(local_cross)<0\n curr_dir='cw';\nelse\n curr_dir='ccw';\nend\n \n%set direction of the contour\nif and(strcmp(curr_dir,'cw'),strcmp(direction,'ccw'))\n Xout=fliplr(Xout);\n Yout=fliplr(Yout);\nend\n\n%varargout\nif nargout==3\n varargout{1}=orphans;\nend\n\nif nargout==4\n varargout{1}=orphans;\n varargout{2}=indout;\nend\n\ndisp('finished')\n\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/35488-connect-randomly-ordered-2d-points-into-a-minimal-nearest-neighbor-closed-contour/points2contour.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339797047029, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.6960880826690804}} {"text": "function geometry_test049 ( )\n\n%*****************************************************************************80\n%\n%% TEST049 tests PARALLELOGRAM_CONTAINS_POINT_3D.\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 ntest = 5;\n%\n% In, Out, Out, Out, Out\n%\n ptest(1:3,1:ntest) = [ ...\n 1.0, 1.0, 0.5; ...\n 3.0, 3.0, 0.0; ...\n 0.5, 0.5, -0.1; ...\n 0.1, 0.1, 0.5; ...\n 1.5, 1.6, 0.5 ]';\n\n p1(1:3,1) = [ 0.0; 0.0; 0.0 ];\n p2(1:3,1) = [ 2.0; 2.0; 0.0 ];\n p3(1:3,1) = [ 1.0; 1.0; 1.0 ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST049\\n' );\n fprintf ( 1, ' PARALLELOGRAM_CONTAINS_POINT_3D determines if a point\\n' );\n fprintf ( 1, ' is within a parallelogram in 3D.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' P Inside?\\n' );\n fprintf ( 1, '\\n' );\n\n for j = 1 : ntest\n\n p(1:3,1) = ptest(1:3,j);\n\n inside = parallelogram_contains_point_3d ( p1, p2, p3, p );\n\n fprintf ( 1, ' %12f %12f %12f %d\\n', p(1:3,1), inside );\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/geometry/geometry_test049.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.696088053625103}} {"text": "function D = Floyd_Steinberg_Dithering(G)\n% ================================================================\n% FUNCTION Floyd_Steinberg Dithering Algorithm\n%\n% Input: G = a 8-bit grayscale / color image\n% Output: D = dithered image of G's format with only values 0 and 255 of the same \n% ----------------------------------------------------------------\n% Demo:\n% G = imread('peppers.png');\n% D = Floyd_Steinberg_Dithering(G);\n% figure('position',[50,50,600,900]),subplot(211),imshow(G),title('Original Image');\n% subplot(212),imshow(D),title('Dithered Image');\n% ----------------------------------------------------------------\n% For more details about Floyd Steinberg Dithering Algorithm\n% Please check\n% http://en.wikipedia.org/wiki/Floyd%E2%80%93Steinberg_dithering\n% ----------------------------------------------------------------\n% Oct. 18th 2011\n% By Yue Wu,\n% Department of Electrical and Computer Engineering\n% Tufts University,\n% Medford, MA 02155\n% ================================================================\n\nswitch size(G,3)\n case 1\n G = double(G); % convert the original image from unit8 to double\n D = zeros(size(G)); % initialize dithered image D\n [M,N] = size(G); % extract size information of the original image\n for r = 1:M\n % applying '2'-like scanning order \n % ->>>>>>>>>>>>>>>>>>>>>>>-\n % |\n % -<<<<<<<<<<<<<<<<<<<<<<<-\n % |\n % ->>>>>>>>>>>>>>>>>>>>>>>-\n if mod(r,2) == 0 % scan pixel from left to right\n cOrder = 1:N; \n direction = 'l2r';\n else % scan pixel from right to left\n cOrder = N:-1:1; \n direction = 'r2l';\n end \n for c = cOrder\n tP = G(r,c); % current pixel intensity\n % pick nearest intensity scale two options 0 or 255\n if tP>=128 % close to 255\n D(r,c) = 255; % pick 255\n else % close to 0\n D(r,c) = 0; % pick 0\n end\n eP = tP-D(r,c); % difference before and after selection\n % diffuse difference eP to neighbor pixels\n if r~=M % deal with none bottom rows\n switch direction\n case 'l2r'\n if c == 1 % left-most pixel case\n G(r,c+1) = G(r,c+1)+eP*7/13;\n G(r+1,c) = G(r+1,c)+eP*5/13;\n G(r+1,c+1) = G(r+1,c+1)+eP*1/13; \n elseif c == N % deal with the right-most pixel case\n G(r+1,c) = G(r+1,c)+eP*5/8;\n G(r+1,c-1) = G(r+1,c-1)+eP*3/8;\n else % the normal case\n G(r,c+1) = G(r,c+1)+eP*7/16;\n G(r+1,c) = G(r+1,c)+eP*5/16;\n G(r+1,c+1) = G(r+1,c+1)+eP*1/16;\n G(r+1,c-1) = G(r+1,c-1)+eP*3/16;\n end\n case 'r2l'\n if c == N % right-most pixel case\n G(r,c-1) = G(r,c-1)+eP/2;\n G(r+1,c) = G(r+1,c)+eP*3/8;\n G(r+1,c-1) = G(r+1,c-1)+eP*1/8; \n elseif c == 1 % left-most pixel case\n G(r+1,c) = G(r+1,c)+eP*5/8;\n G(r+1,c+1) = G(r+1,c+1)+eP*3/8;\n else % normal case\n G(r,c-1) = G(r,c-1)+eP*7/16;\n G(r+1,c) = G(r+1,c)+eP*5/16;\n G(r+1,c-1) = G(r+1,c-1)+eP*1/16;\n G(r+1,c+1) = G(r+1,c+1)+eP*3/16;\n end\n end\n else % deal with the bottom row\n switch direction\n case 'l2r'\n if c ~=N % normal case\n G(r,c+1) = G(r,c+1)+eP;\n end\n case 'r2l'\n if c ~= 1 % normal case\n G(r,c-1) = G(r,c-1)+eP;\n end\n end\n end\n end\n end\n otherwise % if the input image is not one-layer gray-scale image, then apply algorithm with respect to each layer\n for i = 1:size(G,3)\n tD = Floyd_Steinberg_Dithering(G(:,:,i));\n D(:,:,i) = tD;\n end\nend\n\nD = uint8(D); % convert double D to uint8\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/33342-floyd-steinberg-dithering-algorithm/Floyd_Steinberg_Dithering.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802529509909, "lm_q2_score": 0.7577943767446201, "lm_q1q2_score": 0.6960191708372372}} {"text": "function val = simAssetPrice_2(TimeSeries, Period, nYears, nTrials)\n% SIMASSETPRICE_2 simulates the asset prices series in a Monte Carlo\n% simulation. Is similar to simAssetPrice_orig, but removes dependence on\n% the GBM object (at some expense to readibility).\n\n[expReturn, expCov] = calcExpMoments(TimeSeries, Period);\nnAssets = size(expCov,1);\nStartAssetPrice = TimeSeries(end, :)';\n\nT = cholcov(expCov);\nrandNums = randn(nTrials*nYears, nAssets);\nrandNums = permute(reshape(randNums * T, nTrials, nYears, nAssets), [2,3,1]);\nreturns = bsxfun(@plus, randNums, expReturn);\nStartAssetPrice = repmat(StartAssetPrice', [1,1,nTrials]);\nval = cumprod([StartAssetPrice; 1 + returns]);\n\nval(val<0) = 0;\n\nend\n\nfunction [expReturn, expCov] = calcExpMoments(TimeSeries, Period)\n% Estimates and annualizes the expected returns and covariances for the\n% given time series\nreturns = price2ret(TimeSeries);\nexpReturn = mean(returns);\nexpCov = cov(returns);\n\n% Annualize monthly, weekly and daily returns and correlations\nif Period == 'm'\n [expReturn, expCov] = arith2geom(expReturn, expCov, 12);\nelseif Period == 'w'\n % Not implemented\nelseif Period == 'd'\n % Not implemented\nelse\n % Do nothing\nend\n\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/43577-speeding-up-algorithms-when-parallel-computing-and-gpus-do-and-dont-accelerate/Variable_Annuity/simAssetPrice_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.696019165813169}} {"text": "% the following matlab functions are used to calculate the Rand, \n% adjusted Rand, Wallace and other partition comparison coefficients\n%\n% Copyright (C) 2009 UMMI@IMM\n%\n% This file is part of Comparing Partitions website . \n% Comparing Partitions website 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%\n%[a,b,c,d,bc,dn,confmat,res]=PartAgreeCoef(c1,c2)\n%Outputs:\n%ri=rand Index\n%AR = adjusted rand\n%jac=jaccard\n%w1- Wallace c1->c2\n%w2 - Wallace c2->c1\n%lar1 - Larsen c1->c2\n%lar2 - Larsen c2->c1\n%MH - Melia & Heckerman\n%VI - variation of information\n%nVI - normalized variation of information \n% Francisco Pinto fpinto@fm.ul.pt\n\nfunction res=PartAgreeCoef_ARonly(c1,c2)\n\nc1=c1-min(c1)+1;\nc2=c2-min(c2)+1;\nn=length(c1); % number cass \nng1=max(c1);\nng2=max(c2);\n%dn=n*(n-1)/2; %number of possible pairwise comparisons of cases(a+b+c+d)\n\n%y1=pdist(c1(:),'ham');\n%y2=pdist(c2(:),'ham');\n%size(y1)\n%size(y2)\n%ad=sum((y1'==y2')); % number of pairwise concordances (matches (a) and mismatches(d))(a+d)\n%bc=sum((y1'~=y2')); % number of pairwise discordances(b+c)\n%Rand Index\n%res.ri=ad/dn;\n\n%a=sum((y1'==0).*(y2'==0));\n%b=sum(y1'==0)-a;\n%c=sum(y2'==0)-a;\n\n%res.w1=a/sum(y1'==0);% check is =dn\n%res.w1a=a/(a+b);\n%res.w2a=a/(a+c);\n%res.w2=a/sum(y2'==0);\n%d=ad-a;\n\n%Jaccard Index\n%res.jac=a/(dn-d);\n\n%confmat=crosstab(c1,c2);\nconfmat=full(sparse(c1,c2,1,ng1,ng2));\n\ncoltot=sum(confmat);\nrowtot=sum(confmat')';\n%summat=repmat(coltot,ng1,1)+repmat(rowtot,1,ng2);\n%larsenmat=2*confmat./summat;\n%res.lar1=mean(max((larsenmat'))');\n%res.lar2=mean(max(larsenmat)');\n\n%todelmat=larsenmat;\n%cumval=0;\n%for i=1:min([ng1;ng2])\n% [val]=max(max(todelmat)');\n% [rr,cc]=find(todelmat==val);\n% todelmat(rr(1),:)=0;\n% todelmat(:,cc(1))=0;\n% cumval=cumval+confmat(rr(1),cc(1));\n%end\n%res.MH=cumval/n;\n\n%H1=-sum((rowtot/n).*log2((rowtot/n)));\n%H2=-sum((coltot/n)'.*log2((coltot/n)'));\n%indmat=(rowtot/n)*(coltot/n);\n%nozeromat=(confmat/n)+(confmat==0);\n%H12=-sum(sum((confmat/n).*log2(nozeromat)));\n%MI=H1+H2-H12;\n%res.VI=H1+H2-2*MI;\n%res.nVI=res.VI/log2(n);\n\nnis=sum(rowtot.^2);\t\t%sum of squares of sums of rows\nnjs=sum(coltot.^2);\t\t%sum of squares of sums of columns\n\nt1=nchoosek(n,2);\t\t%total number of pairs of entities\nt2=sum(sum(confmat.^2));\t%sum over rows & columnns of nij^2\nt3=.5*(nis+njs);\n\n%Expected index (for adjustment)\nnc=(n*(n^2+1)-(n+1)*nis-(n+1)*njs+2*(nis*njs)/n)/(2*(n-1));\n\nA=t1+t2-t3;\t\t%no. agreements\n%D= -t2+t3;\t\t%no. disagreements\n\nif t1==nc\n res=0;\t\t\t%avoid division by zero; if k=1, define Rand = 0\nelse\n res=(A-nc)/(t1-nc);\t\t%adjusted Rand - Hubert & Arabie 1985\n %res.AR2=(ad-nc)/(dn-nc); % (a+d-nc)/(a+b+c+d-nc)\nend\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/3rdparty/CSCbox/third_party/PartAgreeCoef_ARonly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567085, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6960191607402795}} {"text": "% ***************************************************************************\n% Linear Interpolation\n% ***************************************************************************\n% Author: Chaobin\n% Email: chaubyZou@163.com\n% Date: October 2020\n% ***************************************************************************\n% Language: Matlab\n% Also available in: Python\n% Required library: None\n% ***************************************************************************\n\nclassdef LinearInterpolation < handle\n properties\n name = 'linear interpolation';\n q_via = [];\n t_via = [];\n end\n\n methods\n % crate the objective\n % name: string\n % q_via: N x 3 array\n % t_via: N x 1 array\n function obj = LinearInterpolation(name, q_via, t_via)\n obj.name = name;\n obj.q_via = q_via;\n obj.t_via = t_via;\n if size(q_via(:,1)) ~= length(t_via)\n error('The q_via and t_via must have a same length');\n end\n end\n\n % linar interpolation with two data points\n % q0: the first data point\n % q1: the second data point\n % t0: the time of the first data point\n % t1: the time of the second data point\n % a0, a1: parameters\n function [a0, a1] = linear(obj, q0, q1, t0, t1)\n if abs(t0 - t1) < 1e-6\n error('t0 and t1 must be different');\n end\n a0 = q0;\n a1 = (q1 - q0)/(t1 - t0);\n end\n\n % linar interpolation for all data points\n % t: specified time\n % q: 1 x 3 array, output of the interpolation at time t\n function q = getPosition(obj, t)\n if (t < obj.t_via(1)) || (t > obj.t_via(end))\n error('The specific time error, time ranges error');\n end\n\n j = find(obj.t_via >= t, 1, 'first'); % find the index of t1\n if j == 1\n i = 1;\n j = 2;\n else\n i = j-1;\n end\n\n % position\n q0 = obj.q_via(i,1);\n t0 = obj.t_via(i);\n q1 = obj.q_via(j,1);\n t1 = obj.t_via(j);\n [a0, a1] = obj.linear(q0, q1, t0, t1);\n q(1, 1) = a0 + a1*(t - t0);\n\n % velocity\n q(1, 2) = a1;\n\n % acceleration\n q(1, 3) = 0; % for linear model, the acceleration is infinite, here we set to zero\n end\n end\nend\n", "meta": {"author": "chauby", "repo": "PolynomialInterpolation", "sha": "222dbf804c1e756f51c848631acae3fb1dc172e3", "save_path": "github-repos/MATLAB/chauby-PolynomialInterpolation", "path": "github-repos/MATLAB/chauby-PolynomialInterpolation/PolynomialInterpolation-222dbf804c1e756f51c848631acae3fb1dc172e3/matlab/LinearInterpolation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6960191574071745}} {"text": "function [SE3] = SE3MatrixFromComponents( x, y, z, r, p, yaw )\n \n% SE3MatrixFromComponents - build a 4x4 matrix representing an SE(3) transform\n%\n% [SE3] = SE3MatrixFromComponents( x, y, z, r, p, yaw )\n% \n% INPUTS:\n% x, y, z: translation\n% r, p, yaw: rotation in Euler angle representation\n%\n% OUTPUTS:\n% SE3: 4x4 matrix representing the SE(3) transform\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright (c) 2016 University of Oxford\n% Authors: \n% Geoff Pascoe (gmp@robots.ox.ac.uk)\n% Will Maddern (wm@robots.ox.ac.uk)\n%\n% This work is licensed under the Creative Commons \n% Attribution-NonCommercial-ShareAlike 4.0 International License. \n% To view a copy of this license, visit \n% http://creativecommons.org/licenses/by-nc-sa/4.0/ or send a letter to \n% Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n % Allow passing of a single 6-element vector\n if nargin == 1\n y = x(2);\n z = x(3);\n r = x(4);\n p = x(5);\n yaw = x(6);\n x = x(1);\n end\n\n % Convert euler angles to rotation matrices\n R_x = [ \n 1, 0, 0;\n 0, cos(r), -sin(r);\n 0, sin(r), cos(r) ];\n \n R_y = [ \n cos(p), 0, sin(p);\n 0, 1, 0;\n -sin(p), 0, cos(p) ];\n \n R_z = [\n cos(yaw), -sin(yaw), 0;\n sin(yaw), cos(yaw), 0;\n 0, 0, 1];\n \n R = R_z * R_y * R_x;\n \n SE3 = [R [x; y; z]; zeros(1,3), 1];\n\nend\n", "meta": {"author": "ori-mrg", "repo": "robotcar-dataset-sdk", "sha": "16ce3329223ca418fe5106277b91aea8d9b672b2", "save_path": "github-repos/MATLAB/ori-mrg-robotcar-dataset-sdk", "path": "github-repos/MATLAB/ori-mrg-robotcar-dataset-sdk/robotcar-dataset-sdk-16ce3329223ca418fe5106277b91aea8d9b672b2/matlab/SE3MatrixFromComponents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6960191556673897}} {"text": "%TREXP Matrix exponential for so(3) and se(3)\n%\n% For so(3)::\n%\n% R = TREXP(OMEGA) is the matrix exponential (3x3) of the so(3) element OMEGA that\n% yields a rotation matrix (3x3). \n%\n% R = TREXP(OMEGA, THETA) as above, but so(3) motion of THETA*OMEGA.\n%\n% R = TREXP(S, THETA) as above, but rotation of THETA about the unit vector S.\n%\n% R = TREXP(W) as above, but the so(3) value is expressed as a vector W\n% (1x3) where W = S * THETA. Rotation by ||W|| about the vector W.\n%\n% For se(3)::\n%\n% T = TREXP(SIGMA) is the matrix exponential (4x4) of the se(3) element SIGMA that\n% yields a homogeneous transformation matrix (4x4). \n%\n% T = TREXP(SIGMA, THETA) as above, but se(3) motion of SIGMA*THETA, the\n% rotation part of SIGMA (4x4) must be unit norm.\n%\n% T = TREXP(TW) as above, but the se(3) value is expressed as a twist vector TW\n% (1x6). \n%\n% T = TREXP(TW, THETA) as above, but se(3) motion of TW*THETA, the\n% rotation part of TW (1x6) must be unit norm.\n%\n% Notes::\n% - Efficient closed-form solution of the matrix exponential for arguments that are\n% so(3) or se(3).\n% - If THETA is given then the first argument must be a unit vector or a\n% skew-symmetric matrix from a unit vector.\n% - Angle vector argument order is different to ANGVEC2R.\n%\n% References::\n% - Robotics, Vision & Control: Second Edition, P. Corke, Springer 2016; p42-43.\n% - Mechanics, planning and control, Park & Lynch, Cambridge, 2017.\n%\n% See also ANGVEC2R, TRLOG, TREXP2, SKEW, SKEWA, Twist.\n\n%## 3d homogeneous differential\n\n\n% Copyright (C) 1993-2019 Peter I. Corke\n%\n% This file is part of The Spatial Math Toolbox for MATLAB (SMTB).\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, including without limitation the rights\n% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n% of the Software, and to permit persons to whom the Software is furnished to do\n% so, subject to the following conditions:\n%\n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n% FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n% COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n% IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n%\n% https://github.com/petercorke/spatial-math\nfunction T = trexp(S, theta)\n\n if ishomog(S) || isvec(S,6)\n % input is se(3)\n \n if nargin == 1\n % twist vector 1x6 or augmented skew matrix 4x4\n if isvec(S,6)\n % it's a twist vector\n S = skewa(S);\n end\n T = expm(S);\n else\n % se(3) plus twist\n if all(size(S) == 4)\n % it's se(3) matrix\n [skw,v] = tr2rt(S);\n else\n % it's a twist vector\n v = S(1:3); v= v(:);\n skw = skew(S(4:6));\n end\n \n % use an efficient solution\n R = trexp(skw, theta);\n t = (eye(3,3)*theta + (1-cos(theta))*skw + (theta-sin(theta))*skw^2)*v;\n \n T = rt2tr(R,t);\n end \n elseif isrot(S) || isvec(S,3)\n % input is so(3)\n \n if isrot(S)\n % input is 3x3 skew symmetric\n w = vex(S);\n elseif isvec(S)\n % input is a 3-vector\n w = S; \n end\n \n % for a zero so(3) return unit matrix, theta not relevant\n if norm(w) < 10*eps\n T = eye(3,3);\n return;\n end\n \n if nargin == 1\n % theta is not given, extract it\n theta = norm(w);\n w = unit(w);\n else\n % theta is given\n assert(isunit(w), 'SMTB:trexp:badarg', 'w must be a unit twist');\n end\n \n S = skew(w);\n \n T = eye(3,3) + sin(theta)*S + (1-cos(theta))*S^2;\n \n else\n error('SMTB:trexp:badarg', 'first argument must be so(3), 3-vector, se(3) or 6-vector');\n end\nend\n", "meta": {"author": "petercorke", "repo": "spatialmath-matlab", "sha": "6eeff4a79f14286705560b84f1fe72e0b7e0e7f7", "save_path": "github-repos/MATLAB/petercorke-spatialmath-matlab", "path": "github-repos/MATLAB/petercorke-spatialmath-matlab/spatialmath-matlab-6eeff4a79f14286705560b84f1fe72e0b7e0e7f7/trexp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6959726165555005}} {"text": "function [ type, typeCost ] = assignVanishingType( lines, vp, tol, area )\n%ASSIGNVANISHINGTYPE Summary of this function goes here\n% Detailed explanation goes here\nif nargin<=3\n area = 10;\nend\n\nnumLine = size(lines,1);\nnumVP = size(vp, 1);\ntypeCost = zeros(numLine, numVP);\n% perpendicular \nfor vid = 1:numVP\n cosint = dot( lines(:,1:3), repmat( vp(vid,:), [numLine 1]), 2);\n typeCost(:,vid) = asin(abs(cosint));\nend\n% infinity\nfor vid = 1:numVP\n valid = true(numLine,1);\n for i = 1:numLine\n us = lines(i,5);\n ue = lines(i,6);\n u = [us;ue]*2*pi-pi;\n v = computeUVN(lines(i,1:3), u, lines(i,4));\n xyz = uv2xyzN([u v], lines(i,4));\n x = linspace(xyz(1,1),xyz(2,1),100);\n y = linspace(xyz(1,2),xyz(2,2),100);\n z = linspace(xyz(1,3),xyz(2,3),100);\n xyz = [x' y' z'];\n xyz = xyz ./ repmat(sqrt(sum(xyz.^2,2)),[1 3]);\n ang = acos( abs(dot(xyz, repmat(vp(vid,:), [100 1]), 2)));\n valid(i) = ~any(angtol) = numVP+1;\n\nend\n\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/VpEstimation/assignVanishingType.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6959726047691238}} {"text": "t = 0:0.1:10;\nx = exp(-0.2*t) .* cos(2*t);\ny = exp(-0.2*t) .* sin(2*t);\nplot3(x,y,t,'LineWidth',2);\ntitle('\\bfThree-Dimensional Line Plot');\nxlabel('\\bfx');\nylabel('\\bfy');\nzlabel('\\bftime');\ngrid on; \n", "meta": {"author": "101Hub", "repo": "Matlab101", "sha": "07273f68f1147a110443aeb121fa10962234f298", "save_path": "github-repos/MATLAB/101Hub-Matlab101", "path": "github-repos/MATLAB/101Hub-Matlab101/Matlab101-07273f68f1147a110443aeb121fa10962234f298/assets/\u300aMatlab\u7f16\u7a0b\u300b\u6e90\u7801/chap6/test_plot3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6959726047691237}} {"text": "function [samples,hists] = SampleDGAnyMarginal(gammas,Lambda,supports,Nsamples)\n\n% [samples,hists]=SampleDGAnyMarginal(gammas,Lambda,supports,Nsamples)\n% Generate samples for a Multivariate Discretized Gaussian with parameters\n% \"gammas\" and \"Lambda\" and \"supports\". The number of samples generated is \"Nsamples\"\n%\n% input and output arguments are as described in \"DGAnyMarginal\"\n%\n% Usage: \n%\n% Code from the paper: 'Generating spike-trains with specified\n% correlations', Macke et al., submitted to Neural Computation\n%\n% www.kyb.mpg.de/bethgegroup/code/efficientsampling\n\nd=size(Lambda,1);\n\nif isempty(supports)\n for k=1:d\n supports{k}=[0:numel(gammas{k})-1];\n end\nend\n \ncc=chol(Lambda);\n\nB=randn(Nsamples,d)*cc;\n\nfor k=1:d\n [hists{k},dd]=histc(B(:,k),[-inf;gammas{k};inf]);\n hists{k}=hists{k}/Nsamples;\n samples(:,k)=supports{k}(dd);\n hists{k}=hists{k}(1:max(1,end-2));\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/20591-sampling-from-multivariate-correlated-binary-and-poisson-random-variables/lib/SampleDGAnyMarginal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6959726015301915}} {"text": "function spherical_harmonic_test02 ( )\n\n%*****************************************************************************80\n%\n%% SPHERICAL_HARMONIC_TEST02 tests SPHERICAL_HARMONIC and SPHERICAL_HARMONIC_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 October 2008\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPHERICAL_HARMONIC_TEST02:\\n' );\n fprintf ( 1, ' SPHERICAL_HARMONIC evaluates the\\n' );\n fprintf ( 1, ' spherical harmonic function.\\n' );\n fprintf ( 1, ' SPHERICAL_HARMONIC_VALUES returns some exact values.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' L M THETA PHI YR YI\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, l, m, theta, phi, yr, yi ] = spherical_harmonic_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n [ c, s ] = spherical_harmonic ( l, m, theta, phi );\n\n fprintf ( 1, ' %6d %6d %6f %6f %12f %12f\\n', ...\n l, m, theta, phi, yr, yi );\n fprintf ( 1, ' %12f %12f\\n', ...\n c(l+1), s(l+1) );\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/spherical_harmonic/spherical_harmonic_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.6959472104316271}} {"text": "function bessel_k0_values_test ( )\n\n%*****************************************************************************80\n%\n%% BESSEL_K0_VALUES_TEST demonstrates the use of BESSEL_K0_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 February 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BESSEL_K0_VALUES_TEST:\\n' );\n fprintf ( 1, ' BESSEL_K0_VALUES stores values of \\n' );\n fprintf ( 1, ' the Bessel K0 function.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X K0(X)\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, x, fx ] = bessel_k0_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %12f %24.16f\\n', x, fx );\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/test_values/bessel_k0_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.695947210431627}} {"text": "close all; clear all; clc\n\naddpath('apm')\n\ns = 'http://byu.apmonitor.com';\na = 'parameter_regression';\n\n% clear application and load new model and data files\napm(s,a,'clear all');\napm_load(s,a,'model.apm');\ncsv_load(s,a,'data.csv');\n\n% estimation mode\napm_option(s,a,'apm.imode',5);\napm_option(s,a,'apm.solver',3);\n\n% classify variables\napm_info(s,a,'FV','K1');\napm_info(s,a,'FV','K2');\napm_info(s,a,'FV','K3');\napm_info(s,a,'FV','tau12');\napm_info(s,a,'FV','tau3');\napm_info(s,a,'MV','Q1');\napm_info(s,a,'MV','Q2');\napm_info(s,a,'CV','TC1');\napm_info(s,a,'CV','TC2');\n\n% set status on\napm_option(s,a,'K1.status',1);\napm_option(s,a,'K2.status',1);\napm_option(s,a,'K3.status',1);\napm_option(s,a,'tau12.status',1);\napm_option(s,a,'tau3.status',0);\n\n% set feedback status on\napm_option(s,a,'Q1.fstatus',1);\napm_option(s,a,'Q2.fstatus',1);\napm_option(s,a,'TC1.fstatus',1);\napm_option(s,a,'TC2.fstatus',1);\n\n% optimize parameters\noutput = apm(s,a,'solve');\ndisp(output)\n\n% retrieve solution\ny = apm_sol(s,a);\nz = y.x;\n\n% optimized parameter values\nK1 = apm_tag(s,a,'K1.newval');\nK2 = apm_tag(s,a,'K2.newval');\nK3 = apm_tag(s,a,'K3.newval');\ntau12 = apm_tag(s,a,'tau12.newval');\ntau3 = apm_tag(s,a,'tau3.newval');\n\n% display values\ndisp(['K1: ' num2str(K1)])\ndisp(['K2: ' num2str(K2)])\ndisp(['K3: ' num2str(K3)])\ndisp(['tau12: ' num2str(tau12)])\ndisp(['tau3: ' num2str(tau3)])\n\n% read data.csv file for plotting\ndata = csvread('data.csv',1);\nt = data(:,1);\nT1meas = data(:,4);\nT2meas = data(:,5);\n\n% Plot results\nfigure(1)\nsubplot(3,1,1)\nplot(t/60,T1meas,'b-','LineWidth',2)\nhold on\nplot(z.time/60,z.tc1,'g:','LineWidth',2)\nylabel('Temperature (degC)')\nlegend('T_1 measured','T_1 optimized')\n\nsubplot(3,1,2)\nplot(t/60,T2meas,'k-','LineWidth',2)\nhold on\nplot(z.time/60,z.tc2,'r:','LineWidth',2)\nylabel('Temperature (degC)')\nlegend('T_2 measured','T_2 optimized')\n\nsubplot(3,1,3)\nplot(z.time/60,z.q1,'g-','LineWidth',2)\nhold on\nplot(z.time/60,z.q2,'k--','LineWidth',2)\nylabel('Heater Output')\nlegend('Q_1','Q_2')\n\nxlabel('Time (min)')\n", "meta": {"author": "APMonitor", "repo": "arduino", "sha": "f36e65a70dd7122d1829883899e40e56bf6c4279", "save_path": "github-repos/MATLAB/APMonitor-arduino", "path": "github-repos/MATLAB/APMonitor-arduino/arduino-f36e65a70dd7122d1829883899e40e56bf6c4279/2_Regression/2nd_order_MIMO/MATLAB/tclab_2nd_order_linear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.6959320664688277}} {"text": "% LDA - MATLAB subroutine to perform linear discriminant analysis\n% by Will Dwinnell and Deniz Sevis\n%\n% Use:\n% W = LDA(Input,Target,Priors)\n%\n% W = discovered linear coefficients (first column is the constants)\n% Input = predictor data (variables in columns, observations in rows)\n% Target = target variable (class labels)\n% Priors = vector of prior probabilities (optional)\n%\n% Note: discriminant coefficients are stored in W in the order of unique(Target)\n%\n% Example:\n%\n% % Generate example data: 2 groups, of 10 and 15, respectively\n% X = [randn(10,2); randn(15,2) + 1.5]; Y = [zeros(10,1); ones(15,1)];\n%\n% % Calculate linear discriminant coefficients\n% W = LDA(X,Y);\n%\n% % Calulcate linear scores for training data\n% L = [ones(25,1) X] * W';\n%\n% % Calculate class probabilities\n% P = exp(L) ./ repmat(sum(exp(L),2),[1 2]);\n%\n%\n% Last modified: Dec-11-2010\n\n\nfunction W = LDA(Input,Target,Priors)\n\n% Determine size of input data\n[n m] = size(Input);\n\n% Discover and count unique class labels\nClassLabel = unique(Target);\nk = length(ClassLabel);\n\n% Initialize\nnGroup = NaN(k,1); % Group counts\nGroupMean = NaN(k,m); % Group sample means\nPooledCov = zeros(m,m); % Pooled covariance\nW = NaN(k,m+1); % model coefficients\n\nif (nargin >= 3) PriorProb = Priors; end\n\n% Loop over classes to perform intermediate calculations\nfor i = 1:k,\n % Establish location and size of each class\n Group = (Target == ClassLabel(i));\n nGroup(i) = sum(double(Group));\n \n % Calculate group mean vectors\n GroupMean(i,:) = mean(Input(Group,:));\n \n % Accumulate pooled covariance information\n PooledCov = PooledCov + ((nGroup(i) - 1) / (n - k) ).* cov(Input(Group,:));\nend\n\n% Assign prior probabilities\nif (nargin >= 3)\n % Use the user-supplied priors\n PriorProb = Priors;\nelse\n % Use the sample probabilities\n PriorProb = nGroup / n;\nend\n\n% Loop over classes to calculate linear discriminant coefficients\nfor i = 1:k,\n % Intermediate calculation for efficiency\n % This replaces: GroupMean(g,:) * inv(PooledCov)\n Temp = GroupMean(i,:) / PooledCov;\n \n % Constant\n W(i,1) = -0.5 * Temp * GroupMean(i,:)' + log(PriorProb(i));\n \n % Linear\n W(i,2:end) = Temp;\nend\n\n% Housekeeping\nclear Temp\n\nend\n\n\n% EOF\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/29673-lda-linear-discriminant-analysis/LDA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.793105953629227, "lm_q1q2_score": 0.6959320643232959}} {"text": "function Xptm_run = fast_polytrendmtx(run,ntrs,nruns,order)\n% Xptm = fast_polytrendmtx(run,ntrs,nruns,order)\n%\n\nif(nargin ~= 4)\n msg = 'USAGE: Xptm = fast_polytrendmtx(run,ntrs,nruns,order)';\n qoe(msg);error(msg);\nend\n\nXptm = ones(ntrs,1);\nt = [0:ntrs-1]'; %'\nfor n = 1:order\n r0 = t.^n;\n M = eye(ntrs) - Xptm*inv(Xptm'*Xptm)*Xptm';\n r = M*r0;\n r = r/std(r);\n Xptm = [Xptm r];\nend\n\nXptm_run = zeros(ntrs,nruns*(order+1));\nn1 = (run-1)*(order+1) + 1;\nn2 = n1 + order;\nXptm_run(:,n1:n2) = Xptm;\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/EventRelated/fast_polytrendmtx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736692, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6959320635320004}} {"text": "function gf=filterbankresponse(g,a,L,varargin)\n%FILTERBANKRESPONSE Response of filterbank as function of frequency\n% Usage: gf=filterbankresponse(g,a,L);\n% \n% `gf=filterbankresponse(g,a,L)` computes the total response in frequency\n% of a filterbank specified by *g* and *a* for a signal length of\n% *L*. This corresponds to summing up all channels. The output is a\n% usefull tool to investigate the behaviour of the windows, as peaks\n% indicate that a frequency is overrepresented in the filterbank, while\n% a dip indicates that it is not well represented.\n%\n% CAUTION: This function computes a sum of squares of modulus of the \n% frequency responses, which is also the diagonal of the Fourier \n% transform of the frame operator.\n% Use |filterbankfreqz| for evaluation or plotting of frequency responses\n% of filters.\n%\n% `filterbankresponse(g,a,L,'real')` does the same for a filterbank\n% intended for positive-only filterbank.\n%\n% `filterbankresponse(g,a,L,fs)` specifies the sampling rate *fs*. This\n% is only used for plotting purposes.\n%\n% `gf=filterbankresponse(g,a,L,'individual')` returns responses \n% in frequency of individual filters as columns of a matrix. The total\n% response can be obtained by `gf = sum(gf,2)`. \n%\n% `filterbankresponse` takes the following optional parameters:\n%\n% 'fs',fs \n% Sampling rate, used only for plotting.\n%\n% 'complex' \n% Assume that the filters cover the entire frequency\n% range. This is the default.\n%\n% 'real' \n% Assume that the filters only cover the positive\n% frequencies (and is intended to work with real-valued\n% signals only).\n%\n% 'noplot' \n% Don't plot the response, just return it.\n%\n% 'plot' \n% Plot the response using |plotfftreal| or |plotfft|.\n%\n% See also: filterbank, filterbankbounds\n \ndefinput.flags.ctype={'complex','real'};\ndefinput.flags.plottype={'noplot','plot'};\ndefinput.flags.type={'total','individual'};\ndefinput.keyvals.fs=[];\n[flags,kv,fs]=ltfatarghelper({'fs'},definput,varargin);\n\n[g,asan]=filterbankwin(g,a,L,'normal');\nM=numel(g);\n\ngf = zeros(L,M);\nfor m=1:M\n gf(:,m) = comp_filterbankresponse(g(m),asan(m,:),L,flags.do_real);\nend\n\nif flags.do_total\n gf = sum(gf,2);\nend\n\nif flags.do_plot\n if flags.do_real\n plotfftreal(gf(1:floor(L/2)+1,:),fs,'lin');\n else\n plotfft(gf,fs,'lin');\n end;\nend;\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/filterbank/filterbankresponse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6959320578867005}} {"text": "function [V, dV] = variance(X, dim)\n% Computes the variance of X in dimension dim, and its gradient\n\nmu = mean(X, dim);\nV = mean(bsxfun(@minus, X, mu).^2, dim);\n\nn = size(X, dim);\ndV = bsxfun(@plus, (2/n - 4/n) * mu, 2/n*X);\n", "meta": {"author": "akar43", "repo": "CategoryShapes", "sha": "55c9dab2293bcaceaaa3bf5fea782fdbf930fadb", "save_path": "github-repos/MATLAB/akar43-CategoryShapes", "path": "github-repos/MATLAB/akar43-CategoryShapes/CategoryShapes-55c9dab2293bcaceaaa3bf5fea782fdbf930fadb/external/SIRFS/variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9559813451206062, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6959309545018002}} {"text": "% ASTROTIK by Francesco Santilli\n% R2BP (Restricted Two Bodies Problem)\n% f2H converts true anomaly in hyperbolic anomaly for an hyperbolic orbit.\n%\n% Usage: H = f2H(f,e)\n%\n% where: f(k) = true anomaly [rad]\n% e = eccentricity [-] (e>1)\n% H(k) = hyperbolic anomaly [rad]\n\nfunction H = f2H(f,e)\n\n if ~(nargin == 2)\n error('Wrong number of input arguments.')\n end\n \n check(f,1)\n check(e,0)\n \n if e <= 1\n error('e must be strictly major than 1.')\n end\n \n ee = sqrt((e-1)/(e+1));\n H = 2*atanh( ee*tan(f/2) );\n \n kk = f/(2*pi);\n k = round(kk) - ((kk-fix(kk)) == 0.5);\n H = H + k*(2*pi);\n \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/27308-astrotik-1-0/orbits/f2H.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6957845695955794}} {"text": "%% Code Division Multiple Access Transmitter\n% CDMAt - Function\n% 1. (s) Input the data \n% Input data must be (+/- 1's) (this is a PSK modulation (BPSK))\n% 2. (hl) Hadamard matrix length \n% 3. (cn) code number to be used for this user (row - number of H - matrix)\n% 4. Spread the data by multiplying s by cn.\n% 6. Outpot of the function is spread symbol of user cn.\n% Montadar Abas Taher\n% 11/03/2011\nfunction [outcdmat]=cdmat(s,hl,cn)\nif cn>hl\n errordlg('The input code number must be equal or less than the Hadamard length','File Error');\nend\n%% Generate Hadamard Matrix of length (hl)\nh=hadamard(hl);\n%% Spread the input sequence\noutcdmat=kron(s,h(cn,:));", "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/35476-this-is-a-general-cdma-simulation/cdmat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299653388754, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6957845675541756}} {"text": "function a = ref_random ( m, n, prob, key )\n\n%*****************************************************************************80\n%\n%% REF_RANDOM returns a random row echelon matrix.\n%\n% Definition:\n%\n% 1) the first nonzero entry in any row is 1.\n%\n% 2) the first nonzero entry in row I occurs in a later column\n% than the first nonzero entry of every previous row.\n%\n% 3) rows that are entirely zero occur after all rows with\n% nonzero entries.\n%\n% Example:\n%\n% M = 6, N = 5, PROB = 0.8\n%\n% 1.0 0.3 0.2 0.0 0.5\n% 0.0 0.0 1.0 0.7 0.9\n% 0.0 0.0 0.0 1.0 0.3\n% 0.0 0.0 0.0 0.0 1.0\n% 0.0 0.0 0.0 0.0 0.0\n% 0.0 0.0 0.0 0.0 0.0\n%\n% Properties:\n%\n% A is generally not symmetric: A' /= A.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the order of the matrix.\n%\n% Input, real PROB, the probability that the 1 in the next \n% row will be placed as early as possibly.\n% Setting PROB = 1 forces the 1 to occur immediately, setting\n% PROB = 0 forces the entire matrix to be zero. A more reasonable\n% value might be PROB = 0.8 or 0.9.\n%\n% Input, integer KEY, a positive value that selects the data..\n%\n% Output, real A(M,N), the matrix.\n%\n a = zeros ( m, n );\n\n jprev = 0;\n\n seed = key;\n\n for i = 1 : m\n\n jnew = 0;\n\n for j = 1 : n\n\n if ( j <= jprev )\n a(i,j) = 0.0;\n elseif ( jnew == 0 )\n [ temp, seed ] = r8_uniform_01 ( seed );\n if ( temp <= prob )\n jnew = j;\n a(i,j) = 1.0;\n else\n a(i,j) = 0.0;\n end\n else\n [ a(i,j), seed ] = r8_uniform_01 ( seed );\n end\n\n end\n\n if ( jnew == 0 )\n jnew = n + 1;\n end\n\n jprev = jnew;\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/test_mat/ref_random.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.6957593744241153}} {"text": "% vgg_mrdivs Solves equation system Y*diag(s) = A*X with unkowns A, s.\n%\n% A = vgg_mrdivs(X,Y) solves (overdetermined) equation system Y*diag(s) = A*X\n% by linear method (DLT algorithm).\n% Parameters:\n% X ... double (N,K)\n% Y ... double (M,K)\n% A ... double (M,N)\n% s ... double (1,K)\n%\n% Preconditioning of the points not included in the function. Use vgg_conditioner_*.\n%\n% Typical usage:\n% 1. Estimating an image homography from K pairs of corresponding points.\n% If 3-by-K matrices x and y are the points in homogeneous coordinates, the 3-by-3 homography\n% matrix is obtained as H = vgg_mrdivs(x,y).\n%\n% 2. Estimating 3-by-4 camera projection matrix P from corresponding pairs of image and scene points.\n% For image points x (3xK matrix) and scene points X (4xK matrix) do P = vgg_mrdivs(X,x).\n\n% (c) werner@robots.ox.ac.uk\n\n% Algorithm: \n% \n% For n-th point pair X(:,n) and Y(:,n) we have\n% s*X(:,n) = A*Y(:,n)\n% We eliminate s what results in MY*(MY-1)/2 linear homogenous equations \n% for elements of A. We solve this system by svd or eig.\n\nfunction A = vgg_mrdivs(X,Y)\n\n[MX,N] = size(X);\n[MY,NY] = size(Y);\nif N ~= NY, error('Matrices A, B must have equal number of columns.'); end\n\n % construct the measurement matrix\nW = zeros(MX*MY,MY*(MY-1)/2*N);\nk = 1;\nfor i = 1:MY\n for j = 1:i-1\n W([[1:MX]+MX*(j-1) [1:MX]+MX*(i-1)],[1:N]+N*(k-1)) = [(ones(MX,1)*Y(i,:)).*X; -(ones(MX,1)*Y(j,:)).*X];\n k = k+1;\n end\nend\n\n% solve the system || A'(:)' * W || ---> min\n[dummy,s,A] = svd(W',0);\nA = reshape(A(:,end),MX,MY)';\n\nreturn", "meta": {"author": "jmmanley", "repo": "VGG-Multiple-View-Geometry", "sha": "f114712de03082bb97229eaf2a65981908b64127", "save_path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry", "path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry/VGG-Multiple-View-Geometry-f114712de03082bb97229eaf2a65981908b64127/vgg_numerics/vgg_mrdivs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6957488567437885}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% In this script, we perform phase transition analysis\n% of Orthogonal least squares.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nclose all;\nclear all;\nclc;\nrng('default');\n% Create the directory for storing results\n[status_code,message,message_id] = mkdir('bin');\ntarget_file_path = 'bin/ols_phase_transition_gaussian_dict_gaussian_data.mat';\nN = 1024;\npta = spx.pursuit.PhaseTransitionAnalysis(N);\n% pta.NumTrials = 100;\ndict_model = @(M, N) spx.dict.simple.gaussian_dict(M, N);\ndata_model = @(N, K) spx.data.synthetic.SparseSignalGenerator(N, K).gaussian;\nrecovery_solver = @(Phi, K, y) spx.pursuit.single.OrthogonalLeastSquares(Phi, K).solve(y).z;\npta.run(dict_model, data_model, recovery_solver);\npta.save_results(target_file_path);\n\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/pursuit/single_recovery/orthogonal_least_squares/ex_phase_transition_gaussian_dict_gaussian_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6957488519556831}} {"text": "function stats = glmfit_multilevel(Y, X1, X2, varargin)\n% :Usage:\n% ::\n%\n% stats = glmfit_multilevel(Y, X1, X2, varargin)\n%\n% Mixed-effects models differ in their assumptions and implementation\n% details. glmfit_multilevel is a fast and simple option for running a \n% two-level mixed effects model with participant as a random effect. \n% It implements a random-intercept, random-slope model across 2nd-level units \n% (e.g., participants). it fits regressions for individual 2nd-level\n% units (e.g., participants), and then (optionally) uses a precision-weighted least\n% squares approach to model group effects. It thus treats participants as a\n% random effect. This is appropriate when 2nd-level units are participants\n% and 1st-level units are observations (e.g., trials) within participants. \n% glmfit_multilevel was designed with this use case in mind.\n% \n% Options:\n% glmfit_multilevel includes some options that are not included in many\n% mixed effects models, including:\n% - bootstrapping or sign permutation for inference\n% - robust regression (*needs code update*)\n% - AR(p) autoregressive model (*needs code update*)\n%\n% Requirements: glmfit_multilevel requires enough 1st-level units to fit a \n% separate model for each 2nd-level unit (participant). If this is not the \n% case, other models (igls.m, LMER, etc.) are preferred.\n%\n% Degrees of freedom: glmfit_multilevel is conservative in the sense that the degrees of \n% freedom in the group statistical test is always based on the number of \n% subjects - 2nd-level parameters. \n% The df is never higher than the sample size, which you would have with \n% mixed effects models that estimate the df from the data. This causes\n% problems in many other packages, particularly when there are many 1st-level\n% observations and they are uncorrelated, resulting in large and undesirable \n% estimated df. \n%\n% Correlated effects: The correlations across 1st-level observations are not measured, and \n% 1st-level obs are assumed to be IID. This is valid when generalizing across \n% 2nd-level units, but may not be fully efficient (powerful) if 1st-level \n% units are correlated.\n%\n% :Inputs:\n%\n% **Y:**\n% Is data in either:\n% -cell array, one cell per subject.\n% Column vector of subject outcome data in each cell.\n% -Matrix\n% One column per subject, with vector of subject outcome\n% data in that column\n%\n% **X1 and X2:**\n% are first and 2nd level design matrices\n% - X1 in cell array, one cell per subject\n% design matrix for each subject in each cell. \n% *columns must code for the same variable for all subjects*\n%\n% - X2 in rect. matrix\n% - can be empty (intercept only)\n%\n% E.g., with one 2nd-level predictor:\n% stats = glmfit_multilevel(Y, X1, X2, ...\n% 'names', {'Int' 'Temp'}, 'beta_names', {'2nd-level Intercept (overall group effect)' '2nd-lev predictor: Group membership'});\n%\n% :Output:\n%\n% **stats:**\n% is structure with results.\n% Intercept is always added as first column!\n% (do not add intercept to input predictors)\n%\n% See glmfit_general.m for varargin variable input options.\n%\n% :Examples:\n% ::\n%\n% len = 200; sub = 20;\n% x = zeros(len,sub);\n% x(11:20,:) = 2; % create signal\n% x(111:120,:) = 2;\n% c = normrnd(0.5,0.1,sub,1); % slope between-subjects variations\n% d = normrnd(3,0.2,sub,1); % intercept between-subjects variations\n% % Create y: Add between-subjects error (random effects) and measurement noise\n% % (within-subjects error)\n% for i=1:sub, y(:,i) = d(i) + c(i).*x(:,i) + normrnd(0,0.5,len,1);\n% end;\n%\n% for i = 1:size(y, 2), YY{i} = y(:, i); end\n% for i = 1:size(y, 2), XX{i} = x(:, i); end\n%\n% % one-sample t-test, weighted by inv of btwn + within vars\n% stats = glmfit_multilevel(YY, XX, [], 'verbose', 'weighted');\n%\n% statsg = glmfit_multilevel(y, x, covti, 'names', {'L1 Intercept' 'L1 Slope'},...\n% 'beta_names', {'Group Average', 'L2_Covt'});\n%\n% :Input Options:\n%\n% General Defaults\n% - case 'names', Names of first-level predictors, starting\n% with 'Intercept', in cell array\n%\n% - case 'analysisname', analysisname = varargin{i+1}; varargin{i+1} = [];\n% - case 'beta_names', beta_names = Names of 2nd-level predictors, starting\n% with 'Intercept', in cell array\n%\n% Estimation Defaults\n% - case 'robust', robust_option = 'yes';\n% - case {'weight', 'weighted', 'var', 's2'}, weight_option = 'unweighted';\n% - case {'nocenter'}, do not force centering of 2nd-level predictors\n%\n% Inference defaults\n% - case {'boot1', 'boot', 'bootstrap'}, inference_option = 'bootstrap';\n% - case {'sign perm', 'signperm', 'sign'}, inference_option = 'signperm';\n% - case {'t-test', 'ttest'}, inference_option = 't-test';\n%\n% Display control defaults\n% - case 'plots', doplots = 1; plotstr = 'plots';\n% - case 'noplots', doplots = 0; plotstr = 'noplots';\n%\n% - case {'dosave', 'save', 'saveplots'}, dosave = 1; savestr = 'save';\n% - case 'verbose', verbose = 1; verbstr = 'verbose';\n% - case 'noverbose', verbose = 0; verbstr = 'noverbose';\n% \n% - case {'savefile', 'savefilename'}, savefilename = varargin{i + 1}; varargin{i+1} = [];\n%\n% Bootstrap defaults\n% - case 'nresample', nresample = varargin{i+1};\n% - case {'pvals', 'whpvals_for_boot'}, whpvals_for_boot = varargin{i+1};\n%\n% Sign perm defaults\n% - case {'permsign'}, permsign = varargin{i+1};\n%\n\n\n\n% Programmer's notes:\n% 9/2/09: Tor and Lauren: Edited to drop NaNs within-subject, and drop\n% subject only if there are too few observations to estimate.\n% ..\n\n % Convert from matrix form to cells\n % Matrix: Y is a col vector, X is one predictor column per subject\n % -------------------------------------------------------------------\n\n if ~iscell(Y)\n N = size(Y, 2);\n for i = 1:N\n YY{i} = Y(:, i); \n end\n Y = YY;\n clear YY;\n end\n\n if ~iscell(X1)\n N2 = size(X1, 2);\n if N ~= N2, error('Sizes of X and Y do not match'); end\n for i = 1:N\n XX{i} = X1(:, i); \n end\n X1 = XX;\n clear XX\n end\n \n N = length(Y);\n if N ~= length(X1)\n error('Enter one cell per subject for each of X and Y');\n end\n\n % first level: SETUP\n % -------------------------------------------------------------------\n\n % Check variances and exclude subjects with no variance in any Y or X\n [Y, X1, X2] = check_variances_and_exclude(Y, X1, X2);\n N = length(Y);\n \n % set up first-level X matrix (sample)\n if any(strcmp(varargin, 'noint')) % no-intercept version\n X1tmp = X1{1};\n else\n X1tmp = setup_X_matrix(X1{1}); % intercept first\n end\n\n k = size(X1tmp, 2); % num predictors; assumed to be the same!!\n\n\n % Second level: SETUP\n % Need to remove 2nd-level units with NaN data at first level\n % -------------------------------------------------------------------\n wh_omit = false(1, N);\n for i = 1:N\n %if any(isnan(Y{i})) || any(isnan(X1{i}(:))), wh_omit(i) = 1; end\n \n can_be_nans = length(Y{i}) - k - 1; % up to this many can be NaN, still leaving 1 degree of freedom\n if can_be_nans < 0, warning('Warning: you might be overparameterized! Seems like you have more predictors than observations'); end\n if sum(isnan(Y{i}) | any(isnan(X1{i}), 2)) > can_be_nans\n wh_omit(i) = 1; \n end\n end\n\n if any(wh_omit)\n if isempty(X2), X2 = ones(N, 1); end\n \n Y(wh_omit) = [];\n X1(wh_omit) = [];\n X2(wh_omit, :) = [];\n N = length(Y);\n end\n\n\n beta = zeros(k, N);\n sterr = zeros(k, N);\n t = zeros(k, N);\n p = zeros(k, N);\n dfe = zeros(1, N);\n%phi = zeros(arorder, N);\n\n % first level: ESTIMATE\n % -------------------------------------------------------------------\n for i = 1:N\n [beta(:, i), sterr(:, i), t(:, i), p(:, i), dfe(:, i), phi(:,i), V{i}] = first_level_model(Y{i}, X1{i}, varargin{:});\n % V{i} is var/cov matrix (xtxi)*sigmasq\n end\n\n varnames = {'beta' 't' 'p' 'dfe' 'phi'};\n first_level = create_struct(varnames);\n first_level.ste = sterr;\n\n % second level: Finish SETUP and ESTIMATE\n % -------------------------------------------------------------------\n % set up second-level X matrix: intercept first\n X2 = setup_X_matrix(X2, beta(1,:)');\n\n% set up second-level options\n% names of outcomes become beta_names here b/c second level test on 1st\n% level betas\n [beta_names1, analysisname, beta_names2, robust_option, weight_option, inference_option, ...\n verbose, dosave, doplots, ...\n verbstr, savestr, plotstr, ...\n targetu, nresample, whpvals_for_boot, ...\n permsign] = ...\n setup_inputs(beta', X2, varargin{:});\n\n switch weight_option\n case 'weighted'\n % Note: R & B-style : replaced sterr' with V\n\n stats = glmfit_general( ...\n\t beta', X2, ...\n\t 'analysisname', analysisname, 'names', beta_names1, 'beta_names', beta_names2, ...\n\t verbstr, savestr, plotstr, ...\n\t weight_option, V, inference_option, 'dfwithin', dfe', ...\n\t 'targetu', targetu, 'nresample', nresample, ...\n\t 'whpvals_for_boot', whpvals_for_boot, 'permsign', permsign);\n\n case 'unweighted'\n\n stats = glmfit_general( ...\n\t beta', X2, ...\n\t 'analysisname', analysisname, 'names', beta_names1, 'beta_names', beta_names2, ...\n\t verbstr, savestr, plotstr, ...\n\t weight_option, inference_option, ...\n\t 'targetu', targetu, 'nresample', nresample, ...\n\t 'whpvals_for_boot', whpvals_for_boot, 'permsign', permsign);\n\n otherwise\n error('Problem with weight_option. Please select either weighted or unweighted.')\n end\n\n stats.first_level = first_level;\n\n if doplots\n scn_stats_helper_functions('xyplot', X1, Y, weight_option, 'names', beta_names1, 'nostats');\n xlabel('X'); ylabel('Y');\n end\n\n% _________________________________________________________________________\n%\n%\n%\n% * Inline functions\n%\n%\n%\n%__________________________________________________________________________\n\n function newstruct = create_struct(varnames)\n newstruct = struct();\n for i = 1:length(varnames)\n eval(['newstruct.' varnames{i} ' = ' varnames{i} ';']);\n end\n end\n\nend %End of glmfit_multilevel \n\nfunction [b, sterr, t, p, dfe, phi, V] = first_level_model(y, X, varargin)\n\n% defaults\n% -------------------------------------------------------------------\nverbose = 0;\nverbstr = 'noverbose';\narorder = 0; % or Zero for no AR\ninterceptstr = 'intercept';\n\n% optional inputs\n% -------------------------------------------------------------------\nfor varg = 1:length(varargin)\n if ischar(varargin{varg})\n switch varargin{varg}\n\n % reserved keywords\n case 'verbose all', verbose = 1; verbstr = 'verbose';\n case 'verbose', % do nothing\n case {'ar', 'arorder'} , arorder = varargin{varg+1};\n %otherwise, disp(['Unknown input string option: ' varargin{varg}]);\n\n case 'noint', interceptstr = 'noint';\n end\n end\nend\n\nk = size(X, 2) + 1;\n\n[whnan X y] = nanremove(X, y);\n\nif isempty(X)\n % no data\n \n [b, t, p, sterr] = deal(NaN * ones(k, 1));\n dfe = deal(NaN);\n if arorder, phi = NaN * ones(arorder, 1); else phi = NaN; end\n V = [];\n \n return\n \nend\n\n% set up X matrix: intercept first\nif ~strcmp(interceptstr, 'noint')\n X = setup_X_matrix(X, y);\nend\n\nif arorder\n % if we have missing observations or redundant columns, let's\n % regularize a bit so we can still estimate this, using a ridge prior\n % The degree of regularization is arbitrary.\n % V is used to estimate variance components and re-weight.\n if rank(X) < size(X, 2)\n disp('WARNING! RANK DEFICIENT. THIS FUNCTION WILL RETURN AN ERROR.')\n X = [X; eye(size(X, 2)) ./ size(X, 1)];\n if ~strcmp(interceptstr, 'noint'), X(:, 1) = 1; end\n y = [y; ones(size(X, 2), 1) .* nanmean(y)];\n end\n \n [t, dfe, b, phi, sigma, sterr] = fit_gls(y, X, [], arorder);\n p = 2 * (1 - tcdf(abs(t), dfe)); % two-tailed\n\n V = inv(X' * X) * sigma .^ 2; % Var/Cov mtx, Precision^-1, used in weighted est. and empirical bayes\n \nelse\n % if we have missing observations or redundant columns, let's\n % regularize a bit so we can still estimate this, using a ridge prior\n % The degree of regularization is arbitrary.\n if rank(X) < size(X, 2)\n disp('WARNING! RANK DEFICIENT. THIS FUNCTION WILL RETURN AN ERROR.')\n X = [X; eye(size(X, 2)) ./ size(X, 1)];\n if ~strcmp(interceptstr, 'noint'), X(:, 1) = 1; end\n y = [y; ones(size(X, 2), 1) .* nanmean(y)];\n end\n \n stats = glmfit_general(y, X, verbstr, interceptstr);\n t = stats.t; dfe = stats.dfe; b = stats.beta; phi = NaN; sterr = stats.ste; p = stats.p;\n\n V = inv(X' * X) * stats.var; % Var/Cov mtx, Precision^-1, used in weighted est. and empirical bayes\nend\n\nend\n\nfunction X = setup_X_matrix(X, y)\n % set up X matrix: intercept first\n [n, k] = size(X);\n if n == 0\n n = size(y, 1);\n end\n equal_x = false(1, k);\n for i = 1:k\n if all(X(:, i) == X(1, i))\n % weights are equal\n equal_x(i) = 1;\n end\n end\n if any(equal_x)\n error('Warning: some columns of X have no variance. Do not enter intercept in X; it will be added automatically as the first predictor.');\n X(:, equal_x) = [];\n end\n X = [ones(n, 1) X];\nend\n\n% -------------------------------------------------------------------------\n% Setup inputs, print info to screen if verbose\n% THIS IS FOR SECOND-LEVEL MODEL -- NOT FIRST\n% -------------------------------------------------------------------------\nfunction [names, analysisname, beta_names, robust_option, weight_option, inference_option, ...\n verbose, dosave, doplots, ...\n verbstr, savestr, plotstr, ...\n targetu, nresample, whpvals_for_boot, ...\n permsign] = ...\n setup_inputs(Y, X, varargin)\n\n% Initial compliance checks\n% ----------------------------------------------------------------\n[n, k] = size(X);\nnvars = size(Y, 2);\nnobs_tmp = size(Y, 1);\n\n% Check sizes\nif nobs_tmp ~= n, error('Y and X must have same number of rows!'); end\n\n% Check intercept\nif ~(all(X(:, 1) == X(1)))\n error('First column of X must be an intercept column. (e.g., all ones)');\nend\n\nbeta_names = cell(1, k);\nfor i = 1:k\n beta_names{i} = sprintf('2nd-level B%02d', i);\nend\n\n\n% Defaults\n% ----------------------------------------------------------------\n\n% General Defaults\nnames = cell(1, nvars); % variable names, columns of Y\nfor i = 1:nvars, names{i} = ['1st-level B' num2str(i)]; end\n\nanalysisname = 'Second Level of Multilevel Model ';\n\n% Estimation Defaults\nrobust_option = 'no'; % robust IRLS; 'no' 'yes'\nweight_option = 'unweighted'; % 'weighted' 'unweighted'\nforce_centering = true; % force 2nd-level predictor centering\n\n% Inference defaults\ninference_option = 't-test'; % 't-test' 'bootstrap' 'signperm'\n\n% Display control defaults\nverbose = 1; % verbose output\ndosave = 0; % save figures at end\ndoplots = 0; % make plots\nplotstr = 'noplots';\nsavestr = 'nosave';\nverbstr = 'verbose';\n\nsavefilename = 'glmfit_general_output.txt';\n\n% Bootstrap defaults\ntargetu = .20; % proportion contribution of boot procedure to p-value\nnresample = 1000; % initial bootstrap samples\nwhpvals_for_boot = 1:size(Y,2); % indices of p-values, the min of which is used to determine boot samples needed\n% lower p-values require more boot samples\n% for the p-vals to be meaningful.\n\n% Sign perm defaults\npermsign = []; % empty: setup new sign permutation indices\n% if entered: keep same permutation matrix\n% across repeated calls (much faster! but\n% reduces accuracy in simulations!)\n\n% Inputs\n% ----------------------------------------------------------------\nfor i = 1:length(varargin)\n if ischar(varargin{i})\n switch varargin{i}\n % General Defaults\n case 'names', names = varargin{i+1}; varargin{i+1} = [];\n case 'analysisname', analysisname = varargin{i+1}; varargin{i+1} = [];\n case 'beta_names', beta_names = varargin{i+1}; varargin{i+1} = [];\n\n % Estimation Defaults\n case 'robust', robust_option = 'yes';\n case {'weight', 'weighted', 'var', 's2'}, weight_option = 'weighted';\n case {'nocenter', 'nocentering'}, force_centering = false;\n \n % Inference defaults\n case {'boot1', 'boot', 'bootstrap'}, inference_option = 'bootstrap';\n case {'sign perm', 'signperm', 'sign'}, inference_option = 'signperm';\n case {'t-test', 'ttest'}, inference_option = 't-test';\n\n % Display control defaults\n case {'plot', 'plots'}, doplots = 1; plotstr = 'plots';\n case {'noplots', 'noplot'}, doplots = 0; plotstr = 'noplots';\n\n case {'dosave', 'save', 'saveplots'}, dosave = 1; savestr = 'save';\n case 'verbose', verbose = 1; verbstr = 'verbose';\n case 'noverbose', verbose = 0; verbstr = 'noverbose';\n\n case {'savefile', 'savefilename'}, savefilename = varargin{i + 1}; varargin{i+1} = [];\n\n % Bootstrap defaults\n case 'nresample', nresample = varargin{i+1};\n case {'pvals', 'whpvals_for_boot'}, whpvals_for_boot = varargin{i+1};\n\n\n % Sign perm defaults\n case {'permsign'}, permsign = varargin{i+1};\n\n case 'intercept'\n \n otherwise\n fprintf('Warning! Unknown input string option: %s', varargin{i});\n\n end\n end\nend\n\n% all the other checking, etc. is done in glmfit_general\n\n\n \nis_intercept = all(abs(diff(X, 1, 1)) < 100 * eps);\n\nif force_centering\n X(:, ~is_intercept) = X(:, ~is_intercept) - mean(X(:, ~is_intercept));\nend\n\nis_centered = abs(mean(X)) < 100*eps;\n\nany_noncentered = any(~is_intercept & ~is_centered);\nintercept_beta_name = 'Within-person average effects';\n\nif any_noncentered\n disp('WARNING!!! Some 2nd-level predictors are not mean-centered.')\n disp('Within-person effects and P-values are NOT interpretable as the')\n disp('average within-person effect');\n \n intercept_beta_name = 'Within-person effects when all 2nd-level predictors are zero';\n \nend\n\n% fix names by adding intercept if needed\n% This is over-rided by user input\nif length(beta_names) == k - 1\n if ~isrow(beta_names), beta_names = beta_names'; end\n beta_names = {intercept_beta_name beta_names{:}};\nend\n\n\n\nend\n\n\n% -------------------------------------------------------------------------\n% Check variances\n% -------------------------------------------------------------------------\n\nfunction [Y, X1, X2] = check_variances_and_exclude(Y, X1, X2)\nxvar = cellfun(@var, X1, 'UniformOutput', false);\nxvar = cat(1, xvar{:});\nwh = any(xvar < 100 * eps, 2);\nif any(wh)\n disp('Warning! Some participants have no variance in X column(s) and will be excluded')\n fprintf('Participant numbers:');\n fprintf('%d ', find(wh));\n fprintf('\\n');\nend\n\nwh_out = wh;\n\nyvar = cellfun(@var, Y, 'UniformOutput', false);\nyvar = cat(1, yvar{:});\nwh = any(yvar < 100 * eps, 2);\nif any(wh)\n disp('Warning! Some participants have no variance in Y and will be excluded')\n fprintf('Participant numbers:');\n fprintf('%d ', find(wh));\n fprintf('\\n');\nend\n\nwh_out = wh_out | wh;\n\nX1(wh_out) = [];\nY(wh_out) = [];\nif ~isempty(X2), X2(wh_out, :) = []; end\n\nend\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/glmfit_multilevel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.7690802264851918, "lm_q1q2_score": 0.6957488463336008}} {"text": "function [ craft_vel craft_theta a e EoverM GMsun] = predictor(craft_v,angle1, source_planet,target_planet )\n%PREDICTOR - ellipse determination function\n% the equations in this procedure is based on the \n% This will determine the critical ellipse parametres - mainly a and e,\n% based on the trajectory characteristics of the craft.\n% the procedure for determining a and e from craft trajectory is based on: \n%'Satellite Orbits and Gravitational Assist for Planets' (2008)-Larry Bogan\n%http://www.bogan.ca/astrpages.html\n\n%target planets are indexed , as below.\n%1 = sun\n%2 = earth\n%3 = jupiter\n%4 = saturn\n%5 = uranus\n%6 =neptune\n\n\nmass = [1.9891e+30,5.9736e+24,1.8983e+27,5.68462313752e+26,8.6810e25,1.0243e26, 750];\nm_sun = mass(1);\n% planet masses \nm_craft = mass(7);\nG = 6.67428e-11;\ntp = target_planet;\nsp = source_planet;\nAU=149597870691;\nradius = [ (6.955e8/AU) 1 5.2 9.582 20.083 30.1036];\n\n\n%####################################################################\n% Step 1 Determine GMsun \n% This determines GM with respect to the sun. This is necesscary as all of\n% the tjrajectory ellipses are with respect to the sun as a focus.\n\nGMsun_metres = m_sun * G; \n\nGMsun = GMsun_metres / AU; % this GMsun in m/s)^2 - being converted to AU\n\nGMsun = GMsun / 1e6; %to go from square metres to square kilometres\n% Should be 887 AU/(km/s)^2\n\n%####################################################################\n%Step 2 Energy over mass relationship \n\n\n\n\nKE = (m_craft * craft_v^2)/2;\n\nGPE = GMsun * m_craft / radius(sp);\nE = (KE - GPE);\nEoverM = (KE - GPE)/ m_craft;\n\n% if KE - GPE is negative, it means the orbit is still elliptical around\n% the sun - if not it is a hyperbolic orbit and it will leave the solar\n% system.\n\n\n\n%####################################################################\n%Step 3 determine semimajor axis\n\na = -0.5 * GMsun / EoverM;\n\n\n%####################################################################\n%Step 4 - work out circular velocity, based on using the semi major axis as\n%a radius. The radius is converted to metres from AU, and period is\n%converted to seconds from years.\n\nP = a^(3/2);\n\nVc = 2 * pi * a * AU / P;\n\nVc3 = Vc / (365 * 86164);\nVcirc = Vc3 / 1000;\n\n\n%####################################################################\n% Step 5 from semimajor axis determine the period \n% using Kepeler's third law - already been done above\n\nP = a^(3/2);\n\n%####################################################################\n%Step 6 work out the areal velocity - \n\n\nV_wrt_planet = craft_v * cosd(angle1); \n\nV_wrt_planet_AU = (V_wrt_planet / (AU / 1000)) * 86164 * 365;\n\nA = radius(sp) * V_wrt_planet_AU /2;\n\n%A = area of ellipse / priod - areal velocity\n\n\n\n\n%####################################################################\n%Step 7 \n% determines eccentricity from Areal Velocity and period of Ellipse \n\n\nKK = A * P / (pi * a^2);\n\ne = sqrt(1 - KK^2);\n\n\n%####################################################################\n%Step 8 - from semimajor axis and eccentricity, we get apophelion \n%and periphelion \n\nr_a = a*(1 + e);\nr_p = a*(1 - e);\n\n\n\n%####################################################################\n%Step 9 determine true anomoly - the angle between periphelion and the\n%spacecraft\n\n%1 = sun\n%2 = earth\n%3 = jupiter\n%4 = saturn\n%5 = uranus\n%6 =neptune\n%7 = our spacecraft\n\nV_per = Vcirc * sqrt((1+e) /(1-e));\nV_aps = Vcirc * sqrt((1-e) /(1+e));\n\nGSI = radius(tp) * (( mass(tp)/mass(1))^(2/5));\n% \ncraft_vel = sqrt( (2* EoverM) + (2 * GMsun ./ (radius(tp)- GSI)));\n\n%its reduced by tp.\ncraft_theta = acosd((a*(1 - e^2)/(radius(tp)- GSI) - 1)/e);\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/26107-interplanetary-mission-planner-verifier/predictor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133548753619, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6956997678168225}} {"text": "% LTFAT - Non-stationary Gabor systems\n%\n% Florent Jaillet and Peter L. S\u00f8ndergaard, 2011 - 2018\n%\n% Transforms\n% NSDGT - Non-stationary DGT\n% UNSDGT - Uniform non-stationary DGT\n% INSDGT - Inverse NSDGT and UNSDGT\n% NSDGTREAL - Non-stationary DGT for real-valued signals\n% UNSDGTREAL - Uniform non-stationary DGT for real-valued signals\n% INSDGTREAL - Inverse NSDGTREAL and UNSDGTREAL\n%\n% Window construction and bounds\n% NSGABDUAL - Non-stationary dual windows\n% NSGABTIGHT - Non-stationary tight windows\n% NSGABFRAMEBOUNDS - Frame bounds of an NSDGT system\n% NSGABFRAMEDIAG - Diagonal of non-stationary Gabor frame operator\n%\n% Plots\n% PLOTNSDGT - Plot output coefficients from NSDGT\n% PLOTNSDGTREAL - Plot output coefficients from NSDGTREAL\n%\n% For help, bug reports, suggestions etc. please visit \n% http://github.com/ltfat/ltfat/issues\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/nonstatgab/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.6956934401981376}} {"text": "function x = dge_sl ( n, a_lu, pivot, b, job )\n\n%*****************************************************************************80\n%\n%% DGE_SL solves a system factored by DGE_FA.\n%\n% Discussion:\n%\n% The DGE storage format is used for a general M by N matrix. A storage \n% space is made for each logical entry. The two dimensional logical\n% array is mapped to a vector, in which storage is by columns.\n%\n% DGE_SL is a simplified version of the LINPACK routine DGESL.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 March 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be positive.\n%\n% Input, real A_LU(N,N), the LU factors from DGE_FA.\n%\n% Input, integer PIVOT(N), the pivot vector from DGE_FA.\n%\n% Input, real B(N), the right hand side vector.\n%\n% Input, integer JOB, specifies the operation.\n% 0, solve A * x = b.\n% nonzero, solve A' * x = b.\n%\n% Output, real X(N), the solution vector.\n%\n x(1:n) = b(1:n);\n%\n% Solve A * x = b.\n%\n if ( job == 0 )\n%\n% Solve PL * Y = B.\n%\n for k = 1 : n-1\n\n l = pivot(k);\n\n if ( l ~= k )\n t = x(l);\n x(l) = x(k);\n x(k) = t;\n end\n\n x(k+1:n) = x(k+1:n) + a_lu(k+1:n,k)' * x(k);\n\n end\n%\n% Solve U * X = Y.\n%\n for k = n : -1 : 1\n x(k) = x(k) / a_lu(k,k);\n x(1:k-1) = x(1:k-1) - a_lu(1:k-1,k)' * x(k);\n end\n%\n% Solve A' * X = B.\n%\n else\n%\n% Solve U' * Y = B.\n%\n for k = 1 : n\n x(k) = ( x(k) - x(1:k-1) * a_lu(1:k-1,k) ) / a_lu(k,k);\n end\n%\n% Solve ( PL )' * X = Y.\n%\n for k = n-1 : -1 : 1\n\n x(k) = x(k) + x(k+1:n) * a_lu(k+1:n,k);\n\n l = pivot(k);\n\n if ( l ~= k )\n t = x(l);\n x(l) = x(k);\n x(k) = t;\n end\n\n end\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/geometry/dge_sl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.6956934263034871}} {"text": "function e = year_to_epact_julian ( y )\n\n%*****************************************************************************80\n%\n%% YEAR_TO_EPACT_JULIAN returns the epact of a Julian year.\n%\n% Discussion:\n%\n% The epact of a year is the age in days of the notional moon on\n% the first day of the year. If the year begins with a new moon,\n% the epact is zero. If the new moon occurred the day before,\n% the epact is 1. There is a unique epact for every golden number.\n%\n% Bear in mind that the notional moon is not the one in the sky,\n% but a theoretical one that satisfactorily approximates the behavior\n% of the real one, but which is tame enough to be described by a formula.\n%\n% Example:\n%\n% Year Golden Number Epact\n%\n% 1 BC 1 8\n% 1 AD 2 19\n% 2 AD 3 0\n% 3 AD 4 11\n% 4 AD 5 22\n% 5 AD 6 3\n% 6 AD 7 14\n% 7 AD 8 25\n% 8 AD 9 6\n% 9 AD 10 17\n% 10 AD 11 28\n% 11 AD 12 9\n% 12 AD 13 20\n% 13 AD 14 1\n% 14 AD 15 12\n% 15 AD 16 23\n% 16 AD 17 4\n% 17 AD 18 15\n% 18 AD 19 26\n% 19 AD 1 8\n% 20 AD 2 19\n% 1066 AD 3 0\n% 1900 AD 1 8\n% 1919 AD 1 8\n% 1938 AD 1 8\n% 1957 AD 1 8\n% 1976 AD 1 8\n% 1995 AD 1 8\n% 2014 AD 1 8\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 June 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Edward Richards,\n% Mapping Time, The Calendar and Its History,\n% Oxford, 1999.\n%\n% Parameters:\n%\n% Input, integer Y, the year. The year 0 is illegal input.\n%\n% Output, integer E, the epact, between 0 and 28.\n%\n if ( y == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'YEAR_TO_EPACT_JULIAN - Fatal error!\\n' );\n fprintf ( 1, ' Illegal input Y = 0.\\n' );\n error ( 'YEAR_TO_EPACT_JULIAN - Fatal error!' );\n end\n\n g = year_to_golden_number ( y );\n\n e = i4_wrap ( 11 * g - 3, 0, 29 );\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/calpak/year_to_epact_julian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.6956934143487724}} {"text": "function [TRI,xout,yout,uout,interp] = PlotField2D(Nout, xin, yin, uin)\n\n% function [TRI,xout,yout,uout,interp] = PlotField2D(Nout, xin, yin, uin)\n% Purpose: filled contour plot of solution data\n\nGlobals2D;\n \n% build equally spaced grid on reference triangle\nNpout = (Nout+1)*(Nout+2)/2;\nrout = zeros(Npout,1); sout = zeros(Npout,1); \nsk = 1;\nfor n=1:Nout+1\n for m=1:Nout+2-n\n rout(sk) = -1 + 2*(m-1)/Nout;\n sout(sk) = -1 + 2*(n-1)/Nout;\n counter(n,m) = sk; sk = sk+1;\n end\nend\n\n% build matrix to interpolate field data to equally spaced nodes\ninterp = InterpMatrix2D(rout, sout);\n\n% build triangulation of equally spaced nodes on reference triangle\ntri = []; \nfor n=1:Nout+1\n for m=1:Nout+1-n,\n v1 = counter(n,m); v2 = counter(n,m+1); \n v3 = counter(n+1,m); v4 = counter(n+1,m+1);\n if(v4) \n tri = [tri;[[v1 v2 v3];[v2 v4 v3]]]; \n else\n tri = [tri;[[v1 v2 v3]]]; \n end\n end\nend\n\n% build triangulation for all equally spaced nodes on all elements\nTRI = [];\nfor k=1:K\n TRI = [TRI; tri+(k-1)*Npout];\nend\n\n% interpolate node coordinates and field to equally spaced nodes\nxout = interp*xin; yout = interp*yin; uout = interp*uin;\n\n% render and format solution field\ntrisurf(TRI, xout(:), yout(:), uout(:));\nshading interp, material shiny, lighting gouraud \ncamlight headlight\nreturn\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/JSHesthaven&TWarburton/ServiceRoutines/PlotField2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6956626509407255}} {"text": "function lines2d(varargin)\n%LINES2D Description of functions operating on planar lines.\n%\n% The term 'line' refers to a planar straight line, which is an unbounded\n% curve. Line segments defined between 2 points, which are bounded, are\n% called 'edge', and are presented in file 'edges2d'.\n%\n% A straight line is defined by a point (its origin), and a vector (its\n% direction). The parameters are bundled into a 1-by-4 row vector:\n% LINE = [x0 y0 dx dy];\n%\n% A line contains all points (x,y) such that:\n% x = x0 + t*dx\n% y = y0 + t*dy;\n% for all t between -infinity and +infinity.\n%\n% See also \n% points2d, vectors2d, edges2d, rays2d\n% createLine, cartesianLine, medianLine, edgeToLine, lineToEdge\n% orthogonalLine, parallelLine, bisector, radicalAxis\n% lineAngle, linePosition, projPointOnLine\n% isPointOnLine, distancePointLine, isLeftOriented\n% intersectLines, intersectLineEdge, clipLine\n% reverseLine, transformLine, drawLine\n% lineFit\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2008-10-13, using Matlab 7.4.0.287 (R2007a)\n% Copyright 2008-2022 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas\n\nhelp('lines2d');\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/lines2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.6956626345178815}} {"text": "function pass = test_deriv(~)\n% TEST_DERIV Test the chebfun/deriv method\n\n% This test creates some chebfun, evaluates the derivative and compares with the\n% results of feval(diff(...)).\n\n% Our CHEBFUN\nu = chebfun(@(x) sin(exp(x)), [0 2]);\n\n%% Evaluation at one point, default value of derivative\npass(1) = norm(deriv(u, 1) - feval(diff(u), 1)) == 0;\n\n%% Higher order derivative\npass(2) = norm(deriv(u, .5, 3) - feval(diff(u, 3), .5)) == 0;\n\n%% Default derivative at a vector of points\nxx = linspace(0.1, 0.5, 11);\npass(3) = norm(deriv(u, xx) - feval(diff(u), xx)) == 0;\n\n%% Higher derivative, vector of points\npass(4) = norm(deriv(u, xx, 4) - feval(diff(u, 4), xx)) == 0;\n\n%% Array valued CHEBFUN at a vector of points\npass(5) = norm(deriv([u cos(u)], xx) - feval(diff([u cos(u)]), xx)) == 0;\npass(6) = norm(deriv([u cos(u)], xx, 2) - feval(diff([u cos(u)], 2), xx)) == 0;\n\n%% Left- and right-sided evaluation\nx = chebfun(@(x) x, [-1 1]);\nv = cumsum(sign(x));\npass(7) = norm(feval(diff(v), 0, 'left') - deriv(v, 0, 'left')) == 0;\npass(8) = norm(feval(diff(v, 2), 0, '+') - deriv(v, 0, '+', 2)) == 0;\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun/test_deriv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6956062973419983}} {"text": "function [bb] = tribal1(pp,ee)\n%TRIBAL1 compute the circumballs associated with a 1-simplex\n%triangulation embedded in R^2 or R^3.\n% [BB] = TRIBAL1(PP,EE) returns the circumscribing balls\n% associated with the edge segments in [PP,EE], such that\n% BB = [XC,YC,RC.^2].\n\n% Darren Engwirda : 2017 --\n% Email : de2363@columbia.edu\n% Last updated : 02/05/2018\n\n bb = pwrbal1(pp,zeros(size(pp,1),1),ee) ;\n\nend\n\n\n\n", "meta": {"author": "dengwirda", "repo": "mesh2d", "sha": "749a81073facc8b5db02e4f7bb0b10c9783cebd3", "save_path": "github-repos/MATLAB/dengwirda-mesh2d", "path": "github-repos/MATLAB/dengwirda-mesh2d/mesh2d-749a81073facc8b5db02e4f7bb0b10c9783cebd3/mesh-ball/tribal1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6956062973419983}} {"text": "function S = L0Restoration(Im, kernel, lambda, kappa)\n%%\n% Image restoration with L0 prior\n% The objective function: \n% S^* = argmin ||I*k - B||^2 + lambda |\\nabla I|_0\n%% Input:\n% @Im: Blurred image\n% @kernel: blur kernel\n% @lambda: weight for the L0 prior\n% @kappa: Update ratio in the ADM\n%% Output:\n% @S: Latent image\n%\n% The Code is created based on the method described in the following paper \n% [1] Jinshan Pan, Zhe Hu, Zhixun Su, and Ming-Hsuan Yang,\n% Deblurring Text Images via L0-Regularized Intensity and Gradient\n% Prior, CVPR, 2014. \n% [2] Li Xu, Cewu Lu, Yi Xu, and Jiaya Jia. Image smoothing via l0 gradient minimization.\n% ACM Trans. Graph., 30(6):174, 2011.\n%\n% Author: Jinshan Pan (sdluran@gmail.com)\n% Date : 05/18/2014\n\nif ~exist('kappa','var')\n kappa = 2.0;\nend\n%% pad image\nH = size(Im,1); W = size(Im,2);\nIm = wrap_boundary_liu(Im, opt_fft_size([H W]+size(kernel)-1));\n%%\nS = Im;\nbetamax = 1e5;\nfx = [1, -1];\nfy = [1; -1];\n[N,M,D] = size(Im);\nsizeI2D = [N,M];\notfFx = psf2otf(fx,sizeI2D);\notfFy = psf2otf(fy,sizeI2D);\n%%\nKER = psf2otf(kernel,sizeI2D);\nDen_KER = abs(KER).^2;\n%%\nDenormin2 = abs(otfFx).^2 + abs(otfFy ).^2;\nif D>1\n Denormin2 = repmat(Denormin2,[1,1,D]);\n KER = repmat(KER,[1,1,D]);\n Den_KER = repmat(Den_KER,[1,1,D]);\nend\nNormin1 = conj(KER).*fft2(S);\n%% \nbeta = 2*lambda;\nwhile beta < betamax\n Denormin = Den_KER + beta*Denormin2;\n h = [diff(S,1,2), S(:,1,:) - S(:,end,:)];\n v = [diff(S,1,1); S(1,:,:) - S(end,:,:)];\n if D==1\n t = (h.^2+v.^2)m, coef m->k\n mn=[1 0; 1 1]; % [i,j] = number of terms in m(i+1) whose lowest moment is >= j+1\n fa=1; % factorial list\nend\n% check arguments\nif nargin<4 || isempty(a)\n a=1;\nend\nif nargin<3 || isempty(b)\n b=0;\nend\nif isempty(t)\n t='';\nend\nn=length(m); % number of moments required\nif n>n0 % check if need to update coefficient arrays\n if fix(n/2-1)>length(fa) % we need factorials up to fix(n/2-1)\n fal=length(fa);\n fa(fix(n/2-1),1)=0; % enlarge factorial vector\n for i=fal+1:fix(n/2-1)\n fa(i)=i*fa(i-1); % create new factorials\n end\n end\n bc(n,n+1)=0; % enlarge binomial coefficient array\n mk{n-1,1}=[]; % enlarge cumulant coefficient array\n mn(n-1,n-1)=0; % enlarge cumulant coefficient counts\n for i=n0+1:n\n bc(i,1:i+1)=[1 bc(i-1,1:i)+bc(i-1,2:i+1)]; % update binomial coefficients\n j=fix((i+1)/2); % first coefficient row to sum\n nr=1+sum(mn(((j-1:i-3)+(n-1)*(i-j-2:-1:0)))); % number of terms\n mki=zeros(nr,i+1); % coefficient matrix\n ix=1;\n mki(1,i-1:i+1)=1; % first term always has a coefficient of 1\n for r=j:i-2 % previous coefficients to use\n nk=mn(r-1+(n-1)*(i-r-2)); % number of new coefficients for this value of r\n mkk=mk{r-1}; % old coefficients for this value of r\n mkik=mkk(1:nk,1:r-1); % extract just the list of powers for each term\n mkik(:,i-r-1)=mkik(:,i-r-1)+1; % increment the power of moment i-r\n mki(ix+1:ix+nk,1:r-1)=mkik; % and save as new terms\n mki(ix+1:ix+nk,i)=mkk(1:nk,r)*bc(i,i-r+1)./mkik(:,i-r-1); % calculate coefficient for r->m\n rho=sum(mkik,2)-1; % rho is one less than the sum of the moment powers\n mki(ix+1:ix+nk,i+1)= mki(ix+1:ix+nk,i).*fa(rho).*(-1).^rho; % calculate coefficient for m->r\n ix=ix+nk; % update the number of terms so far\n end\n mki=sortrows(mki); % sort according to the lowest moment that is used\n mn(i-1,1:i-1)=[nr sum(cumprod(mki(:,1:i-2)==0,2),1)]; % update count of terms with lowest moment >= j+1\n mk{i-1}=mki; % save in persistent cell array\n end\n n0=n; % coefficients are now calculated up to order n\nend\n% apply scaling if input type is 'c' or 'k'\nmu=a*m(1)+b; % calculate new mean\nc=m; % initialize output shapes\nr=m;\nk=m;\nm=m(:)'; % now force the input to be a row vector\nif any(t=='k')\n tin=3; % set input type\n k(:)=k(:)'.*a.^(1:n);\n k(1)=0; % first cumulant is actually zero\nelseif any(t=='r')\n tin=2;\nelse\n tin=1;\n c(:)=c(:)'.*a.^(1:n);\n c(1)=0; % first cenral moment is actually zero\nend\ntout=[(~any(t=='K') && ~any(t=='R')) (nargout>=2 || any(t=='R')) (nargout>=3 || any(t=='K'))]; % outputs required\nfor il=1:2 % loop through conversion routines twice\n % first convert between moments\n if il==1 % convert unscaled R -> C\n v=[1 m.*a.^(1:n)];\n bb=b-mu;\n doit=tin==2 && (tout(1) || tout(3));\n else % convert C -> R or unscaled R -> R\n if tin==2 % input type was 'r' (v is OK from previous iteration)\n bb=b;\n else % input type was 'c' or 'k'\n v=[1 c(:)'];\n bb=mu;\n end\n doit=tout(2); % convert if 'R' output required\n end\n if doit\n y=v(2:end);\n if bb~=0 % don't bother if the constant term is zero\n for i=1:n\n y(i)=polyval(bc(i,1:i+1).*v(1:i+1),bb);\n end\n end\n if il==1 % convert unscaled R -> C\n c(:)=y;\n else % convert C -> R or unscaled R -> R\n r(:)=y;\n end\n end\n % now convert cumulants to/from moments\n if il==1 % convert K -> C\n x=k(:)';\n doit=tin==3 && (tout(1) || tout(2));\n else % convert C -> K\n x=c(:)';\n doit=(tin<3) && tout(3);\n end\n if doit\n y=x;\n for i=4:n\n mki=mk{i-1}; % get coefficient matrix\n y(i)=mki(:,i-1+il)'*prod(repmat(x(2:i),size(mki,1),1).^mki(:,1:i-1),2); % calculate moment/cumulant (neat but not efficient)\n end\n if il==1 % converted K -> C\n c(:)=y;\n else % converted C -> K\n k(:)=y;\n end\n end\nend\nc(1)=mu; % restore the means\nk(1)=mu;\nif any(t=='R')\n c=r;\nelseif any(t=='K')\n c=k;\nend\n", "meta": {"author": "jtkim-kaist", "repo": "Speech-enhancement", "sha": "84f1a3c1273fb4952522b911dd62cbb4476a534d", "save_path": "github-repos/MATLAB/jtkim-kaist-Speech-enhancement", "path": "github-repos/MATLAB/jtkim-kaist-Speech-enhancement/Speech-enhancement-84f1a3c1273fb4952522b911dd62cbb4476a534d/SE/lib/sub_lib/voicebox/pdfmoments.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6956062883706752}} {"text": "function [coef]=comp_dgtreal_fb(f,g,a,M)\n%COMP_DGTREAL_FB Filter bank DGT\n% Usage: c=comp_dgt_fb(f,g,a,M,boundary);\n% \n% This is a computational routine. Do not call it directly.\n\n% See help on DGT.\n\n% AUTHOR : Peter L. S\u00f8ndergaard.\n\n% Calculate the parameters that was not specified.\nL=size(f,1);\nN=L/a;\ngl=length(g);\nW=size(f,2); % Number of columns to apply the transform to.\nglh=floor(gl/2); % gl-half\nM2=floor(M/2)+1;\n\n\n% Conjugate the window here.\ng=conj(fftshift(g));\n\ncoef=zeros(M,N,W,assert_classname(f,g));\n\n% Replicate g when multiple columns should be transformed.\ngw=repmat(g,1,W);\n\n% ----- Handle the first boundary using periodic boundary conditions. ---\nfor n=0:ceil(glh/a)-1\n\n % Periodic boundary condition.\n fpart=[f(L-(glh-n*a)+1:L,:);...\n f(1:gl-(glh-n*a),:)];\n\n fg=fpart.*gw;\n \n % Do the sum (decimation in frequency, Poisson summation)\n coef(:,n+1,:)=sum(reshape(fg,M,gl/M,W),2);\n \nend;\n\n% ----- Handle the middle case. ---------------------\nfor n=ceil(glh/a):floor((L-ceil(gl/2))/a)\n \n fg=f(n*a-glh+1:n*a-glh+gl,:).*gw;\n \n % Do the sum (decimation in frequency, Poisson summation)\n coef(:,n+1,:)=sum(reshape(fg,M,gl/M,W),2);\nend;\n\n% ----- Handle the last boundary using periodic boundary conditions. ---\nfor n=floor((L-ceil(gl/2))/a)+1:N-1\n\n % Periodic boundary condition.\n fpart=[f((n*a-glh)+1:L,:);... % L-n*a+glh elements\n f(1:n*a-glh+gl-L,:)]; % gl-L+n*a-glh elements\n\n fg=fpart.*gw;\n \n % Do the sum (decimation in frequency, Poisson summation)\n coef(:,n+1,:)=sum(reshape(fg,M,gl/M,W),2); \nend;\n\n% --- Shift back again to make it a frequency-invariant system. ---\nfor n=0:N-1\n coef(:,n+1,:)=circshift(coef(:,n+1,:),n*a-glh);\nend;\n\ncoef=fftreal(coef);\ncoef=reshape(coef,M2,N,W);\n\n%c=c(1:M2,:);\n\n\n\n% Simple code using a lot of circshifts.\n% Move f initially so it lines up with the initial fftshift of the\n% window\n%f=circshift(f,glh);\n%for n=0:N-1\n % Do the inner product.\n %fg=circshift(f,-n*a)(1:gl,:).*gw;\n \n % Periodize it.\n %fpp=zeros(M,W);\n %for ii=0:gl/M-1\n % fpp=fpp+fg(ii*M+1:(ii+1)*M,:);\n %end;\n% fpp=sum(reshape(fg,M,gl/M,W),2);\n \n % Shift back again.\n% coef(:,n+1,:)=circshift(fpp,n*a-glh); %),M,1,W);\n \n%end;\n\n\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/comp/comp_dgtreal_fb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6956062815669469}} {"text": "function [coef]=comp_dgt_fb(f,g,a,M)\n%COMP_DGT_FB Filter bank DGT\n% Usage: c=comp_dgt_fb(f,g,a,M);\n% \n% This is a computational routine. Do not call it directly.\n%\n% See help on DGT.\n\n% AUTHOR : Peter L. S\u00f8ndergaard.\n\n% Calculate the parameters that was not specified.\nL=size(f,1);\nN=L/a;\ngl=length(g);\nW=size(f,2); % Number of columns to apply the transform to.\nglh=floor(gl/2); % gl-half\n\n\n% Conjugate the window here.\ng=conj(fftshift(g));\n\ncoef=zeros(M,N,W,assert_classname(f,g));\n\n% ----- Handle the first boundary using periodic boundary conditions. ---\nfor n=0:ceil(glh/a)-1\n\n % Periodic boundary condition.\n fpart=[f(L-(glh-n*a)+1:L,:);...\n f(1:gl-(glh-n*a),:)];\n \n fg=bsxfun(@times,fpart,g);\n \n % Do the sum (decimation in frequency, Poisson summation)\n coef(:,n+1,:)=sum(reshape(fg,M,gl/M,W),2);\n \nend;\n\n% ----- Handle the middle case. ---------------------\nfor n=ceil(glh/a):floor((L-ceil(gl/2))/a)\n \n fg=bsxfun(@times,f(n*a-glh+1:n*a-glh+gl,:),g);\n \n % Do the sum (decimation in frequency, Poisson summation)\n coef(:,n+1,:)=sum(reshape(fg,M,gl/M,W),2);\nend;\n\n% ----- Handle the last boundary using periodic boundary conditions. ---\nfor n=floor((L-ceil(gl/2))/a)+1:N-1\n\n % Periodic boundary condition.\n fpart=[f((n*a-glh)+1:L,:);... % L-n*a+glh elements\n f(1:n*a-glh+gl-L,:)]; % gl-L+n*a-glh elements \n \n fg=bsxfun(@times,fpart,g);\n \n % Do the sum (decimation in frequency, Poisson summation)\n coef(:,n+1,:)=sum(reshape(fg,M,gl/M,W),2); \nend;\n\n% --- Shift back again to make it a frequency-invariant system. ---\nfor n=0:N-1\n coef(:,n+1,:)=circshift(coef(:,n+1,:),n*a-glh);\nend;\n\n\ncoef=fft(coef);\n\n\n\n% Simple code using a lot of circshifts.\n% Move f initially so it lines up with the initial fftshift of the\n% window\n%f=circshift(f,glh);\n%for n=0:N-1\n % Do the inner product.\n %fg=circshift(f,-n*a)(1:gl,:).*gw;\n \n % Periodize it.\n %fpp=zeros(M,W);\n %for ii=0:gl/M-1\n % fpp=fpp+fg(ii*M+1:(ii+1)*M,:);\n %end;\n% fpp=sum(reshape(fg,M,gl/M,W),2);\n \n % Shift back again.\n% coef(:,n+1,:)=circshift(fpp,n*a-glh); %),M,1,W);\n \n%end;\n\n\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/comp/comp_dgt_fb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6955981514950229}} {"text": "function elliptic_em_values_test ( )\n\n%*****************************************************************************80\n%\n%% ELLIPTIC_EM_VALUES_TEST demonstrates the use of ELLIPTIC_EM_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 February 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ELLIPTIC_EM_VALUES_TEST:\\n' );\n fprintf ( 1, ' ELLIPTIC_EM_VALUES stores values of\\n' );\n fprintf ( 1, ' the complete elliptic integral of the second\\n' );\n fprintf ( 1, ' kind, with parameter modulus M.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' M EM(M)\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, x, fx ] = elliptic_em_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %12f %24.16f\\n', x, fx );\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/test_values/elliptic_em_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.8633916064587, "lm_q1q2_score": 0.6955760779177697}} {"text": "function [mad_similarity cos_similarity r_similarity] = outliers_xval(obj)\n% Similarity metrics comparing each image to the mean of others in the set using repeated k-fold cross-validation\n%\n% :Usage:\n% ::\n%\n% [mad_similarity cos_similarity r_similarity] = outliers_xval(obj)\n%\n% :Background:\n% ::\n% Assessing image outliers is crucial for detecting artifacts and other\n% violations of assumptions underlying image analysis. \n% \n% Many methods are available, but they often use measures of variance defined relative to a sample,\n% which creates problems. For example, Mahalanobis distance uses squared\n% multivariate distances among images. This is useful, but detects only\n% relative outliers. If there are many corrupted images, all images will\n% look normal by comparison to others. Inter-image correlations are also\n% commonly used. These are also useful, but they are also sensitive to the\n% overall distribution of artifacts across the set. If there are many\n% corrupted images, correlations will tend to be low overall, and the bad \n% images will be harder to detect. In cases where comparing individual\n% images to a gold standard is desired, but there is no external standard\n% image (perhaps because images look somewhat different in each sample),\n% comparing images to a mean image derived from others in the set may be useful. \n% In this case, however, it's desirable for the mean to be derived\n% independent of the test image itself. This can be accomplished with\n% cross-validation, bootstrapping, or jackknife analyses.\n%\n% Here, we compare each of a set of images to a mean derived from other\n% images in the set using k-fold cross-validation. To average over errors\n% related to the particular fold splits chosen, we average over a number of\n% repeated cross-valiations.\n%\n% We return two error metrics, which have different desirable properties\n% depending on the type of image and use case.\n% - Pearson's correlation (r): correlation is insensitive to mean shift and scale\n% it is most useful when only the pattern in the image is meaningful\n% and/or images will be rescaled in analysis, and the zero-point and\n% scale are not important.\n%\n% - cosine similarity is sensitive to mean shift, not scale\n% This is useful for images with a meaningful zero-point that should match across images,\n% but where the scale is irrelevant (or will be removed, e.g., via\n% normalization)\n%\n% - Absolute agreement is most relevant when mean and scale are both relevant\n% This is the case with many images, e.g., those subjected to group statistical analysis of intensity\n% values. e.g., when testing task - control contrast images across a group,\n% We are interested in whether the group mean is 0. The zero-point is meaningful and \n% it should agree if the individual test images are replicates of the same effect.\n% The scale is also meaningful, as deviations in the values determine the variance estimate \n% of the test statistic. Any deviation is treated as error, even if it results from \n% mean shift or scale varation in the image as a whole. \n%\n%\n% :Inputs:\n%\n% **obj:**\n% an image_vector object (e.g., fmri_data) with >=5 images\n%\n% :Outputs:\n%\n% **mad_similarity:**\n% [nimages x 1] vector of absolute agreement between each image and the mean, \n% 1/(1+MAD), averaged across repeated k-fold\n%\n% **cos_similarity:**\n% [nimages x 1] vector of cosine similarity between each image and the mean, \n% averaged across repeated k-fold\n%\n% **r_similarity:**\n% [nimages x 1] vector of correlation between each image and the mean, \n% averaged across repeated k-fold\n%\n% ----------------------------------------------------------------------\n% Examples:\n% ----------------------------------------------------------------------\n% test_images = load_image_set('emotionreg');\n%\n% [mad_similarity cos_similarity r_similarity ] = outliers_xval(test_images);\n% figure; plot(mad_similarity)\n% hold on;\n% plot(cos_similarity)\n% plot(r_similarity)\n% legend({'Abs agreement' 'Cos sim' 'r'})\n%\n% % Compare with outliers based on Mahalanobis and other metrics\n% figure; \n% [est_outliers_uncorr, est_outliers_corr, outlier_tables] = outliers(test_images, 'notimeseries');\n%\n% Another, larger sample dataset\n% test_images = load_image_set('kragel18_alldata');\n% [mad_similarity cos_similarity r_similarity ] = outliers_xval(test_images);\n\n% ..\n% Author and copyright information:\n%\n% Copyright (C) 2023 Tor Wager\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% ..\n\n% ----------------------------------------------------------------------\n% Default parameters\n% ----------------------------------------------------------------------\n\nnfolds = 5;\nnrepeats = 100; % number of cross-validation repeats\n\n% ----------------------------------------------------------------------\n% Set up variables and functions\n% ----------------------------------------------------------------------\n\n% Analyze gray matter, where we expect meaningful variation\n%obj_orig = obj;\nobj = apply_mask(obj, fmri_data(which('gray_matter_mask.nii'), 'noverbose'));\n\nnimages = size(obj.dat, 2);\n\nif nimages < 5, error('Object must contain at least 5 images'), end\n\nYid = ones(nimages, 1);\n\n[r_test, cos_sim_test, mad_test] = deal(NaN .* zeros(nimages, nrepeats));\n\ncvpart = cvpartition(Yid, 'k', nfolds);\n% [S.trIdx, S.teIdx] = xval_stratified_holdout_leave_whole_subject_out(S.Y, S.id, 'doverbose', doverbose, 'doplot', doplot, 'nfolds', nfolds);\n\ncos_sim = @(x, y) x' * y ./ (norm(x) * norm(y));\n\n% ----------------------------------------------------------------------\n% Run\n% ----------------------------------------------------------------------\n\nfor p = 1:nrepeats\n\n % Draw a new k-fold cross-validation partition\n cvpart = cvpart.repartition;\n\n for i = 1:nfolds\n\n train_set = get_wh_image(obj, cvpart.training(i));\n test_set = get_wh_image(obj, cvpart.test(i));\n\n m = mean(train_set);\n\n % correlation is insensitive to mean shift and scale\n % cosine sim is sensitive to mean shift, not scale\n % for images with a meaningful zero-point that should match across images,\n % cosine sim is more meaningful.\n % if mean and scale are both relevant, as with contrast images, absolute\n % agreement may be the best metric, e.g. MAD = median absolute deviation\n\n r_test(cvpart.test(i), p) = corr(m.dat, test_set.dat)';\n\n cos_sim_test(cvpart.test(i), p) = cos_sim(m.dat, test_set.dat)';\n\n mad_test(cvpart.test(i), p) = median(abs(m.dat - test_set.dat))';\n\n end % k-fold\n\nend % cv repeats\n\n% ----------------------------------------------------------------------\n% Calculate final similarity measures\n% ----------------------------------------------------------------------\n\nr_similarity = mean(r_test')';\ncos_similarity = mean(cos_sim_test')';\n\nmad_dissim = mean(mad_test')'; % this is actually still deviation here\nmad_similarity = 1./(1+mad_dissim); % convert to similarity, scale from [0 1] \n% +1 scales so that zero error (perfect agreement) will have a value of 1.\n\nend % function\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/@image_vector/outliers_xval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6955197321437117}} {"text": "function C = EstimateUnitNormalCorr(Y_X, exp_window_size, shrink_factor)\n%C = EstimateUnitNormalCorr(Y_X, exp_window_size, shrink_factor)\n% Estimate the correlation matrix of a joint normal sample, where each\n% element is assumed to be unit normal. Each column of Y_F is a random\n% variable and each row is a sample. Exponential weighting is applied in\n% time, and RMT filtering is applied using the \"PG\" algorithm.\n%\n% To do!!:\n% - review implementation of exponential weighting and RMT\n% - add choice for rectangular averaging?\n% - add choice for other RMT schemes?\n% Code by S. Gollamudi. This version December 2009. \n\n\n[T,N] = size(Y_X);\nuse_rmt_cleaning = 0;\n\n%% Estimate sample correlation matrix with exponential averaging\n\n% compute exponential weights\nlambda = 2/exp_window_size;\nexp_wts = (1-lambda).^(T-1:-1:0)*(lambda/(1-(1-lambda)^T));\nm_exp_wts = repmat(exp_wts',1,N);\n\n% compute the exponentially weighted sample mean\nmeanYX = sum(m_exp_wts.*Y_X, 1);\n% remove mean from the time series Y_X\nY_X = Y_X - repmat(meanYX,T,1);\n\n% compute the exponentially weighted standard deviation\nstdYX = sqrt(sum(m_exp_wts.*(Y_X.^2), 1));\n\n% compute the exponentially weighted correlation matrix\nC = ((m_exp_wts.*Y_X)'*Y_X)./(stdYX'*stdYX);\ndiag_indx = 1:(N+1):(N*N);\n\n\n%% Clean the correlation matrix estimate using Random Matrix Theory\n\nif use_rmt_cleaning,\n\n % ratio of the effective series length and the number of variables\n Q = exp_window_size/N;\n\n % maximum random eigenvalue\n e_max = rmtEigenLim(Q,1);\n\n [eigVec,eigVal] = eig(C);\n [eigVal,Idx] = sort(diag(eigVal),'descend');\n eigVec=eigVec(:,Idx);\n % K is the # of non-random eigenvalues\n K=length(find(eigVal>e_max));\n % PG filter\n eigVal(K+1:end)=mean(eigVal(K+1:end));\n C = eigVec*diag(eigVal)*eigVec';\n % make the diagonal elements equal to one\n C(diag_indx) = 1;\n \nend\n \n%% Shrink to average correlation\n\n% compute the average pairwise correlation coefficient\nrho = (sum(sum(C)) - N)/(N*(N-1));\nC_rho = rho*ones(N,N);\nC_rho(diag_indx) = 1;\n\n% shrink C towards C_rho\nif nargin < 3, shrink_factor = 1/3; end\nC = (1-shrink_factor)*C + shrink_factor*C_rho;\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/26853-factors-on-demand/FactorsOnDemand/StatisticalVsCrossSectional/EstimateUnitNormalCorr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6955197275275602}} {"text": "function simpletrans\n% 1D transport - modelling with extensions for decay and linear sorption\n% using mixing cell method \n%\n% $Ekkehard Holzbecher $Date: 2006/02/08 $\n%--------------------------------------------------------------------------\nT = 2; % maximum time [s]\nL = 1; % length [m]\nD = 0.1; % dispersivity [m*m/s]\nv = 1; % velocity [m/s]\nlambda = 1.2; % decay constant [1/s]\nR = 1; % retardation [1]\nc0 = 0; % initial concentration [kg/m*m*m]\ncin = 1; % inflow concentration [kg/m*m*m]\n\ndtout = 0.05; % output-timestep [s]\ndxmax = 0.02; % maximum grid spacing [m]\n%------------------------ output parameters\ngplot = 2; % =1: breakthrough curves; =2: profiles \ngsurf = 0; % surface\ngcont = 0; % =1: contours; =2: filled contours\nganim = 2; % animation\n\n%------------------------ execution----------------------------------------\n\ndtout = dtout/R; % timestep reduction for retardation case \ndx = dtout*v; % grid spacing\nK = 1; % K = reduction factor for grid spacing\nif (dx>dxmax) K = ceil(dx/dxmax); end\ndx = dx/K; % reduced grid spacing\ndtadv=dtout/K; % advection-timestep \nN = ceil(L/dx); % N = number of cells\nx = linspace(0,(N-1)*dx,N);% nodes on x-axis \nNeumann = D*dtadv/dx/dx; % Neumann-number for dispersion\nM = max (1,ceil(3*Neumann)); % M = reduction factor to fulfill Neumann-condition \nNeumann = Neumann/M/R; % reduced Neumann-number\ndtdiff = dtadv/M; % diffusion timestep\nt = dtadv;\n\nclear c c1 c2;\nc(1:N) = c0; c1 = c;\nk = 1; kanim = 1;\nwhile (t < T/R)\n for i=1:M\n kinetics; % decay (1. order kinetics) \n diffusion; % diffusion\n end\n advection; % advection\n if k >= K \n c = [c;c1]; k=0; \n end\n t = t + dtadv; k = k+1;\nend\nxlabel ('space'); ylabel ('concentration');\n\n%-------------------- graphical output-------------------------------------\n\nswitch gplot\n case 1 \n plot (c) % breakthrough curves\n xlabel ('time'); ylabel ('concentration');\n case 2 \n plot (x,c','--')% profiles\n xlabel ('space'); ylabel ('concentration');\nend\nif gsurf % surface\n figure; surf (x,[0 t],c); \n xlabel ('space'); ylabel ('time'); zlabel('concentration');\nend \nif gcont figure; end\nswitch gcont\n case 1 \n contour (c) % contours\n grid on; xlabel ('space'); ylabel ('time');\n case 2 \n contourf(c) % filled contours\n colorbar; xlabel ('space'); ylabel ('time');\nend \nif (ganim)\n [FileName,PathName] = uiputfile('*.mpg'); \n figure; if (ganim > 1) hold on; end \n for j = 1:size(c,1)\n axis manual; plot (x,c(j,:),'r','LineWidth',2); \n YLim = [min(c0,cin) max(c0,cin)]; \n legend (['t=' num2str(dtout*(j-1))]); \n Anim(j) = getframe;\n plot (x,c(j,:),'b','LineWidth',2); \n end\n mpgwrite (Anim,colormap,[PathName '/' FileName]); % mgwrite not standard MATLAB \n movie (Anim,0); % play animation\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/15646-environmental-modeling/simpletrans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6955197212396376}} {"text": "% this script compares hedging based on Black-Scholes deltas with Factors on Demand hedging \n% see Meucci, A. (2010) \"Factors on Demand\", Risk, 23, 7, p. 84-89\n% available at http://ssrn.com/abstract=1565134\n\nclc; clear; close all;\n%%%%%%%%%%%%%%%%%%%\n% inputs\ntau_tilde=5; % estimation step (days)\ntau=40; % time to horizon (days)\nTime2Mats=[100 150 200 250 300]; % current time to maturity of call options in days\nStrikes = [850 880 910 940 970]; % strikes of call options, same dimension as Time2Mat\n\nr_free=0.04; % risk-free rate\nJ=10000; % number of simulations\n\n%%%%%%%%%%%%%%%%%%%\n% load underlying and volatility surface\nload('DB_ImplVol');\nnumCalls = length(Time2Mats);\ntimeLength = length(spot);\nnumSurfPoints = length(days2Maturity)*length(moneyness);\n\n%%%%%%%%%%%%%%%%%%%\n% estimate invariant distribution assuming normality\n% variables in X are changes in log(spot) and changes in log(imp.vol)\n% evaluated at the 'numSurfPoints' points on the vol surface (vectorized).\nX = zeros(timeLength-1,numSurfPoints+1);\n% log-changes of underlying spot\nX(:,1) = diff(log(spot));\n\n% log-changes of implied vol for different maturities\nimpVolSeries = reshape(impVol,timeLength,numSurfPoints);\nfor i = 1:numSurfPoints,\n X(:,i+1) = diff(log(impVolSeries(:,i)));\nend\nmuX = mean(X);\nSigmaX = cov(X,1);\n\n%%%%%%%%%%%%%%%%%%%\n% project distribution to investment horizon\nmuX = muX*tau/tau_tilde;\nSigmaX = SigmaX*tau/tau_tilde;\n\n%%%%%%%%%%%%%%%%%%%\n% linearly interpolate the vol surface at the current time to obtain\n% implied vol for the given calls today, and price the calls\nspot_T = spot(end);\nvolSurf_T = squeeze(impVol(end,:,:));\ntime2Mat_T = Time2Mats;\nmoneyness_T = Strikes/spot_T;\nimpVol_T = interpne(volSurf_T,[time2Mat_T',moneyness_T'],{days2Maturity,moneyness})'; % function by John D'Errico\ncallPrice_T = BlackScholesCall(spot_T,Strikes,r_free,impVol_T,Time2Mats/252);\n\n%%%%%%%%%%%%%%%%%%%\n% generate simulations at horizon\nX_ = mvnrnd(muX,SigmaX,J);\n\n% interpolate vol surface at horizon for the given calls\nspot_ = spot_T*exp(X_(:,1));\nimpVol_ = zeros(J,numCalls);\nfor j = 1:J,\n volSurf = volSurf_T.*exp(reshape(X_(j,2:end),length(days2Maturity),length(moneyness)));\n time2Mat_ = Time2Mats-tau;\n moneyness_ = Strikes/spot_(j);\n impVol_(j,:) = interpne(volSurf,[time2Mat_',moneyness_'],{days2Maturity,moneyness})'; % function by John D'Errico\nend\n\n% price the calls\ncallPrice_ = zeros(J,numCalls);\nfor i = 1:numCalls,\n callPrice_(:,i) = BlackScholesCall(spot_,Strikes(i),r_free,impVol_(:,i),time2Mat_(i)/252);\nend\n\n% linear returns of the calls\nRc = callPrice_./repmat(callPrice_T,J,1) - 1;\n% linear returns of the underlying\nRsp = spot_./spot_T - 1;\n\n%%%%%%%%%%%%%%%%%%%\n% compute the OLS linear (affine) model: Rc = a + b*Rsp + U\nZ = [ones(J,1), Rsp];\nolsLoadings = (Rc'*Z)/(Z'*Z);\na = olsLoadings(:,1);\nb = olsLoadings(:,2);\n\n%%%%%%%%%%%%%%%%%%%\n% compute Black-Scholes delta and cash held in replicating portfolio\n[callPrice_T,delta_T,cash_T] = BlackScholesCall(spot_T,Strikes,r_free,impVol_T,Time2Mats/252);\na_bs = cash_T./callPrice_T*r_free*tau/252;\nb_bs = (delta_T./callPrice_T.*spot_T)';\nfprintf('OLS: a = [%s\\t]\\n',sprintf('\\t%7.4f',a'))\nfprintf('B-S: a = [%s\\t]\\n',sprintf('\\t%7.4f',a_bs'))\nfprintf('OLS: b = [%s\\t]\\n',sprintf('\\t%7.4f',b'))\nfprintf('B-S: b = [%s\\t]\\n',sprintf('\\t%7.4f',b_bs'))\n\nfor i = 1:numCalls\n figure\n plot(Rsp,Rc(:,i),'.')\n xlabel('return underlying')\n ylabel('return call option')\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/26853-factors-on-demand/FactorsOnDemand/NoGreekHedging/S_Main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894576856559, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6955197166234861}} {"text": "function normalizedU = hyperConvexHullRemoval(U,wavelengths)\n%HYPERCONVEXHULLREMOVAL Performs spectral normalization via convex hull removal \n%\n% Usage\n% [ normalizedU ] = hyperConvexHullRemoval( U, wavelengths )\n%\n% Inputs\n% U - 2D HSI data (p x q)\n% wavelengths - Wavelength of each band (p x 1)\n%\n% Outputs\n% normalizedU - Data with convex hull removed (p x q)\n%\n% Author\n% Luca Innocenti\n%\n% References\n% Clark, R.N. and T.L. Roush (1984) Reflectance Spectroscopy: Quantitative\n% Analysis Techniques for Remote Sensing Applications, J. Geophys. Res., 89,\n% 6329-6340. \n\n% Metadata and formatting\nwavelengths = wavelengths(:);\np = length(wavelengths);\nq = size(U,2);\nU = U.';\n\nU(:,1) = 0;\nU(:,420) = 0;\n\nnormalizedU = zeros(q,420);\n\n% The algorithm\nfor s = 1:q,\n rifl = U(s,:);\n k = convhull(wavelengths,rifl');\n c = [rifl(k); wavelengths(k)'];\n d = sortrows(c',2);\n \n xs = d(:,2);\n ys = d(:,1);\n [xsp, idx] = unique(xs);\n ysp = ys(idx);\n rifl_i = interp1(xsp,ysp,wavelengths');\n \n for t = 1:420,\n if rifl_i(t) ~= 0\n normalizedU(s,t) = rifl(t)/rifl_i(t);\n else\n normalizedU(s,t) = 1;\n end\n end\nend\n\nnormalizedU = normalizedU.';\n", "meta": {"author": "davidkun", "repo": "HyperSpectralToolbox", "sha": "147d58e6efe839e8945dc0d4e8d65029884137f1", "save_path": "github-repos/MATLAB/davidkun-HyperSpectralToolbox", "path": "github-repos/MATLAB/davidkun-HyperSpectralToolbox/HyperSpectralToolbox-147d58e6efe839e8945dc0d4e8d65029884137f1/functions/hyperConvexHullRemoval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6954940142758761}} {"text": "function out=prox_Huber(x,mu,alpha)\n%PROX_HUBER computes the proximal operator of the function alpha*H_(mu) \n% where H_(mu)=huber function with parameter mu\n%\n% Usage: \n% out = PROX_HUBER(x,mu,alpha)\n% ===========================================\n% INPUT:\n% x - point to be projected (vector/matrix)\n% mu - positive scalar\n% alpha - positive scalar\n% ===========================================\n% Assumptions:\n% mu is positive\n% ===========================================\n% Output:\n% out - proximal operator at x\n\n% This file is part of the FOM package - a collection of first order methods for solving convex optimization problems\n% Copyright (C) 2017 Amir and Nili Beck\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\nif (nargin < 3)\n error ('usage: prox_huber(x,mu,alpha)') ;\nend\n\nif (alpha < 0)\n error('usage: prox_huber(x,mu,alpha) - alpha should be positive')\nend\n\nif (mu < 0)\n error('usage: prox_huber(x,mu,alpha) - mu should be positive')\nend\n\nout = x*( 1 - alpha/max(norm(x,'fro'),mu+alpha)) ;\n\nend\n\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/tool/FOM_prox functions/prox_Huber.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.695493996184823}} {"text": "% HMPD: Estimate the short-term deviation of Phase Distortion\n%\n% Inputs\n% PD : [NxM rad] A matrix of Phase Distortion to measure the deviation from.\n% N is the number of frames, M is the order of the PD (either the\n% maximum number of harmonics or the number of bins).\n% nbat : The number of frames to consider in the smoothing window, i.e. the\n% window size.\n% \n% Outputs\n% PDD : [NxM rad] The Phase Distortion Deviation (PDD)\n%\n% Copyright (c) 2013 University of Crete - Computer Science Department(UOC-CSD)/ \n% Foundation for Research and Technology-Hellas - Institute\n% of Computer Science (FORTH-ICS)\n%\n% License\n% This file is under the LGPL license, you can\n% redistribute it and/or modify it under the terms of the GNU Lesser General \n% Public License as published by the Free Software Foundation, either version 3 \n% of the License, or (at your option) any later version. This file is\n% distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; \n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n% PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n% details.\n%\n% This function is part of the Covarep project: http://covarep.github.io/covarep\n%\n% Author\n% Gilles Degottex \n%\n\nfunction PDD = hmpd_phase_deviation(PD, nbat)\n\n winlen = round(nbat/2)*2+1;\n % win = hann(winlen);\n win = ones(winlen,1); % Rectangular window is better than smooth window\n % It better discriminates voiced/unvoiced segments\n win = win./sum(win);\n\n % Compute the std in polar coordinates\n % Compute first the center of gravity of the exp(i*angles)\n PDc = filtfilt(win, 1, cos(PD));\n PDs = filtfilt(win, 1, sin(PD));\n\n z = abs(PDc + 1j*PDs); % For the variance, we need only the magnitude\n\n PDD = zeros(size(PDc));\n idx = find(z<1); % To avoid neg sqrt or sqrt(-log(0))\n PDD(idx) = sqrt(-2*log(z(idx))); % Fisher's standard-deviation\n\nreturn\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/vocoder/hmpd/private/hmpd_phase_deviation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436727, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6954939819614931}} {"text": "function [b a]=get_peak_filter(g,Q,f,Fs)\n\nA=10^(g/40);\nw=2*pi*f/Fs;\nsn=sin(w);\ncs=cos(w);\nal=sn/(2*Q);\n\nb=[1+al*A -2*cs 1-al*A];\na=[1+al/A -2*cs 1-al/A];\n\nb=b/a(1);\na=a/a(1);", "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/34739-equalizer-audioplayer-gui/equalizer_matlab_cut/get_peak_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6954909224328988}} {"text": "function ecop = ecopula(x)\n%ECOPULA Empirical copula based on sample X.\n% ECOP = ECOPULA(X) returns bivariate empirical copula. Extension to\n% n dimensional empirical copula is straightforward.\n%\n% Written by Robert Kopocinski, Wroclaw University of Technology,\n% for Master Thesis: \"Simulating dependent random variables using copulas.\n% Applications to Finance and Insurance\".\n% Date: 2007/05/12\n%\n% Reference:\n% [1] Durrleman, V. and Nikeghbali, A. and Roncalli, T. (2000) Copulas approximation and\n% new families, Groupe de Recherche Operationnelle Credit Lyonnais\n\n[m n] = size(x);\n\ny = sort(x);\n\nfor i=1:m\n for j=1:m\n ecop(i,j) = sum( (x(:,1)<=y(i,1)).*(x(:,2)<=y(j,2)) )/m;\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/15449-copula-generation-and-estimation/ecopula.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6954666332243181}} {"text": "% CANFIS Grid Feed-Forward operation.\nfunction y = canfis_grid_forward(x,mean,sigma,b,ThetaL4)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% \t\t\t\t\t\t\t\t \t\t\t\t\t\t\t \t\t\t\t %\n% \t\t\t \tNETWORK FUNCTIONALITY SECTION\t\t\t\t\t %\n% \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n[NumInVars NumInTerms] = size(mean);\n\nNumRules = NumInTerms^NumInVars; \n\n% LAYER 1 - INPUT TERM NODES\nIn2 = x*ones(1,NumInTerms);\nOut1 = 1./(1 + (abs((In2-mean)./sigma)).^(2*b));\n\n% LAYER 2 - PRODUCT NODES\n precond = comb(Out1); \n Out2 = prod(precond,2);\n S_2 = sum(Out2);\n \n% LAYER 3 - NORMALIZATION NODES\n Out3 = Out2./S_2;\n \n% LAYERS 4 - 5: CONSEQUENT NODES - SUMMING NODE\nAux1 = [x; 1]*Out3';\n\na = reshape(Aux1,(NumInVars+1)*NumRules,1); % New Input Training Data shaped as a column vector.\n\ny = ThetaL4'*a; ", "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/36098-adaptive-neuro-fuzzy-inference-systems-anfis-library-for-simulink/Gradient Consistency Check/canfis_grid_forward.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6953963617811302}} {"text": "function Q = IsentropicVortexIC2D(x, y, time)\n \n% function Q = IsentropicVortexIC2D(x, y)\n% Purpose: compute flow configuration given by\n% Y.C. Zhou, G.W. Wei / Journal of Computational Physics 189 (2003) 159 \n\n% based flow parameters\nxo = 5; yo = 0; beta = 5; gamma = 1.4;\nrho = 1; u = 1; v = 0; p = 1;\n\nxmut = x-u*time; ymvt = y-v*time;\nr = sqrt((xmut-xo).^2 + (ymvt-yo).^2);\n\n% perturbed density\nu = u - beta*exp(1-r.^2).*(ymvt-yo)/(2*pi);\nv = v + beta*exp(1-r.^2).*(xmut-xo)/(2*pi);\nrho1 = (1 - ((gamma-1)*beta^2*exp(2*(1-r.^2))/(16*gamma*pi*pi))).^(1/(gamma-1));\np1 = rho1.^gamma;\n\nQ(:,:,1) = rho1; Q(:,:,2) = rho1.*u; Q(:,:,3) = rho1.*v;\nQ(:,:,4) = p1/(gamma-1) + 0.5*rho1.*(u.^2 + v.^2);\nreturn;\n\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/JSHesthaven&TWarburton/CFD2D/IsentropicVortexIC2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138559, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6953963559106852}} {"text": "% y: dimensionanlity-reduced data\n%\teigVector: eigen-vector obtained in kPCA\n% X: data matrix\n% para: parameter of Gaussian kernel\n%\tz: pre-image of y\n\n% Copyright by Quan Wang, 2011/05/10\n% Please cite: Quan Wang. Kernel Principal Component Analysis and its \n% Applications in Face Recognition and Active Shape Models. \n% arXiv:1207.3538 [cs.CV], 2012. \n\nfunction z=kPCA_PreImage(y,eigVector,X,para)\n\niter=1000;\nN=size(X,1);\nd=max(size(y));\n\ngamma=zeros(1,N);\nfor i=1:N\n gamma(i)=eigVector(i,1:d)*y;\nend\n\nz=mean(X)'; % initialization\nfprintf('\\nReconstruction: \\n');\nfor count=1:iter\n fprintf('%d ', count);\n if mod(count,10)==0\n fprintf('\\n');\n end\n \n pre_z=z;\n xx=bsxfun(@minus,X',z);\n xx=xx.^2;\n xx=-sum(xx)/(2*para.^2);\n xx=exp(xx);\n xx=xx.^gamma;\n \n z=xx*X/sum(xx);\n z=z';\n if norm(pre_z-z)/norm(z)<0.0001\n break;\n end\nend\nfprintf('\\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/39715-kernel-pca-and-pre-image-reconstruction/kPCA_v2.0/code/kPCA_PreImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6953398751320652}} {"text": "function [L,S] = PCP(M,lam,tol)\n%\n% [L,S] = PCP(M,lam,opts)\n\n% This code solves the following model\n%\n% min_A { lam*||S(:)||_1 + ||L||_* }\n% s.t. M = S+L\n\n% where M is the data matrix, which will be decomposed into\n% S sparse matrix S and low-rank matrix L.\n%\n% lam -- S small positive parameter\n\n%% parameter setting\nbeta = .25/mean(abs(M(:))); % \nmaxit = 1000;\n\n%% initialization\n[m,n] = size(M);\nS = zeros(m,n);\nL = zeros(m,n);\nLambda = zeros(m,n); % the dual variable\n\n% main\nfor iter = 1:maxit\n \n nrmLS = norm([S,L],'fro');\n % dS, dL record the change of S and L, only used for stopping criterion\n \n %% S - subproblem \n % S = argmin_A lam*||S||_1 - + (beta/2) * ||S+L-M||.^2\n % Define element wise softshinkage operator as \n % softshrink(z; gamma) = sign(z).* max(abs(z)-gamma, 0);\n % S has closed form solution: S=softshrink(Lambda/beta + M - L; lam/beta)\n % (see my slide page 42 Equation (66).\n X = Lambda / beta + M;\n Y = X - L;\n dS = S;\n S = sign(Y) .* max(abs(Y) - lam/beta, 0); % softshinkage operator\n dS = S - dS;\n \n %% L - subproblem\n % L = argmin_B ||L||_* - + + (beta/2) * ||S+L-M||.^2\n % L has closed form solution (singular value thresholding)\n % see my slide page 42, Equation (65).\n Y = X - S;\n dL = L;\n \n %[U,D,V] = svd(Y,'econ'); % use 'econ' is more efficient especially when Y is large\n [U,D,V] = svdecon(Y); % fastest\n \n VT=V';\n D = diag(D);\n ind = find(D > 1/beta);\n D = diag(D(ind) - 1/beta);\n L = U(:,ind) * D * VT(ind,:);\n dL = L - dL;\n \n %% stopping criterion\n RelChg = norm([dS,dL],'fro') / (1 + nrmLS);\n %fprintf('Iter %d, RelChg %4.2e \\n',iter,RelChg);\n if RelChg < tol, break; end\n \n %% Update Lambda (dual variable)\n Lambda = Lambda - beta * (S + L - M);\nend\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/PCP/PCP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6953398624118605}} {"text": "clc;\nclose all;\nclearvars;\nmake mex_lansvd.cpp; \noptions.verbosity = 1;\nA = spx.data.mtx_mkt.abb313;\noptions.k = 4;\n[U, S, V, details] = spx.fast.lansvd(A, 'k', 4, 'verbosity', 0);\n% [U, S, V, details] = spx.fast.lansvd(A, options);\n\nSS = svds(A, 4);\n\nfprintf('Singular values by SVDS: ');\nspx.io.print.vector(SS);\nfprintf('Singular values by LANSVD: ');\nspx.io.print.vector(S);\n\n\n[U, S, V, details] = spx.fast.lansvd(A, 'lambda', 7.51);\nfprintf('Singular values by LANSVD: ');\nspx.io.print.vector(S);\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/library/+spx/+fast/private/test_lansvd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6953398568782457}} {"text": "function [] = test_l1_logistic_regression()\n\n clc;\n clear;\n close all;\n \n \n %% Set algorithms\n if 0\n algorithms = gd_solver_list('ALL'); \n else\n %algorithms = {'PG-BKT', 'PG-TFOCS-BKT', 'APG-BKT', 'APG-TFOCS-BKT', 'Newton-CHOLESKY', 'NCG-BKT','L-BFGS-TFOCS'};\n algorithms = {'APG-BKT', 'APG-TFOCS-BKT'};\n end \n \n \n %% prepare dataset\n if 1\n % generate synthtic data \n d = 100;\n n = 1000;\n data = logistic_regression_data_generator(n, d);\n x_train = data.x_train;\n y_train = data.y_train; \n x_test = data.x_test;\n y_test = data.y_test; \n d = size(x_train,1);\n w_opt = data.w_opt; \n lambda = 0.1; \n else\n % load pre-created synthetic data \n data = importdata('../data/logistic_regression/data_100d_10000.mat'); \n x_train = data.x_train;\n y_train = data.y_train; \n x_test = data.x_test;\n y_test = data.y_test; \n d = size(x_train,1);\n n = length(y_train);\n w_opt = data.w_star;\n lambda = data.lambda; \n end\n \n %% define problem definitions\n problem = l1_logistic_regression(x_train, y_train, x_test, y_test, lambda);\n\n \n %% calculate solution\n if norm(w_opt)\n else\n % calculate solution\n w_opt = problem.calc_solution(1000, 0.05);\n end\n f_opt = problem.cost(w_opt); \n fprintf('f_opt: %.24e\\n', f_opt); \n \n \n %% initialize\n w_init = rand(d,1); \n w_list = cell(length(algorithms),1);\n info_list = cell(length(algorithms),1);\n \n\n %% perform algorithms\n for alg_idx=1:length(algorithms)\n fprintf('\\n\\n### [%02d] %s ###\\n\\n', alg_idx, algorithms{alg_idx});\n \n clear options;\n % general options for optimization algorithms \n options.w_init = w_init;\n options.tol_gnorm = 1e-10;\n options.max_iter = 300;\n options.verbose = true; \n\n switch algorithms{alg_idx}\n case {'PG-BKT'}\n \n options.step_alg = 'backtracking';\n options.step_init_alg = 'bb_init';\n [w_list{alg_idx}, info_list{alg_idx}] = sd(problem, options);\n \n case {'PG-TFOCS-BKT'}\n \n options.step_alg = 'tfocs_backtracking';\n options.step_init_alg = 'bb_init';\n [w_list{alg_idx}, info_list{alg_idx}] = sd(problem, options); \n \n case {'APG-BKT'}\n \n options.step_alg = 'backtracking';\n options.step_init_alg = 'bb_init';\n [w_list{alg_idx}, info_list{alg_idx}] = ag(problem, options);\n \n case {'APG-TFOCS-BKT'}\n \n options.step_alg = 'tfocs_backtracking';\n options.step_init_alg = 'bb_init';\n [w_list{alg_idx}, info_list{alg_idx}] = ag(problem, options); \n \n case {'L-BFGS-BKT'}\n \n options.step_alg = 'backtracking'; \n [w_list{alg_idx}, info_list{alg_idx}] = lbfgs(problem, options);\n \n case {'L-BFGS-WOLFE'}\n \n options.step_alg = 'strong_wolfe'; \n [w_list{alg_idx}, info_list{alg_idx}] = lbfgs(problem, options); \n \n case {'L-BFGS-TFOCS'}\n \n options.step_alg = 'tfocs_backtracking'; \n [w_list{alg_idx}, info_list{alg_idx}] = lbfgs(problem, options); \n\n case {'BFGS-TFOCS'}\n \n options.step_alg = 'tfocs_backtracking'; \n [w_list{alg_idx}, info_list{alg_idx}] = bfgs(problem, options); \n \n case {'Newton-CHOLESKY'}\n\n options.sub_mode = 'CHOLESKY'; \n options.step_alg = 'backtracking';\n %options.step_alg = 'tfocs_backtracking';\n [w_list{alg_idx}, info_list{alg_idx}] = newton(problem, options);\n\n case {'NCG-BKT'}\n \n options.sub_mode = 'STANDARD'; \n options.step_alg = 'backtracking'; \n %options.step_alg = 'tfocs_backtracking';\n %options.beta_alg = 'PR'; \n [w_list{alg_idx}, info_list{alg_idx}] = ncg(problem, options); \n \n otherwise\n warn_str = [algorithms{alg_idx}, ' is not supported.'];\n warning(warn_str);\n w_list{alg_idx} = '';\n info_list{alg_idx} = ''; \n end\n \n end\n \n \n fprintf('\\n\\n');\n \n \n %% plot all\n close all;\n \n % display iter vs cost/gnorm\n display_graph('iter','cost', algorithms, w_list, info_list);\n % display iter vs. l1 norm, i.e. the toral number of non-zero elements \n display_graph('iter','reg', algorithms, w_list, info_list); \n \nend\n\n\n\n\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/gd_test/test_l1_logistic_regression.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.695339855189394}} {"text": "function output = recall(tp,fn)\n%\n% \n% Recall = tp/(tp+fn)\n% (see page 268 of Manning and Schutze)\n%\n% Inputs \n% tp: True Positive\n% fn: False Negative\n% Outputs\n% recall measure\n\noutput = tp/(tp+fn);\n\n\nend\n", "meta": {"author": "faridani", "repo": "MatlabNLP", "sha": "e18e8bc44ecbc8bb6aa57312c1ee22930f805a6f", "save_path": "github-repos/MATLAB/faridani-MatlabNLP", "path": "github-repos/MATLAB/faridani-MatlabNLP/MatlabNLP-e18e8bc44ecbc8bb6aa57312c1ee22930f805a6f/nlp lib/funcs/recall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6953398488292912}} {"text": "% extracts the center (cc,cr) and radius of the largest blob\nfunction [cc,cr,radius,flag]=extractball(Imwork,Imback,index)%,fig1,fig2,fig3,fig15,index)\n \n cc = 0;\n cr = 0;\n radius = 0;\n flag = 0;\n [MR,MC,Dim] = size(Imback);\n\n % subtract background & select pixels with a big difference\n fore = zeros(MR,MC); %image subtracktion\n fore = (abs(Imwork(:,:,1)-Imback(:,:,1)) > 10) ...\n | (abs(Imwork(:,:,2) - Imback(:,:,2)) > 10) ...\n | (abs(Imwork(:,:,3) - Imback(:,:,3)) > 10); \n\n % Morphology Operation erode to remove small noise\n foremm = bwmorph(fore,'erode',2); %2 time\n\n % select largest object\n labeled = bwlabel(foremm,4);\n stats = regionprops(labeled,['basic']);%basic mohem nist\n [N,W] = size(stats);\n if N < 1\n return \n end\n\n % do bubble sort (large to small) on regions in case there are more than 1\n id = zeros(N);\n for i = 1 : N\n id(i) = i;\n end\n for i = 1 : N-1\n for j = i+1 : N\n if stats(i).Area < stats(j).Area\n tmp = stats(i);\n stats(i) = stats(j);\n stats(j) = tmp;\n tmp = id(i);\n id(i) = id(j);\n id(j) = tmp;\n end\n end\n end\n\n % make sure that there is at least 1 big region\n if stats(1).Area < 100 \n return\n end\n selected = (labeled==id(1));\n\n % get center of mass and radius of largest\n centroid = stats(1).Centroid;\n radius = sqrt(stats(1).Area/pi);\n cc = centroid(1);\n cr = centroid(2);\n flag = 1;\n return", "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/14243-2d-target-tracking-using-kalman-filter/target tracking using kalman/extractball.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6952924492347513}} {"text": "classdef svd\n\nmethods(Static)\n\n function [rank, max_gap] = mahdi_rank(singular_values)\n % rank accordingly to mahdi 2013 heuristic\n [ min_val , ind_min ] = min( diff( singular_values(1:end-1) ) ) ;\n rank = ind_min;\n max_gap = -min_val;\n end\n\n function rank = vidal_rank(singular_values,kappa)\n if nargin < 2\n kappa = .1;\n end\n % Rank used in Vidal papers\n n = length(singular_values);\n % we will try rank values between 1 to n-1.\n % an array to store criterion value\n criterion = zeros(1, n-1);\n for(r=1:n-1)\n num = singular_values(r+1)^2;\n den = sum(singular_values(1:r).^2);\n criterion(r)=num/den + kappa*r;\n end\n %criterion\n % find the rank with minimum value of the criterion\n [min_value, index]=min(criterion);\n rank = index;\n end\n\n\n function result = low_rank_approx(X, r)\n % return low rank approximation of X\n [U S V] = svd(X);\n % keep the first r left singular vectors\n U = U(:, 1:r);\n % keep the first r singular values\n S = S(1:r, 1:r);\n % keep the first r right singular vectors\n V = V(:, 1:r);\n % Return the approximation\n result = U * S * V';\n end\n\n function [result, basis] = low_rank_projection(X, r)\n % Projects X to a low dimensional space\n % X is NxS\n % result is RxS\n % basis is [NxR] orthonormal basis\n\n % Compute the SVD\n [U, ~, ~] = svd(X, 0);\n % Choose the low rank basis\n basis = U(:, 1:r);\n % Compute coefficients in this basis\n result = basis' * X;\n end\n\n function result = low_rank_basis(X, r)\n % Returns the ON basis for low rank approximation\n [U S V] = svd(X, 'econ');\n result = U(:, 1:r);\n end\n\n function result = low_rank_bases(X, counts, r)\n % low rank bases for individual subspaces\n K = length(counts);\n % bases cell array\n result = cell(1, K);\n [start_indices, end_indices] = spx.cluster.start_end_indices(counts);\n for k=1:K\n ss = start_indices(k);\n ee = end_indices(k);\n XX = X(:, ss:ee);\n basis = spx.la.svd.low_rank_basis(XX, r);\n result{k} = basis;\n end\n end\n\n\n function [result, r] = mahdi_rank_basis(X)\n [U S V] = svd(X, 'econ');\n sv = diag(S);\n r = spx.la.svd.mahdi_rank(sv);\n % r = r + 1;\n result = U(:, 1:r);\n end\n\n function [result, ranks] = mahdi_rank_bases(X, counts)\n % low rank bases for individual subspaces\n K = length(counts);\n % bases cell array\n result = cell(1, K);\n [start_indices, end_indices] = spx.cluster.start_end_indices(counts);\n ranks = zeros(1, K);\n for k=1:K\n ss = start_indices(k);\n ee = end_indices(k);\n XX = X(:, ss:ee);\n [basis,r] = spx.la.svd.mahdi_rank_basis(XX);\n result{k} = basis;\n ranks(k) = r;\n end\n end\n\n function [result, r] = vidal_rank_basis(X, kappa)\n if nargin < 3\n kappa = 0.1;\n end\n [U S V] = svd(X, 'econ');\n sv = diag(S)';\n r = spx.la.svd.vidal_rank(sv, kappa);\n % r = r + 1;\n result = U(:, 1:r);\n end\n\n function [result, ranks] = vidal_rank_bases(X, counts, kappa)\n if nargin < 3\n kappa = 0.1;\n end\n % low rank bases for individual subspaces\n K = length(counts);\n % bases cell array\n result = cell(1, K);\n [start_indices, end_indices] = spx.cluster.start_end_indices(counts);\n ranks = zeros(1, K);\n for k=1:K\n ss = start_indices(k);\n ee = end_indices(k);\n XX = X(:, ss:ee);\n [basis,r] = spx.la.svd.vidal_rank_basis(XX, kappa);\n result{k} = basis;\n ranks(k) = r;\n end\n end\n\n\n\nend\n\nend", "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/library/+spx/+la/svd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6952924434059413}} {"text": "function [accumX, uniqIndices] = aggregateMatrix(X, indices)\n%%%\n% Fast way of aggregating column vectors based on indices which contain repetitive values.\n% X = [101:105; 11:15];\n% indices = [1 4 4 2 2]\n% aggregateMatrix(X, indices) returns:\n% accumX = \n% 101 209 205\n% 11 29 25\n% uniqIndices = [1 2 4]\n%\n% Thang Luong @ 2015, \n%%%\n\n [uniqIndices, ~, J] = unique(indices);\n numUniqIndices = length(uniqIndices);\n numEmbGrads = length(indices);\n\n if numEmbGrads==1\n accumX = X;\n else\n sparseMatrix = zeros(numEmbGrads, numUniqIndices,'double', 'gpuArray');\n sparseIndices = sub2ind([numEmbGrads, numUniqIndices], 1:numEmbGrads, J'); \n sparseMatrix(sparseIndices) = ones(numEmbGrads, 1);\n accumX = X*sparseMatrix;\n end\nend\n", "meta": {"author": "jiweil", "repo": "Hierarchical-Neural-Autoencoder", "sha": "2cea5c0b687e6d3dfb20dee4bec97aec6b57a95f", "save_path": "github-repos/MATLAB/jiweil-Hierarchical-Neural-Autoencoder", "path": "github-repos/MATLAB/jiweil-Hierarchical-Neural-Autoencoder/Hierarchical-Neural-Autoencoder-2cea5c0b687e6d3dfb20dee4bec97aec6b57a95f/misc/aggregateMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.6952924319419178}} {"text": "% [C, E] = curve_ext(Tx, log2(fs), lambda);\n%\n% Extract a maximum energy, minimum curvature, curve from\n% Synchrosqueezed Representation. Note, energy is given as:\n% abs(Tx).^2\n%\n% This implements the solution to Eq. (8) of [1].\n%\n% 1. E. Brevdo, N.S. Fu\u010dkar, G. Thakur, and H-T. Wu, \"The\n% Synchrosqueezing algorithm: a robust analysis tool for signals\n% with time-varying spectrum,\" 2011.\n%\n% Original Author: Jianfeng Lu (now at NYU CIMS)\n% Maintainer: Eugene Brevdo\n%\n% Inputs:\n% lambda should be >=0. Default: lambda=0\n%\n% Outputs:\n% C: the curve locations (indices)\n% E: the (logarithmic) energy of the curve\n%\n%---------------------------------------------------------------------------------\n% Synchrosqueezing Toolbox\n% Authors: Eugene Brevdo (http://www.math.princeton.edu/~ebrevdo/)\n%---------------------------------------------------------------------------------\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/synchrosqueezing/synchrosqueezing/curve_ext.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7662936430859598, "lm_q1q2_score": 0.6952675836817566}} {"text": "function features = values_to_features(values)\n\t% Convert a time-series obtained from a sample to a feature using\n\t% different kind of statistics over the values and the derivatives\n\n\tmean_val = nanmean(values, 2);\n\tvariance = nanvar(values, 0, 2);\n\t% feature_skewness = skewness(values(~isnan(values)));\n\t% feature_kurtosis = kurtosis(values(~isnan(values)));\n\n\tabs_delta = abs(values(:, 2:end) - values(:, 1:end-1));\n\tmean_delta = nanmean(abs_delta, 2);\n\tvar_delta = nanvar(abs_delta, 0, 2);\n\n\tmaximum = max(values, [], 2);\n\tminimum = min(values, [], 2);\n\n\tfeatures = [mean_val; variance; ... \n\t% feature_skewness; feature_kurtosis; ...\n mean_delta; var_delta; maximum; minimum];\nend", "meta": {"author": "yueyuzhao", "repo": "gyrophone", "sha": "aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e", "save_path": "github-repos/MATLAB/yueyuzhao-gyrophone", "path": "github-repos/MATLAB/yueyuzhao-gyrophone/gyrophone-aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e/values_to_features.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6952675749981323}} {"text": "function val=calcGAE(xTrue,xEst,is3D)\n%%CALCGAE Compute the scalar geometric average error (GAE). Unlike the\n% RMSE, it is not dominated by large individual terms.\n%\n%INPUTS: xTrue The truth data. This is either an xDimXNumSamples matrix or\n% an xDimXNXnumSamples matrix. The latter formulation is\n% useful when the MSE over multiple Monte Carlo runs of an\n% entire length-N track is desired. In the first formulation,\n% we take N=1. Alternatively, if the same true value is used\n% for all numSamples, then xTrue can just be an xDimXN matrix.\n% Alternatively, if xTrue is the same for all numSamples and\n% all N, then just an xDimX1 matrix can be passed. N and\n% numSamples are inferred from xEst.\n% xEst An xDimXnumSamples set of estimates or an xDimXNXnumSamples\n% set of estimates (if values at N times are desired).\n% is3D An optional indicating that xEst is 3D. This is only used if\n% xEst is a matrix. In such an instance, there is an ambiguity\n% whether xEst is truly 2D, so N=1, or whether numSamples=1\n% and xEst is 3D with the third dimension being 1. If this\n% parameter is omitted or an empty matrix is passed, it is\n% assumed that N=1.\n%\n%OUTPUTS: val The 1XN set of scalar GAE values.\n%\n%The GAE is given in Equation 3 in [1].\n%\n%EXAMPLE:\n%For a Gaussian random vector, the root-trace of the covariance matrix is\n%the RMSE. The RMSE is larger than the average Euclidean error, which is\n%also larger than the geometric average error\n% R=[28, 4, 10;\n% 4, 22, 16;\n% 10, 16, 16];%The covariance matrix.\n% xTrue=[10;-20;30];\n% numRuns=100000;\n% xEst=GaussianD.rand(numRuns,xTrue,R);\n% valRMSE=rootTrace=sqrt(trace(R))\n% valAEE=calcAEE(xTrue,xEst)\n% valGAE=calcGAE(xTrue,xEst)\n%\n%REFERENCES:\n%[1] X. R. Li and Z. Zhao, \"Measures of performance for evaluation of\n% estimators and filters,\" in Proceedings of SPIE: Conference on Signal\n% and Data processing of Small Targets, vol. 4473, San Diego, CA, 29\n% Jul. 2001, pp. 530-541.\n%\n%February 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(is3D))\n is3D=false; \nend\n\nxDim=size(xEst,1);\nif(ismatrix(xEst)&&is3D==false)\n N=1;\n numSamples=size(xEst,2);\n xEst=reshape(xEst,[xDim,1,numSamples]);\n \n if(size(xTrue,2)==1)\n %If the true values are the same for all samples.\n xTrue=repmat(xTrue,[1,1,numSamples]);\n else\n xTrue=reshape(xTrue,[xDim,1,numSamples]);\n end\nelse\n N=size(xEst,2);\n numSamples=size(xEst,3);\n \n if(ismatrix(xTrue))\n if(size(xTrue,2)==1)\n %If the true values are the same for all samples and for all N.\n xTrue=repmat(xTrue,[1,N,numSamples]);\n else \n %If the true values are the same for all samples.\n xTrue=repmat(xTrue,[1,1,numSamples]);\n end\n end\nend\n\nval=zeros(1,N);\nfor k=1:N\n val(k)=exp((1/(2*numSamples))*sum(log(sum((xEst(:,k,:)-xTrue(:,k,:)).^2,1))));\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/Performance_Evaluation/calcGAE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.6952431279272616}} {"text": "function value = error_f ( x )\n\n%*****************************************************************************80\n%\n%% ERROR_F computes the error function.\n%\n% Discussion:\n%\n% This function was renamed \"ERROR_F\" from \"ERF\", to avoid a conflict\n% with the name of a corresponding routine often, but not always,\n% supplied as part of the math support library.\n%\n% The definition of the error function is:\n%\n% ERF(X) = ( 2 / SQRT ( PI ) ) * Integral ( 0 <= T <= X ) EXP ( -T**2 ) dT\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 March 2007\n%\n% Author:\n%\n% FORTRAN77 original version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% David Kahaner, Cleve Moler, Steven Nash,\n% Numerical Methods and Software,\n% Prentice Hall, 1989,\n% ISBN: 0-13-627258-4,\n% LC: TA345.K34.\n%\n% Parameters:\n%\n% Input, real X, the argument of the error function.\n%\n% Output, real VALUE, the value of the error function at X.\n%\n persistent nterf;\n persistent sqeps;\n persistent xbig;\n\n erfcs = [ ...\n -0.049046121234691808, -0.14226120510371364, ...\n 0.010035582187599796, -0.000576876469976748, ...\n 0.000027419931252196, -0.000001104317550734, ...\n 0.000000038488755420, -0.000000001180858253, ...\n 0.000000000032334215, -0.000000000000799101, ...\n 0.000000000000017990, -0.000000000000000371, ...\n 0.000000000000000007 ];\n\n sqrtpi = 1.7724538509055160;\n%\n% Initialize the Chebyshev series.\n%\n if ( size ( nterf ) == 0 )\n nterf = inits ( erfcs, 13, 0.1 * eps );\n xbig = sqrt ( - log ( sqrtpi * eps ) );\n sqeps = sqrt ( 2.0 * eps );\n end\n\n y = abs ( x );\n\n if ( y <= sqeps )\n value = 2.0 * x / sqrtpi;\n elseif ( y <= 1.0 )\n value = x * ( 1.0 + csevl ( 2.0 * x * x - 1.0, erfcs, nterf ) );\n elseif ( y <= xbig )\n value = r8_sign ( x ) * ( 1.0 - error_fc ( y ) );\n else\n value = r8_sign ( x );\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/quadrature_test/error_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.6952431248979726}} {"text": "function hypersphere_properties_test01 ( )\n\n%*****************************************************************************80\n%\n%% HYPERSPHERE_PROPERTIES_TEST01 tests the coordinate conversion routines.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 December 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HYPERSPHERE_PROPERTIES_TEST01\\n' );\n fprintf ( 1, ' Test the coordinate conversion routines:\\n' );\n fprintf ( 1, ' CARTESIAN_TO_HYPERSPHERE: X -> R,Theta\\n' );\n fprintf ( 1, ' HYPERSPHERE_TO_CARTESIAN: R,Theta -> X.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Pick a random X, and compute X2 by converting X\\n' );\n fprintf ( 1, ' to hypersphere and back. Consider norm of difference.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' M || X - X2 ||\\n' );\n seed = 123456789;\n n = 1;\n for m = 1 : 5 \n fprintf ( 1, '\\n' );\n for test = 1 : 5\n [ x, seed ] = r8mat_uniform_01 ( m, n, seed );\n [ c, seed ] = r8vec_uniform_01 ( m, seed );\n [ r, theta ] = cartesian_to_hypersphere ( m, n, c, x );\n x2 = hypersphere_to_cartesian ( m, n, c, r, theta );\n err = norm ( x - x2 );\n fprintf ( 1, ' %d %g\\n', m, err );\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/hypersphere_properties/hypersphere_properties_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.6952431241954767}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Gaussian Process Regression 2D Example %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% 1) Load 2D Regression Datasets %%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Example of Gaussian Process Regression (2D)\n%% Generate Random Gaussian distribution\nclear all; close all; clc;\nK = 90;\na =-50;\nb = 50;\nx = a + (b-a).*rand(K,1); \ny = a + (b-a).*rand(K,1); \n\na = 40;\nb = 100;\nvars = a + (b-a).*rand(K,1); \n \nMu = [x,y]';\nSigma = zeros(2,2,K);\n\nfor k=1:K\n Sigma(:,:,k) = eye(2,2) .* vars(k);\nend\n \ngmm_x.Priors = ones(1,K)./K;\ngmm_x.Mu = Mu;\ngmm_x.Sigma = Sigma;\n\n% Generate some training Data\nX = ml_gmm_sample(500,gmm_x.Priors,gmm_x.Mu,gmm_x.Sigma )';\nf = @(X)ml_gmm_pdf(X',gmm_x.Priors,gmm_x.Mu,gmm_x.Sigma );\ny = f(X);\ny = y(:);\n\n% Plot Training Data\n\n% Plot Real Function\noptions = [];\noptions.title = 'Training data';\noptions.surf_type = 'surf';\n\nif exist('h1','var') && isvalid(h1), delete(h1);end\nh1 = ml_plot_value_func(X,f,[1 2],options);hold on\n\n% Plot Training Data\noptions.bFigure = false;\noptions.surf_type = 'scatter';\noptions.points_size = 20;\nml_plot_value_func(X,f,[1 2],options);hold on\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% 2) \"Train\" GPR Model %%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Train GP (no real training, just give parameters)\nepsilon = 0.1;\ndims = 2;\nmodel.X_train = X;\nmodel.y_train = y;\nrbf_var = 25;\ngp_f = @(X)ml_gpr(X,[],model,epsilon,rbf_var);\n\n% Plot Estimated Function\noptions = [];\noptions.title = 'Estimated y=f(x) from Gaussian Process Regression';\noptions.surf_type = 'surf';\nif exist('h2','var') && isvalid(h2), delete(h2);end\nh2 = ml_plot_value_func(X,gp_f,[1 2],options);hold on\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% 3) Test GPR Model on Train points %%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Test GPR\noptions = [];\noptions.bFigure = true;\noptions.title = 'Test data';\noptions.surf_type = 'pcolor';\ndims = [1,2];\n\nif exist('h2','var') && isvalid(h2), delete(h2);end\nh2 = gp_plot(model.X_train,gp_f,dims,options);\ncolorbar\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% 4) Grid Search for GPR with RBF Kernel %%\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% K-fold cross validation \nKfold = 20; \n\ndisp('Parameter grid search GP');\n\nrbf_vars = [5,10,20,40,50,100,10000];\n\ntest = cell(length(rbf_var),1);\ntrain = cell(length(rbf_var),1);\n\n\nfor i=1:length(rbf_vars)\n disp(['[' num2str(i) '/' num2str(length(rbf_vars)) ']']);\n \n f = @(X,y,model)ml_gpr(X,y,model,epsilon,rbf_vars(i));\n [test_eval,train_eval] = ml_kcv(X,y,Kfold,f,'regression');\n \n test{i} = test_eval;\n train{i} = train_eval;\n disp(' ');\nend\n\n%% Get Statistics\n\n[ stats ] = ml_get_cv_grid_states_regression(test,train);\n\n%% Plot Statistics\n\noptions = [];\noptions.title = 'GPR k-CV';\noptions.metrics = {'nrmse','r'}; % <- you can add many other metrics, see list in next cell box\noptions.para_name = 'variance rbf';\n\nif exist('handle','var'), delete(handle); end\n[handle,handle_test,handle_train] = ml_plot_cv_grid_states_regression(stats,rbf_vars,options);\n\n\n%% Full list of evaluation metrics for regression methods\n\noptions.metric = {'mse','nmse','rmse','nrmse','mae','mare','r','d','e','me','mre'};\n\n% '1' - mean squared error (mse)\n% '2' - normalised mean squared error (nmse)\n% '3' - root mean squared error (rmse)\n% '4' - normalised root mean squared error (nrmse)\n% '5' - mean absolute error (mae)\n% '6' - mean absolute relative error (mare)\n% '7' - coefficient of correlation (r)\n% '8' - coefficient of determination (d)\n% '9' - coefficient of efficiency (e)\n% '10' - maximum absolute error (me)\n% '11' - maximum absolute relative error (mre)\n\n\n\n\n\n\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/examples/regression/GPR_2D_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857204, "lm_q2_score": 0.7577943767446201, "lm_q1q2_score": 0.6951267972069435}} {"text": "function kern = gibbsKernParamInit(kern)\n\n% GIBBSKERNPARAMINIT GIBBS kernel parameter initialisation.\n% This is the non stationary kernel proposed by Mark Gibbs in his 1997\n% thesis. It is similar to an RBF but has a length scale that varies\n% with input location. This leads to an additional term in front of\n% the kernel.\n%\n% Given \n% r = sqrt((x_i - x_j)'*(x_i - x_j))\n% \n% we have\n% k(x_i, x_j) = sigma2*Z*exp(-r^2/(l(x)*l(x) + l(x')*l(x')))\n%\n% where\n% Z = sqrt(2*l(x)*l(x')/(l(x)*l(x) + l(x')*l(x'))\n%\n% The parameters are sigma2, the process variance (kern.variance),\n% and the parameters of l(x) which is a function that can be specified by the user, by default an MLP is used.\n%\n% SEEALSO : mlpCreate, gibbsKernSetLengthScaleFunc\n%\n% FORMAT\n% DESC initialises Mark Gibbs's non-stationary\n% kernel structure with some default parameters.\n% ARG kern : the kernel structure which requires initialisation.\n% RETURN kern : the kernel structure with the default parameters placed in.\n%\n% SEEALSO : kernCreate, kernParamInit\n%\n% COPYRIGHT : Neil D. Lawrence, 2006\n\n% KERN\n\nkern.variance = 1;\noptions = mlpOptions(5);\nkern.lengthScaleFunc = modelCreate('mlp', kern.inputDimension, 1, options);\nkern.lengthScaleTransform = optimiDefaultConstraint('positive');\n\nkern.nParams = 1+kern.lengthScaleFunc.numParams;\n\nkern.transforms.index = kern.nParams;\nkern.transforms.type = optimiDefaultConstraint('positive');\n\nkern.isStationary = false;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/gibbsKernParamInit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6951267870497446}} {"text": "function [pos vel] = IntKalman(z)\n%\n%\npersistent A H Q R \npersistent x P\npersistent firstRun\n\n\nif isempty(firstRun)\n firstRun = 1;\n \n dt = 0.1;\n \n A = [ 1 dt;\n 0 1 ];\n H = [0 1];\n \n Q = [ 1 0;\n 0 3 ];\n R = 10;\n\n x = [ 0 20 ]';\n P = 5*eye(2);\nend\n\n \nxp = A*x; \nPp = A*P*A' + Q; \n\nK = Pp*H'*inv(H*Pp*H' + R);\n\nx = xp + K*(z - H*xp);\nP = Pp - K*H*Pp; \n \npos = x(1);\nvel = x(2);", "meta": {"author": "philbooks", "repo": "Kalman-Filter-for-Beginners", "sha": "5190a723dcbf96eacda71ed56abddb3a11779a82", "save_path": "github-repos/MATLAB/philbooks-Kalman-Filter-for-Beginners", "path": "github-repos/MATLAB/philbooks-Kalman-Filter-for-Beginners/Kalman-Filter-for-Beginners-5190a723dcbf96eacda71ed56abddb3a11779a82/11.DvKalman/IntKalman.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6951196004397319}} {"text": "function J=polAzEquiDistRefChangeCrossGrad(pAzPt,latLonRefOld,latLonRefNew,rE)\n%%POLAZEQUIDISTREFCHANGECROSSGRAD Given a point in polar azimuthal\n% coordinates with respect to a reference position on a spherical\n% Earth, find the gradient of the point in a polar azimuthal\n% coordinate system with a difference reference point taken with\n% respect to the point in the original system. This is the gradient of\n% the polAzEquidistRefChange function.\n%\n%INPUTS: pAzPts A 2XN set of the [ground distance; heading] points, with\n% the heading given in radians East of North, to convert.\n% Alternatively, if heights are also given, this can be a 3XN\n% set of points with the height being the third dimension.\n% latLonRefOld A 2X1 [latitude;longitude] reference point in radians about\n% which pAzPts was computed.\n% latLonRefNew A 2X1 [latitude;longitude] reference point in radians with\n% respect to which the function to be differentied is defined.\n% rE The radius of the reference sphere. If this argument is\n% omitted or an empty matrix is passed, the value in\n% Constants.WGS84MeanRadius is used.\n%\n%OUTPUTS: J A 2X2XN matrix holding the gradient of the transformation\n% evaluated at each point in pAzPts (or a 3X3XN matrix if height\n% is also provided). If one says that a point in pAzPts=[p;az;h]\n% and a converted point is [p1;az1;h1], the gradients in 3D are\n% ordered:\n% [dp1dp, dp1dAz, dp1dh;\n% dAz1dp, dAz1dAz, dAz1dh;\n% dh1dp, dh1dAz, dh1dh]; \n% \n%The gradient is the analytic gradient of the spherical Earth conversion\n%given in the function polAzEquidistRefChange. Due to a singularity, the\n%gradient is not valid if the target is exactly on the opposite side of the\n%Earth from the first sensor.\n%\n%EXAMPLE:\n%Given three random points, the accuracy of this function is compared to\n%numeric differentiation. The relative error is on the order of what one\n%might expect due to finite precision limitations.\n% rE=Constants.WGS84MeanRadius;\n% latLonRef1Old=[UniformD.rand(1,[-pi/2;pi/2]);\n% UniformD.rand(1,[-pi;pi])];\n% latLonRefNew=[UniformD.rand(1,[-pi/2;pi/2]);\n% UniformD.rand(1,[-pi;pi])];\n% latLonPt=[UniformD.rand(1,[-pi/2;pi/2]);\n% UniformD.rand(1,[-pi;pi])]; \n% pAzPt=ellips2PolarAzEquidistProj(latLonPt,latLonRef1Old,rE,0);\n% J=polAzEquiDistRefChangeCrossGrad(pAzPt,latLonRef1Old,latLonRefNew,rE);\n% f=@(x)polAzEquidistRefChange(x,latLonRef1Old,latLonRefNew,rE,0);\n% JNumDiff=numDiff(pAzPt,f,2);\n% RelErr=max(max(abs((J-JNumDiff)./JNumDiff)))\n%\n%December 2021 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(rE))\n rE=Constants.WGS84MeanRadius; \nend\n\nnumPoints=size(pAzPt,2);\nif(all(latLonRefOld==latLonRefNew))\n %For the special case of no change, force the result to be exact (avoid\n %finite precision issues).\n numDim=size(pAzPt,1);%2 or 3.\n J=repmat(eye(numDim,numDim),[1,1,numPoints]);\n return;\nend\n\nazStart=greatCircleAzimuth(latLonRefOld,latLonRefNew);\nazOffset1=pi/2-azStart;\nlambda0=greatCircleDistance(latLonRefOld,latLonRefNew,1);\n\nif(size(pAzPt,1)==3)\n J=zeros(3,3,numPoints);\n J(3,3,:)=1;\nelse\n J=zeros(2,2,numPoints);\nend\n\n%Transform into the system with both sensors on the equator.\npAzPt(2,:)=pAzPt(2,:)+azOffset1;\n\np=pAzPt(1,:);\naz=pAzPt(2,:);\n\ncosPre=cos(p/rE);\nsinPre=sin(p/rE);\n\ncosLambda0=cos(lambda0);\nsinLambda0=sin(lambda0);\nsinAz=sin(az);\ncosAz=cos(az);\n\ndenom2=1-(cosPre.*cosLambda0+sinPre.*sinAz.*sinLambda0).^2;\ndenom1=sqrt(denom2);\n\ndp0dp=(cosLambda0.*sinPre-cosPre.*sinAz.*sinLambda0)./denom1;\ndp0dAz=-rE.*sinPre.*cosAz.*sinLambda0./denom1;\n\ndAz0dp=cosAz.*sinLambda0./(rE.*denom2);\ndAz0dAz=sinPre.*(cosLambda0.*sinPre-cosPre.*sinAz.*sinLambda0)./denom2;\n\nJ(1,1,:)=dp0dp;\nJ(2,1,:)=dAz0dp;\nJ(1,2,:)=dp0dAz;\nJ(2,2,:)=dAz0dAz;\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/Cross_Gradients/polAzEquiDistRefChangeCrossGrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6951179244421523}} {"text": "% a=0.005, x^2\n% a=0.0002, abs(x)^3\n% a=0.0001, x^4\n\na = 0.005;\nb = 0.00025;\nxs = 0:50;\nys2 = zeros(length(xs), 1);\nys3 = zeros(length(xs), 1);\nfor i = 1:length(xs)\n ys2(i) = exp(-a*abs(xs(i))^2);\n ys3(i) = exp(-b*abs(xs(i))^3);\nend\nplot(xs, ys2);\nhold on;\nplot(xs, ys3);\nhold off;", "meta": {"author": "eldar", "repo": "deepcut", "sha": "096e2d174ddf2fbdc61458d9e7e6c6e897eac16c", "save_path": "github-repos/MATLAB/eldar-deepcut", "path": "github-repos/MATLAB/eldar-deepcut/deepcut-096e2d174ddf2fbdc61458d9e7e6c6e897eac16c/lib/utils/plot_label_assignment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6951179242877333}} {"text": "% Extract instantaneous phase from a signal\n%\n% This function extracts instantaneous phase of a signal based on Hilbert transform.\n%\n% USAGE\n% phase_deg = general.extractPhase(eeg)\n% eeg Vector that contains a signal\n% phase_deg Vector that contains extracted phase. Vector values are in degrees.\n%\nfunction [phase_deg] = extractPhase(eeg)\n% phase_rad = phase(hilbert(eeg));\n phase_rad = angle(hilbert(eeg)); % faster than phase\n phase_deg = rad2deg(mod(phase_rad, 2*pi));\nend", "meta": {"author": "kavli-ntnu", "repo": "MINI2P_toolbox", "sha": "83311a49baea69ecf027e19390e608fd4eaeae8d", "save_path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox", "path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox/MINI2P_toolbox-83311a49baea69ecf027e19390e608fd4eaeae8d/Analysis/+general/extractPhase.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6950680694778688}} {"text": "%DEMGPARD Demonstrate ARD using a Gaussian Process.\n%\n%\tDescription\n%\tThe data consists of three input variables X1, X2 and X3, and one\n%\ttarget variable T. The target data is generated by computing\n%\tSIN(2*PI*X1) and adding Gaussian noise, x2 is a copy of x1 with a\n%\thigher level of added noise, and x3 is sampled randomly from a\n%\tGaussian distribution. A Gaussian Process, is trained by optimising\n%\tthe hyperparameters using the scaled conjugate gradient algorithm.\n%\tThe final values of the hyperparameters show that the model\n%\tsuccessfully identifies the importance of each input.\n%\n%\tSee also\n%\tDEMGP, GP, GPERR, GPFWD, GPGRAD, GPINIT, SCG\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\nclc;\nrandn('state', 1729);\nrand('state', 1729);\ndisp('This demonstration illustrates the technique of automatic relevance')\ndisp('determination (ARD) using a Gaussian Process.')\ndisp(' ');\ndisp('First, we set up a synthetic data set involving three input variables:')\ndisp('x1 is sampled uniformly from the range (0,1) and has a low level of')\ndisp('added Gaussian noise, x2 is a copy of x1 with a higher level of added')\ndisp('noise, and x3 is sampled randomly from a Gaussian distribution. The')\ndisp('single target variable is given by t = sin(2*pi*x1) with additive')\ndisp('Gaussian noise. Thus x1 is very relevant for determining the target')\ndisp('value, x2 is of some relevance, while x3 should in principle be')\ndisp('irrelevant.')\ndisp(' ');\ndisp('Press any key to see a plot of t against x1.')\npause;\n\nndata = 100;\nx1 = rand(ndata, 1);\nx2 = x1 + 0.05*randn(ndata, 1);\nx3 = 0.5 + 0.5*randn(ndata, 1);\nx = [x1, x2, x3];\nt = sin(2*pi*x1) + 0.1*randn(ndata, 1);\n\n% Plot the data and the original function.\nh = figure;\nplotvals = linspace(0, 1, 200)';\nplot(x1, t, 'ob')\nhold on\nxlabel('Input x1')\nylabel('Target')\naxis([0 1 -1.5 1.5])\n[fx, fy] = fplot('sin(2*pi*x)', [0 1]);\nplot(fx, fy, '-g', 'LineWidth', 2);\nlegend('data', 'function');\n\ndisp(' ');\ndisp('Press any key to continue')\npause; clc;\n\ndisp('The Gaussian Process has a separate hyperparameter for each input.')\ndisp('The hyperparameters are trained by error minimisation using the scaled.')\ndisp('conjugate gradient optimiser.')\ndisp(' ');\ndisp('Press any key to create and train the model.')\ndisp(' ');\npause;\n\nnet = gp(3, 'sqexp');\n% Initialise the parameters.\nprior.pr_mean = 0;\nprior.pr_var = 0.1;\nnet = gpinit(net, x, t, prior);\n\n% Now train to find the hyperparameters.\noptions = foptions;\noptions(1) = 1;\noptions(14) = 30;\n\n[net, options] = netopt(net, options, x, t, 'scg');\n\nrel = exp(net.inweights);\n\nfprintf(1, ...\n '\\nFinal hyperparameters:\\n\\n bias:\\t\\t%10.6f\\n noise:\\t%10.6f\\n', ...\n exp(net.bias), exp(net.noise));\nfprintf(1, ' Vertical scale: %8.6f\\n', exp(net.fpar(1)));\nfprintf(1, ' Input 1:\\t%10.6f\\n Input 2:\\t%10.6f\\n', ...\n rel(1), rel(2));\nfprintf(1, ' Input 3:\\t%10.6f\\n\\n', rel(3));\ndisp(' ');\ndisp('We see that the inverse lengthscale associated with')\ndisp('input x1 is large, that of x2 has an intermediate value and the variance')\ndisp('of weights associated with x3 is small.')\ndisp(' ');\ndisp('This implies that the Gaussian Process is giving greatest emphasis')\ndisp('to x1 and least emphasis to x3, with intermediate emphasis on')\ndisp('x2 in the covariance function.')\ndisp(' ')\ndisp('Since the target t is statistically independent of x3 we might')\ndisp('expect the weights associated with this input would go to')\ndisp('zero. However, for any finite data set there may be some chance')\ndisp('correlation between x3 and t, and so the corresponding hyperparameter remains')\ndisp('finite.')\ndisp('Press any key to continue.')\npause\n\ndisp('Finally, we plot the output of the Gaussian Process along the line')\ndisp('x1 = x2 = x3, together with the true underlying function.')\nxt = linspace(0, 1, 50);\nxtest = [xt', xt', xt'];\n\ncn = gpcovar(net, x);\ncninv = inv(cn);\n[ytest, sigsq] = gpfwd(net, xtest, cninv);\nsig = sqrt(sigsq);\n\nfigure(h); hold on;\nplot(xt, ytest, '-k');\nplot(xt, ytest+(2*sig), '-b', xt, ytest-(2*sig), '-b');\naxis([0 1 -1.5 1.5]);\nfplot('sin(2*pi*x)', [0 1], '--m');\n\ndisp(' ');\ndisp('Press any key to end.')\npause; clc; close(h); clear all\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/netlab3.3/demgpard.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.6949921879602704}} {"text": "function g = sphf2cartf(f, lam, th, coord)\n%SPHF2CARTF Wrapper for evaluating a function defined in Cartesian \n% \n% G = SPHF2CARTF(F, LAM, TH) evaluates the function handle F = F(x,y,z)\n% at x = cos(lam).*sin(th), y = sin(lam).*sin(th), z = cos(th). This is\n% the co-latitude spherical coordinate system.\n%\n% G = SPHF2CARTF(F, LAM, TH, 0) same as SPHF2CARTF(F, LAM, TH).\n%\n% G = SPHF2CARTF(F, LAM, TH, 1) evaluates F = F(x,y,z) at \n% at x = cos(lam).*cos(th), y = sin(lam).*cos(th), z = sin(th). This is\n% the latitude spherical coordinate system.\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% For Developers, recall that: \n% coord - Type of spherical coordinate system:\n% coord = 0 (co-latitude) --> -pi <= lam < pi, 0 <= th <= pi\n% coord = 1 (latitude) --> -pi <= lam < pi, -pi/2 <= th <= pi/2\n% (Default above is co-latitude.)\n\n% TODO: Create separate wrapper functions for latitude/co-latitude so that\n% this if can be removed (thus improving performance.\n\nif ( nargin == 3 )\n coord = 0; % Default is to use co-latitude.\nend\n\nif ( coord == 0 )\n % Latitude: 0 <= theta < pi\n x = cos(lam).*sin(th);\n y = sin(lam).*sin(th);\n z = cos(th);\nelseif ( coord == 1 )\n % Latitude: -pi/2 <= theta < pi/2\n x = cos(lam).*cos(th);\n y = sin(lam).*cos(th);\n z = sin(th);\nelse\n error('SPHEREFUN:sphf2cartf:CoordSysUnknown', ['Unknown coordinate '...\n 'system for the sphere.']);\nend\n\ng = feval(f, x, y, z);\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@spherefun/sphf2cartf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.6949921627624823}} {"text": "%% Dirichlet Mixture\n\n\n\n\n\nclear classes\n\nds = prtDataGenOldFaithful; \n\nmix = prtBrvMixture('components', repmat(prtBrvMvn,5,1), 'vbVerboseText', true, 'vbVerbosePlot', true, 'vbConvergenceThreshold', 1e-11);\n\n[mixLearned, training] = mix.vbBatch(ds);\n\n%% DP Mixture\nclear classes\nds = prtDataGenOldFaithful;\n\nmix = prtBrvDpMixture('components',repmat(prtBrvMvn,15,1), 'vbVerboseText',true, 'vbVerbosePlot', true, 'vbConvergenceThreshold',1e-10);\n[mixLearned, training] = mix.vbBatch(ds);\n\n%% Online Dirichlet Mixture\n\nclear classes\n%ds = prtDataGenOldFaithful;\nds = prtDataGenBimodal(5000);\n\nmix = prtBrvMixture('components',repmat(prtBrvMvn,25,1),'vbOnlineLearningRateFunctionHandle',@(t)(32 + t).^(-0.6),'vbVerbosePlot',true,'vbOnlineBatchSize',25,'vbOnlineFullDataSetSize',ds.nObservations);\nmixLearned = mix.vbOnline(ds.X);\n\n\n%% Online DP Mixture\n\nclear classes\nds = prtDataGenOldFaithful;\n%ds = prtDataGenBimodal(5000);\n\nmix = prtBrvDpMixture('components',repmat(prtBrvMvn,50,1),'vbOnlineLearningRateFunctionHandle',@(t)(32 + t).^(-0.8),'vbVerbosePlot',true,'vbOnlineBatchSize',25,'vbOnlineFullDataSetSize',ds.nObservations);\nmixLearned = mix.vbOnline(ds.X);\n\n%%\n\n\n\n\n\n%% MCMC Dirichlet\nclear classes\n%ds = prtDataGenOldFaithful; \nds = prtDataGenBimodal;\n\nmix = prtBrvMixture('components', repmat(prtBrvMvn,5,1), 'mcmcVerboseText', false, 'mcmcVerbosePlot', 100, 'mcmcTotalIterations', 5000);\n\n[mixLearned, training] = mix.mcmc(ds);\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/]beta/brv/prtBrvMixtureExample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6949886510223915}} {"text": "function obj = setRotationMatrix(obj,r)\n % set the rotation matrix (R) of the frame w.r.t to the\n % reference frame\n %\n % Parameters:\n % r: the rotation matrix or Euler angles (in radian) @type\n % rowvec|matrix\n \n if isvector(r) && length(r) == 3\n % rpy = rad2deg(r);\n obj.R = rotz(r(3)) * roty(r(2)) * rotx(r(1));\n elseif all(size(r)==[3,3])\n if isnumeric(r)\n assert(abs(det(r))-1 <= 1e-6,...\n 'The determinant of the rotation matrix must equal 1.');\n end\n obj.R = r;\n end\n % remove small numbers generated from the rotation matrix\n if isnumeric(r)\n obj.R = roundn(obj.R,-6);\n end\n % update the homogeneous transformation matrix\n obj.computeHomogeneousTransform();\nend\n\nfunction R = rotx(alpha)\n%rotz rotate around X by ALPHA\n%\n%\tR = rotx(alpha)\n%\n% See also: roty, rotz\n% Author: Jake Reher: jreher@caltech.edu\n\nR = [1 0 0; ...\n 0 cos(alpha) -sin(alpha); ...\n 0 sin(alpha) cos(alpha)];\n \nend\n\nfunction R = roty(alpha)\n%roty rotate around Y by ALPHA\n%\n%\tR = roty(alpha)\n%\n% See also: rotx, rotz\n% Author: Jake Reher: jreher@caltech.edu\n\nR = [cos(alpha) 0 sin(alpha); ...\n 0 1 0; ...\n -sin(alpha) 0 cos(alpha)];\n \nend\n\nfunction R = rotz(alpha)\n%rotz rotate around Z by ALPHA\n%\n%\tR = rotz(alpha)\n%\n% See also: ROTX, ROTY, ROT, POS.\n% Author: Jake Reher: jreher@caltech.edus\n\nR = [cos(alpha) -sin(alpha) 0; ...\n sin(alpha) cos(alpha) 0; ...\n 0 0 1];\n\nend", "meta": {"author": "ayonga", "repo": "frost-dev", "sha": "e5dc0624d834520872bfa588dd3eda5643da71de", "save_path": "github-repos/MATLAB/ayonga-frost-dev", "path": "github-repos/MATLAB/ayonga-frost-dev/frost-dev-e5dc0624d834520872bfa588dd3eda5643da71de/matlab/robotics/@CoordinateFrame/setRotationMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6949886335492325}} {"text": "function [pos, tri] = mesh_tetrahedron\n\n% MESH_TETRAHEDRON returns the vertices and triangles of a tetrahedron.\n%\n% Use as\n% [pos, tri] = mesh_tetrahedron;\n%\n% See also MESH_ICOSAHEDRON, MESH_OCTAHEDRON, MESH_SPHERE\n\n% Copyright (C) 2018-2019, Robert Oostenveld and Jan-Mathijs Schoffelen\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip 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% FieldTrip 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 FieldTrip. If not, see .\n\nv1 = [ 0, 0, 1 ];\nv2 = [ sqrt(8/9), 0, -1/3 ];\nv3 = [ -sqrt(2/9), sqrt(2/3), -1/3 ];\nv4 = [ -sqrt(2/9), -sqrt(2/3), -1/3 ];\n\npos = [\n v1\n v2\n v3\n v4\n ];\n\ntri = [\n 1 2 3\n 1 3 4\n 1 4 2\n 2 4 3\n ];\n\n % scale all vertices to the unit sphere\n pos = pos ./ repmat(sqrt(sum(pos.^2,2)), 1,3);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/utilities/private/mesh_tetrahedron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.694925319255515}} {"text": "function p = sigmoid(x)\n% Sigmoid function: s(x) = 1 / (1+exp(-x))\n\n% This file is from pmtk3.googlecode.com\n\np = 1./(1+exp(-x));\nend\n", "meta": {"author": "emtiyaz", "repo": "vadam", "sha": "d8ea6bdc82ac8765b873578660e1d9ba95c701d4", "save_path": "github-repos/MATLAB/emtiyaz-vadam", "path": "github-repos/MATLAB/emtiyaz-vadam/vadam-d8ea6bdc82ac8765b873578660e1d9ba95c701d4/matlab/lib/utils/sigmoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6949253131409946}} {"text": "function [repairedData, coefficients, grossErrors] = repair_corrupted_data(dictionary, corruptedData)\n% repair_missing_data.m\n%\n% Given a set of complete data vectors, and another set of vectors with\n% missing entries, use L1-minimization to repair the incomplete vectors.\n% This function required the CVX package for semidefinite programming.\n%\n%\n% Inputs:\n% dictionary - a matrix whose columns are data vectors that are\n% used as overcomplete basis to represent other\n% vectors. note that some or all of these columns\n% may contain gross errors.\n% corruptedData - a matrix whose columns are data vectors with\n% some elements that may have gross errors. these\n% vectors will be repaired using the dictionary.\n%\n% Outputs:\n% repairedData - a matrix whose columns are repaired versions of\n% the given incomplete data vectors\n% coefficients - a matrix whose ith column is a list of\n% coefficients used to represent the ith vector in\n% in corrupted data as a linear combination of\n% vectors in the dictionary\n% grossErrors - a matrix whose ij-th entry is true if the ij-th\n% entry of corruptedData was corrupted by gross\n% errors.\n% Dependencies:\n% CVX package\n%\n% Nov. '07 Shankar Rao -- srrao@uiuc.edu\n\n% Copyright 2007, University of Illinois. All rights reserved.\n\nVERBOSE = false;\nGROSS_ERROR_THRESHOLD = 0.5;\n\n[dimensionCount, sampleCount] = size(dictionary);\ncorruptedSampleCount = size(corruptedData,2);\n\n\nrepairedData = corruptedData;\ngrossErrors = false(size(corruptedData));\ncoefficients = zeros(sampleCount+dimensionCount, corruptedSampleCount);\nnormalizedData = dictionary ./ repmat(sqrt(sum(dictionary.^2, 1)), dimensionCount, 1);\nI = eye(dimensionCount);\nX = [ normalizedData I];\nfor sampleIndex = 1:corruptedSampleCount\n y = corruptedData(:, sampleIndex);\n\n if VERBOSE,\n disp(sprintf('Repairing sample %d of %d', sampleIndex, corruptedSampleCount));\n end\n\n state = cvx_quiet(true);\n cvx_begin\n variable c(sampleCount+dimensionCount);\n minimize(norm(c,1));\n subject to\n X * c == y;\n cvx_end\n cvx_quiet(state);\n\n yhat = X(:, 1:sampleCount)*c(1:sampleCount);\n coefficients(:, sampleIndex) = c;\n errors = c(sampleCount+1:end);\n grossErrors(:, sampleIndex) = abs(errors) > GROSS_ERROR_THRESHOLD;\n repairedData(grossErrors(:, sampleIndex), sampleIndex) = yhat(grossErrors(:, sampleIndex));\nend\n", "meta": {"author": "SuTanTank", "repo": "VideoStitchingViaShakinessRemoving", "sha": "701145c6d319d9dd54b534c8f3498aaeabe9f269", "save_path": "github-repos/MATLAB/SuTanTank-VideoStitchingViaShakinessRemoving", "path": "github-repos/MATLAB/SuTanTank-VideoStitchingViaShakinessRemoving/VideoStitchingViaShakinessRemoving-701145c6d319d9dd54b534c8f3498aaeabe9f269/Stitching-1.1.0/tracks/helpers/repair_corrupted_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.6949253095966449}} {"text": "function [f] = spm_mc_fx_3(x,v,P)\n% equations of motion for the mountain car problem using basis functions\n% problem\n% FORMAT [f] = spm_mc_fx_3(x,v,P)\n%\n% x - hidden states\n% v - exogenous inputs\n% P.p - parameters for gradient function: G(x(1),P.p)\n% P.q - parameters for cost or loss-function: C(x(1),P.q)\n%\n% returns f = dx/dt = f = [x(2);\n% G - x(2)*C]*dt;\n%\n% where C determines divergence of flow x(2) at any position x(1).\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_mc_fx_3.m 3333 2009-08-25 16:12:44Z karl $\n \n \n% gradient (G)\n%--------------------------------------------------------------------------\nG = spm_DEM_basis(x.x(1),v,P.p);\n \n% cost function (C)\n%--------------------------------------------------------------------------\nC = spm_DEM_basis(x.x(1),v,P.q);\n \n% flow\n%--------------------------------------------------------------------------\ndt = 1/8;\nf.x = [x.x(2); G - x.x(2)*x.c]*dt;\nf.c = [-C - x.c]*dt;\n \n \n% true scalar potential gradient (see spm_moutaincar_fx)\n%--------------------------------------------------------------------------\n% if x(1) < 0\n% G = 2*x(1) + 1;\n% else\n% xx = x(1)^2;\n% G = (1 + 5*xx)^(-1/2) - 5*xx/(1 + 5*xx)^(3/2) + (x(1)/2)^4;\n% end", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/spm_mc_fx_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6949150941862348}} {"text": "function h = p08_h ( n, x )\n\n%*****************************************************************************80\n%\n%% P08_H evaluates the Hessian for problem 8.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 October 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the values of the variables.\n%\n% Output, real H(N,N), the N by N Hessian matrix.\n%\n ap = 0.00001;\n\n t1 = - 0.25 + sum ( x(1:n).^2 );\n\n d1 = 2.0 * ap;\n th = 4.0 * t1;\n\n for i = 1 : n\n h(i,i) = d1 + th + 8.0 * x(i)^2;\n for j = 1 : i - 1\n h(i,j) = 8.0 * x(i) * x(j);\n end\n end\n\n for i = 1 : n\n for j = i + 1 : n\n h(i,j) = h(j,i);\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_opt/p08_h.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.6949147325037214}} {"text": "function FPDF = TabulatedPDF (x, p)\n% Return function handles to routines to calculate the area, mean, and\n% second moment of a unit-variance, zero-mean, uniform probability\n% density function.\n% b\n% Farea(a,b) = Int p(x) dx\n% a\n% b\n% Fmean(a,b) = Int x p(x) dx\n% a\n% b\n% Fvar(a,b) = Int x^2 p(x) dx\n% a\n% where p(x) is a tabulated function. The PDF is assumed to be zero outside\n% of the limits, and defined by linear interpolation between points. The\n% tabulated function need not be initially normalized to unit area.\n%\n% x - Abscissa values (in increasing order)\n% p - Vector of probability values at the corresponding abscissa values.\n% The PDF is assumed to be zero outside of [x(1), x(end)] and to be\n% linearly interpolated between abscissa points.\n\n% global xpdf pdf\n\n% Test for increasing x\nif (any(diff(x) < 0))\n error('TabulatedPDF - Non-increasing abscissa values');\nend\nif (any(p < 0))\n error('TabulatedPDF - Negative probability value');\nend\nif (length(x) ~= length(p) || length(x) <= 1)\n error('TabulatedPDF - Invalid table length');\nend\n\n% Normalize the tabulated data\nxpdf = x;\npdf = p;\nA = Tarea(-Inf, Inf);\npdf = pdf / A;\n\nFPDF = {@Tarea, @Tmean, @Tvar};\n\nreturn\n\n%----- ----- begin nested functions\nfunction v = Tarea (a, b)\n\n% global xpdf pdf\n\nv = TabulatedPDFInt(@TLarea, a, b, xpdf, pdf);\n\nreturn\nend\n\n% ----- ------\nfunction v = Tmean (a, b)\n\n% global xpdf pdf\n\nv = TabulatedPDFInt(@TLmean, a, b, xpdf, pdf);\n\nreturn\nend\n\n% ----- ------\nfunction v = Tvar (a, b)\n\n% global xpdf pdf\n\nv = TabulatedPDFInt(@TLvar, a, b, xpdf, pdf);\n\nreturn\nend\n\n% ----- -----\nfunction v = TabulatedPDFInt (Fn, a, b, x, p)\n% The abscissa values are assumed to be in increasing order\n\n% Limit the evaluation interval and flip the limits if a > b\nbr = min(x(end), max(a, b));\nar = max(x(1), min(a, b));\n\nif (br <= ar)\n v = 0;\n return\nend\n\n% Search for the intervals included in the integral\niL = max(find(x <= ar));\niU = min(find(x >= br));\nif (iL == iU)\n error('TabulatedPDFInt - iL == iU');\nend\nx = x(iL:iU); % Keep only intervals of interest\np = p(iL:iU);\n\n% Lop off the end intervals\np(1) = Alin(ar, x(1:2), p(1:2));\nx(1) = ar;\np(end) = Alin(br, x(end-1:end), p(end-1:end));\nx(end) = br;\n\n% Integrate\nv = feval(Fn, x, p);\n\n% Negate the integral if a > b\nif (a > b)\n v = -v;\nend\n\nreturn\nend\n\n% ----- -----\nfunction v = TLarea (x, p)\n\nxl = x(1:end-1);\nxu = x(2:end);\npl = p(1:end-1);\npu = p(2:end);\n% syms p pl pu xl xu x\n% p = pl+(x-xl)*(pu-pl)/(xu-xl)\n% factor(int(p,xl,xu)\n% ans = -1/2*(pl+pu)*(-xu+xl)\nA = (xu-xl) .* (pl+pu);\n\nv = 0.5 * sum(A);\n\nreturn\nend\n\n% ----- ------\nfunction v = TLmean (x, p)\n\nxl = x(1:end-1);\nxu = x(2:end);\npl = p(1:end-1);\npu = p(2:end);\n% syms p pl pu xl xu x\n% p = pl+(x-xl)*(pu-pl)/(xu-xl)\n% factor(int(x*p,xl,xu)\n% ans = -1/6*(-xu+xl)*(2*pl*xl+pu*xl+pl*xu+2*pu*xu)\nA = (xu-xl) .* ((xl+xu) .* (pl+pu) + pl.*xl + pu.*xu);\n\nv = sum(A) / 6;\n\nreturn\nend\n\n% ----- -----\nfunction v = TLvar (x, p)\n\nxl = x(1:end-1);\nxu = x(2:end);\npl = p(1:end-1);\npu = p(2:end);\n% syms p pl pu xl xu x\n% p = pl+(x-xl)*(pu-pl)/(xu-xl)\n% factor(int(x^2*p,xl,xu)\n% ans = -1/12*(-xu+xl)\n% *(3*pl*xl^2+pu*xl^2+2*xl*pu*xu+2*pl*xu*xl+pl*xu^2+3*pu*xu^2)\nA = (xu-xl) .* ((pu+pl) .* (xu+xl).^2 + 2*(pu.*xu.^2 + pl.*xl.^2));\n\nv = sum(A) / 12;\n\nreturn\nend\n\n% ----- -----\nfunction pa = Alin(a, x, p)\n\nslope = (p(2) - p(1)) / (x(2) - x(1));\npa = (a - x(1)) * slope + p(1);\n\nreturn\nend\n\n% ---- end of the nested functions\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/24333-quantizers/Quantizer/private/TabulatedPDF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6948992242003124}} {"text": "function [inpC,p] = regCorrContrast(inp,Limit,pinit);\n% regCorrContrast - removes mean and normalizes by the standard deviation, \n% both estimated by minimizing a robust error measure \n% between the sampled histogram and a mixture of 2 gaussians.\n%\n% [inpC,p] = regCorrContrast(inp, );\n%\n% INPUT:\n% - inp: set of original inplanes\n% - pinit: initial parameters of the two best fitting Gaussians (optional)\n% (pinit = [mu1 sigma1^2 mu2 sigma2^2 p1 p2])\n%\n% Oscar Nestares - 5/99\n%\n\nif nargin<2\n Limit = 2;\nend\n\n% building the histogram\nII = find(~isnan(inp));\n[h x] = regHistogram(double(inp(II)), 256);\n\n% normalizing the histogram\nh = h/(sum(h)*mean(diff(x)));\n\n% initial parameters: if they are not specified, chosoe the first\n% gaussian with the actual mean and variance, and the second gaussian\n% around 1 and with 1/10 of the actual variance, both with weights of 0.5 \nif nargin<3\n pinit = [mean(inp(II)) var(inp(II)) 1 var(inp(II))/10 0.5 0.5];\nend\n\n% minimizing the robust measure of the error\n%p=fmins('regErrGaussRob', pinit, [], [], x, h);\np = fminsearch('regErrGaussRob', double(pinit), [], x, h);\n\n% selecting the mean closer to 1\nif abs(p(1)-1)>abs(p(3)-1)\n mu = p(3); sigma2 = p(4);\nelse\n mu = p(1); sigma2 = p(2);\nend\n\n% renormalizing\ninpC = (inp - mu)/sqrt(sigma2);\n\n% saturating for low and high values\n%Limit = 4; %%% This is a reasonable value, 2*std (now std=1)\nLow = inpC < -Limit;\nHigh = inpC > Limit;\ninpC = inpC .*((~Low) & (~High)) + (-Limit)*Low + Limit*High;\n\nreturn\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAlign/registrationOscar/regCorrContrast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.694705713851144}} {"text": "function [s,time] = modulation(x,Ts,Nos,Fc)\n% Ts : Sampling period\n% Nos: Oversampling factor\n% Fc : Carrier frequency\nNx=length(x); offset = 0; \nif nargin<5\n scale = 1; \n T=Ts/Nos; % Scale and Oversampling period for Baseband\nelse\n scale = sqrt(2);\n T=1/Fc/2/Nos; % Scale and Oversampling period for Passband\nend\nt_Ts = [0:T:Ts-T]; \ntime = [0:T:Nx*Ts-T]; % One sampling interval and whole interval\ntmp = 2*pi*Fc*t_Ts+offset; \nlen_Ts=length(t_Ts); \ncos_wct = cos(tmp)*scale; \nsin_wct = sin(tmp)*scale;\n%s = zeros(N*len_Ts,1);\nfor n = 1:Nx\n s((n-1)*len_Ts+1:n*len_Ts) = real(x(n))*cos_wct-imag(x(n))*sin_wct;\nend", "meta": {"author": "LyricYang", "repo": "MIMO_OFDM", "sha": "df25e1837bc4019f2bbcd946bc49b0942827a847", "save_path": "github-repos/MATLAB/LyricYang-MIMO_OFDM", "path": "github-repos/MATLAB/LyricYang-MIMO_OFDM/MIMO_OFDM-df25e1837bc4019f2bbcd946bc49b0942827a847/\u7b2c7\u7ae0 PAPR/\u5355\u8f7d\u6ce2\u4fe1\u53f7\u7684PAPR/modulation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103777, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6946992329153622}} {"text": "function test_issue1985\n\n% WALLTIME 00:10:00\n% MEM 2gb\n\n% DEPENDENCY filter_with_correction fir_filterdcpadded\n\nnchan = 1;\nfsample = 1000;\nnsample = 2*fsample;\n\ndat = zeros(nchan, nsample);\ndat(1,fsample) = 1;\n\n%%\n\nfhp = 0.3;\nflp = 30;\nfbp = [fhp flp];\n\norder = 30;\ntype = 'firws';\n\n% use defaulls where possible\nfilt1 = ft_preproc_bandpassfilter(dat, fsample, fbp, order, type, 'onepass-zerophase');\nfilt2 = ft_preproc_bandpassfilter(dat, fsample, fbp, order, type, 'onepass-reverse-zerophase');\nfilt3 = ft_preproc_bandpassfilter(dat, fsample, fbp, order, type, 'onepass-minphase');\n\n\n%%\n\nfigure; hold on\nplot(dat * 0.1)\nplot(filt1+0.01)\nplot(filt2+0.02)\nplot(filt3+0.03)\nlegend", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_issue1985.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6946992266205889}} {"text": "function [y,yz,yzi] = autoGen_cst_swingFootHeight(q1,q2,q4,q5,l1,l2,l4,l5,stepLength,stepHeight)\n%AUTOGEN_CST_SWINGFOOTHEIGHT\n% [Y,YZ,YZI] = AUTOGEN_CST_SWINGFOOTHEIGHT(Q1,Q2,Q4,Q5,L1,L2,L4,L5,STEPLENGTH,STEPHEIGHT)\n\n% This function was generated by the Symbolic Math Toolbox version 6.3.\n% 25-Oct-2015 18:36:31\n\nt3 = sin(q1);\nt4 = l1.*t3;\nt7 = sin(q2);\nt8 = l2.*t7;\nt9 = sin(q4);\nt10 = l4.*t9;\nt11 = sin(q5);\nt12 = l5.*t11;\nt2 = t4+t8-t10-t12;\nt5 = 1.0./stepLength.^2;\nt6 = cos(q1);\nt13 = cos(q2);\nt14 = cos(q4);\nt15 = cos(q5);\ny = -l1.*t6-l2.*t13+l4.*t14+l5.*t15-stepHeight.*(t2.^2.*t5-1.0);\nif nargout > 1\n yz = [t4-l1.*stepHeight.*t2.*t5.*t6.*2.0;t8-l2.*stepHeight.*t2.*t5.*t13.*2.0;-t10+l4.*stepHeight.*t2.*t5.*t14.*2.0;-t12+l5.*stepHeight.*t2.*t5.*t15.*2.0];\nend\nif nargout > 2\n yzi = [2.0;3.0;5.0;6.0];\nend\n", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/demo/fiveLinkBiped/costOfTransport/autoGen_cst_swingFootHeight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6946992254543474}} {"text": "function filters = make_filters(radii, gtheta)\n\nd = 2; \n\nfilters = cell(numel(radii), numel(gtheta));\nfor r = 1:numel(radii),\n for t = 1:numel(gtheta),\n \n ra = radii(r);\n rb = ra / 4;\n theta = gtheta(t);\n \n ra = max(1.5, ra);\n rb = max(1.5, rb);\n ira2 = 1 / ra^2;\n irb2 = 1 / rb^2;\n wr = floor(max(ra, rb));\n wd = 2*wr+1;\n sint = sin(theta);\n cost = cos(theta);\n \n % 1. compute linear filters for coefficients\n % (a) compute inverse of least-squares problem matrix\n filt = zeros(wd,wd,d+1);\n xx = zeros(2*d+1,1);\n for u = -wr:wr,\n for v = -wr:wr,\n ai = -u*sint + v*cost; % distance along major axis\n bi = u*cost + v*sint; % distance along minor axis\n if ai*ai*ira2 + bi*bi*irb2 > 1, continue; end % outside support\n xx = xx + cumprod([1;ai+zeros(2*d,1)]);\n end\n end\n A = zeros(d+1,d+1);\n for i = 1:d+1,\n A(:,i) = xx(i:i+d);\n end\n \n % (b) solve least-squares problem for delta function at each pixel\n for u = -wr:wr,\n for v = -wr:wr,\n ai = -u*sint + v*cost; % distance along major axis\n bi = u*cost + v*sint; % distance along minor axis\n if (ai*ai*ira2 + bi*bi*irb2) > 1, continue; end % outside support\n yy = cumprod([1;ai+zeros(d,1)]);\n filt(v+wr+1,u+wr+1,:) = A\\yy;\n end\n end\n\t\t \n filters{r,t}=filt;\n end\nend\n", "meta": {"author": "s-gupta", "repo": "rcnn-depth", "sha": "7a7baf7dcccc6fdf6be7c13d16828064d89dff4e", "save_path": "github-repos/MATLAB/s-gupta-rcnn-depth", "path": "github-repos/MATLAB/s-gupta-rcnn-depth/rcnn-depth-7a7baf7dcccc6fdf6be7c13d16828064d89dff4e/structured-edges/ng/make_filters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6946759851770928}} {"text": "function [s,d,S_k,S_si] = pinHoleSegment(k,si)\n\n% PINHOLESEGMENT Pin hole projection of a segment.\n% [S,D] = PINHOLESEGMENT(K,SI) projects into a pinhole camera with\n% intrinsic aprameters K the segment SI. It returns the projected segment\n% S and the non-observable depths D of the two endpoints.\n%\n% SI is a 6-vector containing the two endpoints of the 3D segment.\n% S is a 4-vector conteining the two endpoints of the 2D segment.\n%\n% SI can also be a 6-by-N matrix with N segments. In such case S is a\n% 4-by-N matrix with N projected segments.\n%\n% [S,D,S_k,S_si] = POINHOLESEGMENT(...) returns the Jacobians of S wrt K\n% and SI. It only works for single segments.\n%\n% See also PINHOLE.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\np1 = si(1:3,:);\np2 = si(4:6,:);\n\nif nargout <= 2\n\n [e1,d1] = pinHole(p1,k);\n [e2,d2] = pinHole(p2,k);\n s = [e1;e2];\n d = [d1;d2];\n\nelse % Jacobians\n\n if size(si,2) == 1\n\n [e1,d1,E1_p1,E1_k] = pinHole(p1,k);\n [e2,d2,E2_p2,E2_k] = pinHole(p2,k);\n s = [e1;e2];\n d = [d1;d2];\n\n S_k = [...\n E1_k\n E2_k];\n\n Z23 = zeros(2,3);\n\n S_si = [...\n E1_p1 Z23\n Z23 E2_p2];\n\n else\n\n error('Jacobians not available for multiple segments.')\n\n end\n\nend\n\nreturn\n\n%% test\nsyms p1 p2 p3 q1 q2 q3 u0 v0 au av real\nk = [u0;v0;au;av];\nsi = [p1;p2;p3;q1;q2;q3];\n\n[s,d,S_k,S_si] = pinHoleSegment(k,si);\n\nsimplify(S_k - jacobian(s,k))\nsimplify(S_si - jacobian(s,si))\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/Observations/pinHoleSegment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.694666092535052}} {"text": "function value = p20_exact ( dim_num )\n\n%*****************************************************************************80\n%\n%% P20_EXACT returns the exact integral for problem 20.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 June 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Output, real VALUE, the exact value of the integral.\n%\n aval = 0.0;\n aval = p20_r8 ( 'G', 'A', aval );\n\n bval = 0.0;\n bval = p20_r8 ( 'G', 'B', bval );\n\n p = 0.0;\n p = p20_r8 ( 'G', 'P', p );\n\n value = 0.0;\n exponent = dim_num + p;\n\n minus_one = -1.0;\n for i = 0 : dim_num\n minus_one = - minus_one;\n value = value + minus_one * r8_choose ( dim_num, i ) ...\n * ( ( dim_num - i ) * bval + i * aval )^exponent;\n end\n\n for i = 1 : dim_num\n value = value / ( p + i );\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/quadrature_test/p20_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.859663743319094, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.694666087642958}} {"text": "function value = r4_li ( x )\n\n%*****************************************************************************80\n%\n%% R4_LI evaluates the logarithmic integral for an R4 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the logarithmic integral evaluated at X.\n%\n persistent sqeps\n\n if ( isempty ( sqeps ) )\n sqeps = sqrt ( r4_mach ( 3 ) );\n end\n\n if ( x < 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_LI - Fatal error!\\n' );\n fprintf ( 1, ' Function undefined for X <= 0.\\n' );\n error ( 'R4_LI - Fatal error!' )\n end\n\n if ( x == 0.0 )\n value = 0.0;\n return\n end\n\n if ( x == 1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_LI - Fatal error!\\n' );\n fprintf ( 1, ' Function undefined for X = 1.\\n' );\n error ( 'R4_LI - Fatal error!' )\n end\n\n if ( abs ( 1.0 - x ) < sqeps )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_LI - Warning!\\n' );\n fprintf ( 1, ' Answer less than half precision.\\n' );\n fprintf ( 1, ' X is too close to 1.\\n' );\n end\n\n value = r4_ei ( log ( x ) );\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/fn/r4_li.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.6946660874933465}} {"text": "function [x,m,e] = RunningAverage(X,Y,varargin)\n\n%RunningAverage - Compute running linear or angular average.\n%\n% Computes the running average of y=f(x). Variable y can be linear or circular\n% (use radians). The error bars are standard errors of the mean for linear\n% data, or 95% confidence intervals for circular data.\n%\n% USAGE\n%\n% [x,m,e] = RunningAverage(x,y,)\n%\n% x x variable (e.g., time)\n% y values at x\n% optional list of property-value pairs (see table below)\n%\n% =========================================================================\n% Properties Values\n% -------------------------------------------------------------------------\n% 'window' averaging window size (default (max-min)/10)\n% 'overlap' overlap between successive windows (default = 0.8*window)\n% 'limits' x limits to use instead of min and max\n% 'type' either 'linear' or 'circular' (default 'linear')\n% =========================================================================\n%\n% OUTPUT\n%\n% x new x variable\n% m running average\n% e sem for linear variables, otherwise 95% confidence intervals\n\n% Copyright (C) 2004-2011 by Micha\u00ebl Zugaro\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% Default values\ntype = 'linear';\nlimits = [min(X) max(X)];\nnBins = 10;\nwindow = 0;\noverlap = [];\n\nif nargin < 2 | mod(length(varargin),2) ~= 0,\n error('Incorrect number of parameters (type ''help RunningAverage'' for details).');\nend\n\n% Parse parameter list\nfor i = 1:2:length(varargin),\n\tif ~ischar(varargin{i}),\n\t\terror(['Parameter ' num2str(i+2) ' is not a property (type ''help RunningAverage'' for details).']);\n\tend\n\tswitch(lower(varargin{i})),\n\t\tcase 'type',\n\t\t\ttype = varargin{i+1};\n\t\t\tif ~isstring_FMAT(type,'linear','circular'),\n\t\t\t\terror('Incorrect value for property ''type'' (type ''help RunningAverage'' for details).');\n\t\t\tend\n\n\t\tcase 'window',\n\t\t\twindow = varargin{i+1};\n\t\t\tif ~isdscalar(window,'>0'),\n\t\t\t\terror('Incorrect value for property ''window'' (type ''help RunningAverage'' for details).');\n\t\t\tend\n\n\t\tcase 'overlap',\n\t\t\toverlap = varargin{i+1};\n\t\t\tif ~isdscalar(overlap,'>=0'),\n\t\t\t\terror('Incorrect value for property ''overlap'' (type ''help RunningAverage'' for details).');\n\t\t\tend\n\n\t\tcase 'limits',\n\t\t\tlimits = varargin{i+1};\n\t\t\tif ~isdvector(limits,'#2','<'),\n\t\t\t\terror('Incorrect value for property ''limits'' (type ''help RunningAverage'' for details).');\n\t\t\tend\n\n\t\totherwise,\n\t\t\terror(['Unknown property ''' num2str(varargin{i}) ''' (type ''help RunningAverage'' for details).']);\n\n\tend\nend\n\nx0 = limits(1);\nx1 = limits(2);\nif window == 0,\n\twindow = (x1-x0)/nBins;\nend\nif isempty(overlap),\n\toverlap = 0.8*window;\nend\n\n% Loop through data\ni = 1;\nxi = x0+window/2;\nwhile xi+window/2 <= x1,\n\tx(i,1) = xi;\n\tok = InIntervals(X,xi+[-0.5 0.5]*window);\n\tif sum(ok) == 0,\n\t\tm(i,1) = NaN;\n\t\te(i,:) = [NaN NaN];\n\telseif strcmp(type,'circular'),\n\t\t[M,C] = CircularConfidenceIntervals(Y(ok));\n\t\tm(i,1) = M;\n\t\te(i,:) = C;\n\telse\n\t\tm(i,1) = nanmean(Y(ok));\n\t\tn = sum(ok);\n\t\ts = nanstd(Y(ok))/sqrt(n);\n\t\te(i,1) = m(i)-s;\n\t\te(i,2) = m(i)+s;\n\tend\n\txi = xi + window - overlap;\n\ti = i + 1;\nend\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/FMAToolbox/General/RunningAverage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.6946660777091584}} {"text": "function [prob,sol,fmin] = qp_prob(varargin)\n%QP_PROB Return an OPTI QP \n%\n% prob = qp_prob(no) return a pre-built optiprob of a saved QP.\n%\n% [prob,sol,fmin] = qp_prob(no) returns the optimum solution and \n% function eval at the optimum\n%\n% no = qp_prob() returns the number of problems available for testing.\n\n% (C) 2011 Jonathan Currie (I2C2)\n\n%Check if just returning no problems\nif(nargin < 1)\n prob = 3; sol = []; fmin = [];\n return;\nelse\n no = varargin{1};\nend \n\n%Big switch yard\nswitch(no)\n case 1 \n H = eye(3);\n f = -[2 3 1]';\n A = [1 1 1;3 -2 -3; 1 -3 2]; \n b = [1;1;1];\n prob = optiprob('H',H,'f',f,'ineq',A,b); \n sol = [1/3;4/3;-2/3];\n fmin = -2.83333333301227;\n \n case 2 \n H = [1 -1; -1 2];\n f = -[2 6]';\n A = [1 1; -1 2; 2 1];\n b = [2; 2; 3]; \n lb = [0;0];\n prob = optiprob('H',H,'f',f,'ineq',A,b,'lb',lb); \n sol = [1/3;4/3];\n fmin = -8.22222220552525;\n \n case 3 \n H = [1 -1; -1 2];\n f = -[2 6]';\n A = [1 1; -1 2; 2 1];\n b = [2; 2; 3];\n Aeq = [1 1.5];\n beq = 2;\n lb = [0;0];\n ub = [10;10];\n prob = optiprob('H',H,'f',f,'ineq',A,b,'eq',Aeq,beq,'bounds',lb,ub); \n sol = [0.34482763667623;1.10344824221585];\n fmin = -6.41379310344827; \n \n otherwise\n error('Problem not available or not implemented yet');\nend", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Test Problems/qp_prob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6945918814698167}} {"text": "function seed = i4_seed_advance ( seed )\n\n%*****************************************************************************80\n%\n%% I4_SEED_ADVANCE \"advances\" the seed.\n%\n% Discussion:\n%\n% This routine implements one step of the recursion\n%\n% SEED = ( 16807 * SEED ) mod ( 2^31 - 1 )\n%\n% This version of the routine does not check whether the input value of\n% SEED is zero. If the input value is zero, the output value will be zero.\n%\n% If we repeatedly use the output of SEED_ADVANCE as the next input,\n% and we start with SEED = 12345, then the first few iterates are:\n%\n% Input Output\n% SEED SEED\n%\n% 12345 207482415\n% 207482415 1790989824\n% 1790989824 2035175616\n% 2035175616 77048696\n% 77048696 24794531\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 April 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Paul Bratley, Bennett Fox, Linus Schrage,\n% A Guide to Simulation,\n% Second Edition,\n% Springer, 1987,\n% ISBN: 0387964673,\n% LC: QA76.9.C65.B73.\n%\n% Bennett Fox,\n% Algorithm 647:\n% Implementation and Relative Efficiency of Quasirandom\n% Sequence Generators,\n% ACM Transactions on Mathematical Software,\n% Volume 12, Number 4, December 1986, pages 362-376.\n%\n% Pierre L'Ecuyer,\n% Random Number Generation,\n% in Handbook of Simulation,\n% edited by Jerry Banks,\n% Wiley, 1998,\n% ISBN: 0471134031,\n% LC: T57.62.H37.\n%\n% Peter Lewis, Allen Goodman, James Miller,\n% A Pseudo-Random Number Generator for the System/360,\n% IBM Systems Journal,\n% Volume 8, Number 2, 1969, pages 136-143.\n%\n% Parameters:\n%\n% Input, integer SEED, the seed value.\n%\n% Output, integer SEED, the \"next\" seed.\n%\n i4_huge = 2147483647;\n\n seed = floor ( seed );\n\n seed = mod ( seed, i4_huge );\n\n if ( seed < 0 )\n seed = seed + i4_huge;\n end\n\n k = floor ( seed / 127773 );\n\n seed = 16807 * ( seed - k * 127773 ) - k * 2836;\n\n if ( seed < 0 )\n seed = seed + i4_huge;\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/uniform/i4_seed_advance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.6945918793284167}} {"text": "%%\n% Comparison of various dual norms (aka integral probability metrics).\n\nSetAR = @(ar)set(gca, 'PlotBoxAspectRatio', [1 ar 1]);\nrep = ['results/dual-norms/'];\n[~,~] = mkdir(rep);\n\n\n% random test\nnormalize = @(x)x/sum(x(:));\nk = @(x,y)-abs(x-y);\nnx = 3; ny = 5;\nx = randn(nx,1);\ny = randn(ny,1);\np = normalize(rand(nx,1));\nq = normalize(rand(ny,1));\nd = rkhs_norm(k,x,p,x,p);\nd = rkhs_norm(k,x,p,y,q);\n\nname = '1dirac-1dirac'; \nname = '1dirac-2dirac';\n\n% delta_0 <-> delta_t\nxmax = 3;\ntlist = linspace(-xmax,xmax,257)';\n\nswitch name\n case '1dirac-1dirac'\n p = 1; q = 1;\n x = @(t)0; \n y = @(t)t;\n case '1dirac-2dirac'\n p = 1; q = [1;1]/2;\n x = @(t)0; \n y = @(t)[-t/2;t/2];\n otherwise\n error('Unknown');\nend\n\nD = []; lgd = {};\n% energy distance\nk = @(x,y)-abs(x-y);\nf = @(t)sqrt( rkhs_norm(k, x(t),p, y(t),q) );\nD(:,end+1) = arrayfun(f,tlist);\nlgd{end+1} = 'Energy';\n% Gaussian RKHS\nsigma = .3;\nk = @(x,y)exp( -(x-y).^2 / (2*sigma^2) );\nf = @(t)sqrt( rkhs_norm(k, x(t),p, y(t),q) );\nD(:,end+1) = arrayfun(f,tlist);\nlgd{end+1} = 'Gauss';\n% W1 distance\nD(:,end+1) = abs(tlist);\nlgd{end+1} = 'W_1';\n% Flat distance\nD(:,end+1) = min(abs(tlist),1);\nlgd{end+1} = 'Flat';\n\n%% display\nclf;\nplot(tlist, D, 'LineWidth', 2); \nlegend(lgd, 'Location', 'NorthWest');\naxis tight;\nSetAR(1/2);\nset(gca, 'FontSize', 20);\nsaveas(gcf, [rep name '.eps'], 'epsc');\n", "meta": {"author": "optimaltransport", "repo": "optimaltransport.github.io", "sha": "2fa6db6e6a48ab9bd6676088db00bd7c5c8b4203", "save_path": "github-repos/MATLAB/optimaltransport-optimaltransport.github.io", "path": "github-repos/MATLAB/optimaltransport-optimaltransport.github.io/optimaltransport.github.io-2fa6db6e6a48ab9bd6676088db00bd7c5c8b4203/_site/code/dual-norms/test_dual_norms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6945918724743512}} {"text": "function cos_power_int_values_test ( )\n\n%*****************************************************************************80\n%\n%% COS_POWER_INT_VALUES_TEST demonstrates the use of COS_POWER_INT_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 January 2015\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'COS_POWER_INT_VALUES_TEST:\\n' );\n fprintf ( 1, ' COS_POWER_INT_VALUES returns values of \\n' );\n fprintf ( 1, ' the N-th power of the cosine function.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A B N FX\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, a, b, n, fx ] = cos_power_int_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %8f %8f %6d %24.16f\\n', a, b, n, fx );\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/test_values/cos_power_int_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.8757869867849166, "lm_q1q2_score": 0.6945918711887186}} {"text": "clear all\n% ===== make testdata =====\n% ti=0;\n% tf=10;\n% dt=.01;\n% t=ti:dt:tf; % second\n% \n% a1=1;\n% f1=5;\n% y1=a1*cos(2*pi*f1*t)*rand(length(t));\n% a2=5;\n% f2=1;\n% y2=a2*sin(2*pi*f2*t);\n% \n% testdata=y1+y2+10;\n\nfilename = 'cmy(finish).wav';\n[data,Fs]=audioread(filename);\n\n% wavplay(y,Fs)\ntestdata=data';\ndt=1/Fs;\nt=0:dt:length(testdata)/Fs-dt;\n\n% ===== decomposition in time domain =====\nst=100; % sifting time; 100-300\n[IMF]=EMD(testdata,st);\n% save('IMF.mat','IMF')\n% load IMF.mat\n \n \n \n% for i=1:10;\n% plot(IMF(i,:));\n% title(['IMF' num2str(i)])\n% pause\n% close all\n% end\n \n \n \n% set(gca,'xtick',[0:100:1000],'xticklabel',0:10);\n% set(gca,'ytick',get(gca,'ytick'),'yticklabel',{'DC term','IMF5','IMF4','IMF3','IMF2','IMF1','test data'});\n% xlabel('Time (second)');\n% pause\n% ===== computation of instantaneous frequency and amplitude =====\n[ipifs,ifs,amp]=imf2ipfa(IMF(1:end-1,:),dt); % the DC term should not be include\n\n% ===== Hilbert spectrum =====\n% x=round([t;t;t;t;t]'*100+1); % xlabel, time\n[L,W]=size(ifs);\n\nx=NaN(L,W);\nfor i=1:W;\n x(:,i)=t';\nend\ny=ifs;\n\nx=x(:);\ny=y(:);\nz=amp(:);\n\n\n% === x-axis (time) ===\ndx=0.01;% time resolution 0.1 second\nxi=0;\nxf=t(end);\n\nT=[xi:dx:0.5];\n\n% === y-axis (frequency) ===\ndy=10;% frequency resolution 100 Hz\nyi=0;\nyf=1500;\nF=yi:dy:yf;\n\nz(y>yf)=[];\nx(y>yf)=[];\ny(y>yf)=[]; % romove the data with frequency > 5000Hz\n\nx=round(x/dx)+1;\ny=round(y/dy)+1; % ylabel, frequency\n\nx(z<0)=[]; % remove the bad data (negative amplitude)\ny(z<0)=[];\nz(z<0)=[];\n\n% pause\n\n% z(y>90)=[];\n% x(y>90)=[];\n% y(y>90)=[]; % romove the data with frequency > 9Hz\n\nm=zeros(length(F),length(T));\nc=m;\nfor i=1:length(z);\n m(y(i),x(i))=m(y(i),x(i))+z(i);\n c(y(i),x(i))=c(y(i),x(i))+1;\nend\n\nhsp=m./c;\n\nclose all\nfigure('position',[300 100 600 600])\naxes('position',[.15 .64 .7 .3])\nplot(t,testdata,'-k');\ntitle('(a) Data');\nset(gca,'fontsize',16)\ngrid on\naxis tight\n\naxes('position',[.15 .12 .7 .4])\npcolor(T,F,hsp);\nshading flat\n%[C,H]=contourf(T,F,hsp);\n%set(H,'levellist',[0:.0001:.3])\ncaxis([0 .02])\ncb=colorbar('position',[.88 .12 .03 .4]);\nset(get(cb,'title'),'string','Amplitude')\nxlabel('Time (second)');\nylabel('Frequency (Hz)');\nylim([0 1500])\ntitle('(b) Hilbert spectrum');\nset(gca,'fontsize',16)\nset(gcf,'paperpositionmode','auto')\nprint -dpng -r300 Fig01\n\n", "meta": {"author": "EZ4BYG", "repo": "Signal_Tools", "sha": "d3525313b179c42a8ad298db1d29746e1911e7d6", "save_path": "github-repos/MATLAB/EZ4BYG-Signal_Tools", "path": "github-repos/MATLAB/EZ4BYG-Signal_Tools/Signal_Tools-d3525313b179c42a8ad298db1d29746e1911e7d6/HHT3/HHT_example_gong.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6945918707628165}} {"text": "% Mathematics Q2876283\n% https://math.stackexchange.com/questions/2876283\n% Least Square with Optimization of Triangular Matrix\n% References:\n% 1. aa\n% Remarks:\n% 1. sa\n% TODO:\n% \t1. ds\n% Release Notes\n% - 1.0.000 12/08/2018\n% * First release.\n\n\n%% General Parameters\n\nsubStreamNumberDefault = 79;\n\nrun('InitScript.m');\n\nfigureIdx = 0; %\n% Contributor: Matt Fig\n% Last update: 07/April/2009\n% 10/Jan/2010: possibility to disable post-sorting step\n\nnout=cell(1,max(1,nargout));\n[nout{:}] = minmaxk(@maxkmex, varargin{:});\nvarargout=nout;\n\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/mc/RPCA-GD/private/maxk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.6944298673541418}} {"text": "function optionValueReturned = optionvalue(SpotPrice, StrikePrice, RiskFreeRate,TimeExpiry, Volatility,theOptionType,ButterflyRange)\n% mcc -d compiled -B 'ccom:BSOptionModel,BSOptionModelClass,1' optionvalue.m webvizroutine.m \n%CALCROUTINE Calculate the value of the option\n\nOptionType = lower(theOptionType);\n\nif (strcmpi(OptionType,'call') == 1) %Call option\n \n %Convert months to expiry to years to expiry\n TimeExpiry = TimeExpiry / 12;\n \n %Calculate the value of the option\n optionValueReturned = blsprice(SpotPrice, StrikePrice, RiskFreeRate, ...\n TimeExpiry, Volatility);\n \n\n \nelseif (strcmpi(OptionType,'put') == 1) %Put option\n \n %Convert months to expiry to years to expiry\n TimeExpiry = TimeExpiry / 12;\n \n %Calculate the value of the put option\n optionValueReturned = blsprice(SpotPrice, StrikePrice, RiskFreeRate, ...\n TimeExpiry, Volatility);\n\nelseif (strcmpi(OptionType,'straddle') == 1) %Straddle option\n \n %Convert months to expiry to years to expiry\n TimeExpiry = TimeExpiry / 12;\n \n %Compute the value of the straddle\n \n optionValueReturned = blsstrval(SpotPrice, StrikePrice, RiskFreeRate, ...\n TimeExpiry, Volatility);\n \nelseif (strcmpi(OptionType,'butterfly') == 1) %Butterfly option\n \n %Convert months to expiry to years to expiry\n TimeExpiry = TimeExpiry / 12;\n \n %Compute the value of the butterfly\n optionValueReturned = blsbtyval(SpotPrice, StrikePrice, RiskFreeRate, ...\n TimeExpiry, Volatility, ButterflyRange);\n \nend\n\n%--------------------------------------------------------------------------\n\nfunction StraddleValue = blsstrval(SpotPrice, StrikePrice, RiskFreeRate, ...\n TimeExpiry, Volatility)\n%BLSSTRVAL Black Scholes value of a straddle option\n\n%Calculate the value of both the call and put option\n[CallValue, PutValue] = blsprice(SpotPrice, StrikePrice, RiskFreeRate, ...\n TimeExpiry, Volatility);\n\n%Compute the value of the straddle\nStraddleValue = CallValue + PutValue;\n\n%end of BLSSTRVAL subroutine\n\nfunction ButterflyValue = blsbtyval(SpotPrice, StrikePrice, RiskFreeRate, ...\n TimeExpiry, Volatility, ButterflyRange)\n%BLSBTYVAL Black Scholes value of a butterfly option\n\n%Set the different strike prices\nLowStrike = StrikePrice .* (1 - ButterflyRange);\nHighStrike = StrikePrice .* (1 + ButterflyRange);\n\n%Value the long positions in the low and high struck calls\nLowValue = blsprice(SpotPrice, LowStrike, RiskFreeRate, ...\n TimeExpiry, Volatility);\nHighValue = blsprice(SpotPrice, HighStrike, RiskFreeRate, ...\n TimeExpiry, Volatility);\n\n%Value the short position in the calls struck at the initial strike\n%price\nShortValue = 2 .* -(blsprice(SpotPrice, StrikePrice, RiskFreeRate, ...\n TimeExpiry, Volatility));\n\n%Calculate the total value of the butterfly\nButterflyValue = LowValue + HighValue + ShortValue;\n\n%end of BLSBTYVAL subroutine\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/12099-black-scholes-option-value-web-application-javatomcat/BlackScholesJava/M-Files/optionvalue.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6944231732296744}} {"text": "clear all; close all; clc;\n\n%%\nL=10; x3=-L:0.1:L; n=length(x3)-1; % define domain\nx2=x3(1:n); k=(2*pi/(2*L))*[0:n/2-1 -n/2:-1]; % k-vector\nye=exp(-(x2.^2)); ye2=exp((x2.^2)/2); % define Gaussians\nfor j=0:9 % loop through 10 modes\n yd=real(ifft(((i*k).^j).*fft(ye))); % 2nd derivative \n mode=((-1)^(j))*(((2^j)*factorial(j)*sqrt(pi))^(-0.5))*ye2.*yd;\n y(:,j+1)=(mode).'; % store modes as columns\nend\n\nx=x2(n/2+1-40:n/2+1+40); % keep only -4-norm(x,1)-(1/2)*mu*norm(x-x0)\n% A must be a linear operator, b must be a vector, and delta and mu\n% must be positive scalars. Initial points x0 and z0 are optional.\n% The standard calling sequence assumes that D=I. To supply a scaling,\n% pass the cell array { A, D } instead of A. D must either be a scalar,\n% a vector of weights, or a linear operator.\n\n% Supply default values\nerror(nargchk(4,8,nargin));\nif nargin < 5, x0 = []; end\nif nargin < 6, z0 = []; end\nif nargin < 7, opts = []; end\n\n% -- legacy options from original software --\nif isfield(opts,'lambda0')\n z0 = opts.lambda0;\n opts = rmfield(opts,'lambda0');\nend\nif isfield(opts,'xPlug')\n x0 = opts.xPlug;\n opts = rmfield(opts,'xPlug');\nend\nif isfield(opts,'solver')\n svr = opts.solver;\n opts = rmfield(opts,'solver');\n if isfield(opts,'alg') && ~isempty(opts.alg)\n disp('Warning: conflictiong options for the algorithm');\n else\n % if specified as \"solver_AT\", truncate:\n s = strfind( svr, '_' );\n if ~isempty(s), svr = svr(s+1:end); end\n opts.alg = svr;\n end\nend\n\n% Extract the linear operators\nD = [];\nif isa( A, 'cell' ),\n if length(A) > 1, D = A{2}; end\n A = A{1};\nend\nif isempty(D),\n D = @(x)x;\nelseif isa( D, 'double' ),\n D = @(x)D.*x;\nend\nif isa( A, 'double' ),\n A = linop_matrix(A);\nend\n\n% Call TFOCS\nobjectiveF = prox_l1;\naffineF = { @(y,mode)linear_DS( D, A, y, mode ), -D(A(b,2)) };\ndualproxF = prox_l1( delta );\n[varargout{1:max(nargout,1)}] = ...\n tfocs_SCD( objectiveF, affineF, dualproxF, mu, x0, z0, opts, varargin{:} );\n\n% Implements x -> D*A'*A*x and its adjoint if A is a linop\nfunction y = linear_DS( D, A, y, mode )\nswitch mode,\ncase 0, \n y = A([],0);\n if iscell( y ),\n y = { y{1}, y{1} };\n else\n y = { [y(2),1], [y(2),1] };\n end\ncase 1, y = D(A(A(y,1),2));\ncase 2, y = A(A(D(y),1),2);\nend\n\n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.\n\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/solver_sDantzig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6943817396544361}} {"text": "function pass = test_nufft( pref )\n\nif ( nargin == 0 ) \n pref = chebfunpref();\nend\n\n% Choose a tolerance:\ntol = eps;\nrng(0)\n\n% Test NUFFT-I \ncount = 1; \nfor N = 10.^(0:4)\n omega = (0:N-1)'; \n omega = omega + 1.2*rand(N,1)/N;\n c = rand(N,1) + 1i*rand(N,1);\n exact = nudft1( c, omega ); \n fast = chebfun.nufft( c, omega, 1 );\n pass(count) = norm( exact - fast, inf ) < 300*N*tol*norm(c,1);\n count = count + 1;\nend\n\n% Test on random inputs: \nN = 50; \nomega = N*randn(1,N);\nc = rand(N,1) + 1i*rand(N,1);\nF = exp(-2*pi*1i*((0:N-1)/N).'*omega);\nf = chebfun.nufft(c, omega.', 1);\npass(count) = ( norm( f - F*c ) < 300*N*tol*norm(c,1) );\ncount = count + 1; \n\n% Test NUFFT-II:\nfor N = 10.^(0:4)\n x = linspace(0,1,N+1)'; x(end) = [];\n x = x + 1.2/N;\n c = rand(N,1) + 1i*rand(N,1);\n exact = nudft2( c, x ); \n fast = chebfun.nufft( c, x );\n pass(count) = norm( exact - fast, inf ) < 300*N*tol*norm(c,1);\n count = count + 1; \nend\n\n% Test on random inputs: \nN = 50; \nx = 100*rand(N,1);\nc = rand(N,1) + 1i*rand(N,1);\nF = exp(-2*pi*1i*x*(0:N-1));\nf = chebfun.nufft(c, x);\npass(count) = ( norm( f - F*c ) < 300*N*tol*norm(c,1) );\ncount = count + 1; \n\n% Test NUFFT-III\nfor N = 10.^(0:4)\n omega = (0:N-1)'; \n omega = omega + 1.2*rand(N,1)/N;\n x = linspace(0,1,N+1)'; x(end) = [];\n x = x + 1.2/N;\n c = rand(N,1) + 1i*rand(N,1);\n exact = nudft3( c, x, omega ); \n fast = chebfun.nufft( c, x, omega, 3 );\n pass(count) = norm( exact - fast, inf ) < 10000*N*tol*norm(c,1);\n count = count + 1;\nend\n\n% Test NUFFT-II on nonsquare inputs: \nn = 101; \nm = 3; \nx = linspace(0,1,m+1)'; x(end) = [];\nx = x + 1.01/m;\nc = rand(n,1); \nexact = nudft2( c, x );\nfast = chebfun.nufft( c, x );\npass(count) = norm( exact - fast, inf ) < 100*tol*norm(c,1);\ncount = count + 1;\n\nend\n\nfunction f = nudft1( c, omega) \n\nf = zeros(size(omega,1),1);\nfor j = 1:numel(f)\n f(j) = exp(-2*pi*1i*(j-1)/size(omega,1)*omega.')*c;\nend\nend\n\nfunction f = nudft2( c, x) \n\nf = zeros(size(x,1),1);\nomega = 0:size(c,1)-1;\nfor j = 1:numel(f)\n f(j) = exp(-2*pi*1i*x(j)*omega)*c;\nend\nend\n\nfunction f = nudft3( c, x, omega) \n\nf = zeros(size(omega,1),1);\nfor j = 1:numel(f)\n f(j) = exp(-2*pi*1i*x(j)*omega.')*c;\nend\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/misc/test_nufft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7826624688140728, "lm_q1q2_score": 0.6943817376618172}} {"text": "function f = changeMap(f, newdom)\n%CHANGEMAP Map the domain of a DELTAFUN via a linear change of variable.\n% G = MAP(F,NEWDOM), where the DELTAFUN F has a domain [a, b], returns a\n% DELTAFUN G defined on [c, d], where c = NEWDOM(1), d = NEWDOM(2), such that\n% G(x) = F(a*(d - x)/(d - c) + b*(x - c)/(d - c)) for all x in [c, d].\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\n% Store the old mapping:\noldMapping = f.funPart.mapping;\n\n% Map the funPart:\nf.funPart = changeMap(f.funPart, newdom);\n\n% Grab the new mapping:\nnewMapping = f.funPart.mapping;\n\n% Map the deltaLocs:\nf.deltaLoc = newMapping.For(oldMapping.Inv(f.deltaLoc));\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/@deltafun/changeMap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6943817373202265}} {"text": "function c = ultra2ultra(c, lam_in, lam_out)\n%ULTRA2ULTRA Convert between Ultraspherical (US) expansions.\n% C_OUT = ULTRA2ULTRA(C_IN, LAM_IN, LAM_OUT) converts the vector C_IN of\n% US-LAM_IN coefficients to a vector of US-LAM_OUT coefficients.\n%\n% This code is essentially a wrapper for the JAC2JAC code based on [1].\n%\n% References:\n% [1] A. Townsend, M. Webb, and S. Olver, \"Fast polynomial transforms\n% based on Toeplitz and Hankel matrices\", submitted, 2016.\n%\n% See also JAC2JAC.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nn = length(c) - 1;\n\n% Scale input from US to Jacobi basis:\nc = c./scl(lam_in, n);\n% Call JAC2JAC:\nc = jac2jac(c, lam_in-.5, lam_in-.5, lam_out-.5, lam_out-.5);\n% Scale output from Jacobi to US:\nc = c.*scl(lam_out, n);\n\nend\n\nfunction s = scl(lam, n)\n% Scaling from Jacobi to US polynomials. See DLMF Table 18.3.1.\n if ( lam == 0 )\n nn = (0:n-1).';\n s = [1 ; cumprod((nn+.5)./(nn+1))];\n else\n nn = (0:n).';\n s = ( gamma(2*lam) ./ gamma(lam+.5) ) * ...\n exp( gammaln(lam+.5+nn) - gammaln(2*lam+nn) );\n end\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/ultra2ultra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6943692773120912}} {"text": "% Diagram of van Albada limiter\n\n% Theory in Section 10.8 of:\n\n% \tP. Wesseling: Principles of Computational Fluid Dynamics\n% \tSpringer, Heidelberg, 2000 ISBN 3-5453-0. XII, 642 pp.\n% See http://ta.twi.tudelft.nl/nw/users/wesseling/cfdbook.html\n\n% This program makes Fig. 10.27 in the book\n\nfigure(1), clf, hold on\n\nx = 0.0:0.01:4.0; y = (x.*x + x)./(1 + x.*x);\t% Graph of van Albada limiter\nplot(x,y)\n\nx = 0.0:0.01:1.1; y = 0.5*(1+sqrt(2))*x; plot(x,y)\nx = 0.0:0.01:4.0; y = 0.5*(1+sqrt(2))*ones(size(x)); plot(x,y)\ny = ones(size(x)); plot(x,y)\nx = 0.0:0.01:1.3; plot(x,x)\ny = 0.0:0.01:1; x = ones(size(y)); plot(x,y,'--')\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/cfdbook/chap10.8/albada.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.694369276926401}} {"text": "function regression_table(y,X,names,varargin)\n%regression_table(y,X,names,[do figures],[do robust])\n%\n% performs regression using the regress command, and prints an output table\n% X should not have an intercept\n%\n% Tor Wager\n\ndofigs = 1; dorobust = 0;\nif length(varargin) > 0, dofigs = varargin{1}; end\nif length(varargin) > 1, dorobust = varargin{2}; end\n\n[n, k] = size(X);\n\nif dorobust\n [b,stat]=robustfit(X,y); \n BINT = NaN * zeros(n + 1,2);\n STATS = [NaN NaN NaN];\n partialr = NaN * zeros(1, k + 1);\n \nelse\n [b,dev,stat]=glmfit(X,y); \n [B,BINT,R,RINT,STATS] = regress(y,[ones(n ,1) X]);\n \n % partial correlations\n partialr(1) = NaN; % intercept\n for i = 1:k, [x,y,partialr(i+1),partialp] = partialcor(X,y,i); end\nend\n\n\nnames = [{'Intercept'}, names];\n\nfprintf(1,'Parameter\\tb-hat\\tt\\tp\\tConf. interval\\t\\tPartial Corr\\tRob. Partial Corr.\\n')\n\nif dofigs \n create_figure('Regression Table output', k, 2); \n\nend\n \nfor i = 1:length(b)\n \n if i == 1, %intercept\n fprintf(1,'%s\\t%3.2f\\t%3.2f\\t%3.4f\\t%3.2f\\t%3.2f\\t\\n', ...\n names{i},b(i),stat.t(i),stat.p(i),BINT(i,1),BINT(i,2));\n \n else\n if dofigs\n subplot(k, 2, 2 * (i - 2) + 1); [r,str,sig] = prplot(y,X,i-1,0); xlabel([names{i}])\n subplot(k, 2, 2 * (i - 2) + 2); [r2,str,sig] = prplot(y,X,i-1,1); xlabel([names{i} ': Robust IRLS'])\n else\n r = partialr(i); \n r2 = NaN;\n end\n \n fprintf(1,'%s\\t%3.2f\\t%3.2f\\t%3.4f\\t%3.2f\\t%3.2f\\t%3.2f\\t%3.2f\\t\\n', ...\n names{i},b(i),stat.t(i),stat.p(i),BINT(i,1),BINT(i,2),r,r2);\n end\nend\n\n\nfprintf(1,'\\nOverall R2 = %3.2f, F = %3.2f, p = %3.4f\\t\\n',STATS(1),STATS(2),STATS(3));\n\n\nreturn", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/regression_table.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735663, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6943692728964196}} {"text": "function Umap=FM2map(im,U,H)\n% Unpack fuzzy-membership funcitons to produce membership maps.\n% \n% INPUT ARGUMENTS:\n% - im : N-dimensional grayscale image in integer format. \n% - U : L-by-c array of fuzzy class memberships, where c is the \n% number of classes and L is the intensity range of the input \n% image, such that L=numel(min(im(:)):max(im(:))). See \n% FastFCMeans for more info.\n% - H : image histogram returned by FastFCMeans function.\n%\n% OUTPUT:\n% - Umap : membership maps. Umap has the same size as the input image\n% plus an additional dimension to account for c classes. For\n% example, if im is a 2D M-by-N image then U will be \n% M-by-N-by-c array where U(:,:,i) is a membership map for the\n% i-th class.\n%\n% AUTHOR : Anton Semechko (a.semechko@gmail.com)\n% DATE : May.2013\n%\n\nif nargin<3 || isempty(H)\n\n % Intensity range\n Imin=double(min(im(:)));\n Imax=double(max(im(:)));\n I=(Imin:Imax)';\n \n % Intensity histogram\n H=hist(double(im(:)),I);\n H=H(:);\n\nend\n\n% Unpack memberships\nUmap=zeros(sum(H),size(U,2));\ni1=1; i2=0;\nfor i=1:numel(H)\n i2=i2+H(i);\n Umap(i1:i2,:)=repmat(U(i,:),[H(i) 1]);\n i1=i2+1;\nend\n\n% Find the positional mapping\n[~,idx]=sort(im(:), 'ascend');\n[~,idx]=sort(idx(:),'ascend');\n\n% Reshape membership maps to match image dimensions.\nUmap=reshape(Umap(idx,:),[size(im) size(U,2)]);\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/41967-fast-segmentation-of-n-dimensional-grayscale-images/FM2map.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6943692727035752}} {"text": "function [mu,dmu,k,gamma] = sparse_learning(Phi,T,lambda,iters,flag1,flag2,flag3)\n% *************************************************************************\n% \n% *** PURPOSE *** \n% Implements generalized versions of SBL and FOCUSS for learning sparse\n% representations from possibly overcomplete dictionaries.\n%\n%\n% *** USAGE ***\n% [mu,dmu,k,gamma] = sparse_learning(Phi,T,lambda,iters,flag1,flag2,flag3);\n%\n%\n% *** INPUTS ***\n% Phi = N X M dictionary\n% T = N X L data matrix\n% lambda = scalar trade-off parameter (balances sparsity and data fit)\n% iters = maximum number of iterations\n%\n% flag1 = 0: fast Mackay-based SBL update rules\n% flag1 = 1: fast EM-based SBL update rule\n% flag1 = 2: traditional (slow but sometimes better) EM-based SBL update rule\n% flag1 = [3 p]: FOCUSS algorithm using the p-valued quasi-norm\n%\n% flag2 = 0: regular initialization (equivalent to min. norm solution)\n% flag2 = gamma0: initialize with gamma = gamma0, (M X 1) vector\n%\n% flag3 = display flag; 1 = show output, 0 = supress output\n%\n% *** OUTPUTS ***\n% mu = M X L matrix of weight estimates\n% dmu = delta-mu at convergence\n% k = number of iterations used\n% gamma = M X 1 vector of hyperparameter values\n%\n%\n% *************************************************************************\n% Written by: David Wipf, david.wipf@mrsc.ucsf.edu\n% *************************************************************************\n \n\n% *** Control parameters ***\nMIN_GAMMA = 1e-16; \nMIN_DMU = 1e-12; \nMAX_ITERS = iters;\nDISPLAY_FLAG = flag3; % Set to zero for no runtime screen printouts\n\n\n% *** Initializations ***\n[N M] = size(Phi); \n[N L] = size(T);\n\nif (~flag2) gamma = ones(M,1); \nelse gamma = flag2; end; \n \nkeep_list = [1:M]';\nm = length(keep_list);\nmu = zeros(M,L);\ndmu = -1;\nk = 0;\n\n\n% *** Learning loop ***\nwhile (1)\n \n % *** Prune things as hyperparameters go to zero ***\n if (min(gamma) < MIN_GAMMA )\n\t\tindex = find(gamma > MIN_GAMMA);\n\t\tgamma = gamma(index);\n\t\tPhi = Phi(:,index);\n\t\tkeep_list = keep_list(index);\n m = length(gamma);\n \n if (m == 0) break; end;\n end;\n \n \n % *** Compute new weights ***\n G = repmat(sqrt(gamma)',N,1);\n PhiG = Phi.*G; \n [U,S,V] = svd(PhiG,'econ');\n \n [d1,d2] = size(S);\n if (d1 > 1) diag_S = diag(S); \n else diag_S = S(1); end;\n \n U_scaled = U(:,1:min(N,m)).*repmat((diag_S./(diag_S.^2 + lambda + 1e-16))',N,1); \n Xi = G'.*(V*U_scaled'); \n \n mu_old = mu;\n mu = Xi*T; \n \n \n % *** Update hyperparameters ***\n gamma_old = gamma;\n mu2_bar = sum(abs(mu).^2,2);\n \n if (flag1(1) == 0)\n % MacKay fixed-point SBL\n R_diag = real( (sum(Xi.'.*Phi)).' );\n gamma = mu2_bar./(L*R_diag); \n \n elseif (flag1(1) == 1)\n % Fast EM SBL\n R_diag = real( (sum(Xi.'.*Phi)).' );\n gamma = sqrt( gamma.*real(mu2_bar./(L*R_diag)) ); \n \n elseif (flag1(1) == 2)\n % Traditional EM SBL\n PhiGsqr = PhiG.*G;\n Sigma_w_diag = real( gamma - ( sum(Xi.'.*PhiGsqr) ).' );\n gamma = mu2_bar/L + Sigma_w_diag;\n \n else\n % FOCUSS\n p = flag1(2);\n gamma = (mu2_bar/L).^(1-p/2);\n end;\n \n \n \n % *** Check stopping conditions, etc. ***\n \tk = k+1; \n if (DISPLAY_FLAG) disp(['iters: ',num2str(k),' num coeffs: ',num2str(m), ...\n ' gamma change: ',num2str(max(abs(gamma - gamma_old)))]); end; \n if (k >= MAX_ITERS) break; end;\n \n\tif (size(mu) == size(mu_old))\n dmu = max(max(abs(mu_old - mu)));\n if (dmu < MIN_DMU) break; end;\n end;\n \nend;\n\n\n% *** Expand weights, hyperparameters ***\ntemp = zeros(M,1);\nif (m > 0) temp(keep_list,1) = gamma; end;\ngamma = temp;\n\ntemp = zeros(M,L);\nif (m > 0) temp(keep_list,:) = mu; end;\nmu = temp;\n \nreturn;\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/sparse_learning.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6943692660800681}} {"text": "function ex1bvp\n%EX1BVP Example 1 of the BVP tutorial.\n% This is the example for MUSN in U. Ascher, R. Mattheij, and R. Russell, \n% Numerical Solution of Boundary Value Problems for Ordinary Differential \n% Equations, SIAM, Philadelphia, PA, 1995. MUSN is a multiple shooting \n% code for nonlinear BVPs. The problem is\n% \n% u' = 0.5*u*(w - u)/v\n% v' = -0.5*(w - u)\n% w' = (0.9 - 1000*(w - y) - 0.5*w*(w - u))/z\n% z' = 0.5*(w - u)\n% y' = -100*(y - w)\n% \n% The interval is [0 1] and the boundary conditions are\n% \n% u(0) = v(0) = w(0) = 1, z(0) = -10, w(1) = y(1)\n% \n% The example uses a guess for the solution coded here in EX1INIT. \n% The results of a run of the FORTRAN code MUSN are here compared to\n% the curves produced by BVP4C. \n\n% Copyright 2004, The MathWorks, Inc.\n\nsolinit = bvpinit(linspace(0,1,5),@ex1init);\noptions = bvpset('Stats','on','RelTol',1e-5);\n\nsol = bvp4c(@ex1ode,@ex1bc,solinit,options);\n\n% The solution at the mesh points\nx = sol.x;\ny = sol.y;\n\n% Solution obtained using MUSN:\namrx = [ 0. .1 .2 .3 .4 .5 .6 .7 .8 .9 1.]';\namry = [1.00000e+00 1.00000e+00 1.00000e+00 -1.00000e+01 9.67963e-01\n 1.00701e+00 9.93036e-01 1.27014e+00 -9.99304e+00 1.24622e+00\n 1.02560e+00 9.75042e-01 1.47051e+00 -9.97504e+00 1.45280e+00\n 1.05313e+00 9.49550e-01 1.61931e+00 -9.94955e+00 1.60610e+00\n 1.08796e+00 9.19155e-01 1.73140e+00 -9.91915e+00 1.72137e+00\n 1.12900e+00 8.85737e-01 1.81775e+00 -9.88574e+00 1.80994e+00\n 1.17554e+00 8.50676e-01 1.88576e+00 -9.85068e+00 1.87957e+00\n 1.22696e+00 8.15025e-01 1.93990e+00 -9.81503e+00 1.93498e+00\n 1.28262e+00 7.79653e-01 1.98190e+00 -9.77965e+00 1.97819e+00\n 1.34161e+00 7.45374e-01 2.01050e+00 -9.74537e+00 2.00827e+00\n 1.40232e+00 7.13102e-01 2.02032e+00 -9.71310e+00 2.02032e+00];\n\n% Shift up the fourth component for the plot.\namry(:,4) = amry(:,4) + 10;\ny(4,:) = y(4,:) + 10;\n\nfigure\nplot(x,y',amrx,amry,'*')\naxis([0 1 -0.5 2.5])\ntitle('Example problem for MUSN')\nylabel('bvp4c and MUSN (*) solutions')\nxlabel('x')\n\n% --------------------------------------------------------------------------\n\nfunction dydx = ex1ode(x,y)\n%EX1ODE ODE function for Example 1 of the BVP tutorial.\n% The components of y correspond to the original variables\n% as y(1) = u, y(2) = v, y(3) = w, y(4) = z, y(5) = y.\ndydx = [ 0.5*y(1)*(y(3) - y(1))/y(2)\n -0.5*(y(3) - y(1))\n (0.9 - 1000*(y(3) - y(5)) - 0.5*y(3)*(y(3) - y(1)))/y(4)\n 0.5*(y(3) - y(1))\n 100*(y(3) - y(5)) ];\n\n%-------------------------------------------------------------------------\n\nfunction res = ex1bc(ya,yb)\n%EX1BC Boundary conditions for Example 1 of the BVP tutorial.\n% RES = EX1BC(YA,YB) returns a column vector RES of the\n% residual in the boundary conditions resulting from the\n% approximations YA and YB to the solution at the ends of \n% the interval [a b]. The BVP is solved when RES = 0. \n% The components of y correspond to the original variables\n% as y(1) = u, y(2) = v, y(3) = w, y(4) = z, y(5) = y.\nres = [ ya(1) - 1\n ya(2) - 1\n ya(3) - 1\n ya(4) + 10\n yb(3) - yb(5)];\n\n%-------------------------------------------------------------------------\n\nfunction v = ex1init(x)\n%EX1INIT Guess for the solution of Example 1 of the BVP tutorial.\nv = [ 1 \n 1\n -4.5*x^2+8.91*x+1\n -10\n -4.5*x^2+9*x+0.91 ];\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/3819-tutorial-on-solving-bvps-with-bvp4c/BVP_tutorial/BVP_examples_70/ex1bvp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.6943357041323871}} {"text": "function laplacian_test01 ( )\n\n%*****************************************************************************80\n%\n%% LAPLACIAN_TEST01 tests L1DD and similar routines.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 October 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LAPLACIAN_TEST01\\n' );\n fprintf ( 1, ' A full-storage matrix is returned by:\\n' );\n fprintf ( 1, ' L1DD: Dirichlet/Dirichlet BC;\\n' );\n fprintf ( 1, ' L1DN: Dirichlet/Neumann BC;\\n' );\n fprintf ( 1, ' L1ND: Neumann/Dirichlet BC;\\n' );\n fprintf ( 1, ' L1NN: Neumann/Neumann BC;\\n' );\n fprintf ( 1, ' L1PP: Periodic BC;\\n' );\n\n n = 5;\n\n for test = 1 : 2\n\n if ( test == 1 )\n h = 1.0;\n else\n h = 1.0 / ( n + 1 );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using spacing H = %g\\n', h );\n\n l = l1dd ( n, h );\n r8mat_print ( n, n, l, ' L1DD:' );\n\n l = l1dn ( n, h );\n r8mat_print ( n, n, l, ' L1DN:' );\n\n l = l1nd ( n, h );\n r8mat_print ( n, n, l, ' L1ND:' );\n\n l = l1nn ( n, h );\n r8mat_print ( n, n, l, ' L1NN:' );\n\n l = l1pp ( n, h );\n r8mat_print ( n, n, l, ' L1PP:' );\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/laplacian/laplacian_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.6943356871522488}} {"text": "function [cost,grad] = softICACost(theta, x, params)\n\n% unpack weight matrix\nW = reshape(theta, params.numFeatures, params.n);\n\n% % project weights to norm ball (prevents degenerate bases)\nWold = W;\nW = l2rowscaled(W, 1);\n\n% Forward Prop\nh = W*x;\nr = W'*h;\n\n% Sparsity Cost\nK = sqrt(params.epsilon + h.^2);\nsparsity_cost = params.lambda * sum(sum(K));\nK = 1./K;\n\n% Reconstruction Loss and Back Prop\ndiff = (r - x);\nreconstruction_cost = 0.5 * sum(sum(diff.^2));\noutderv = diff;\n\n% compute the cost comprised of: 1) sparsity and 2) reconstruction\ncost = sparsity_cost + reconstruction_cost;\n\n% Backprop Output Layer\nW2grad = outderv * h';\n\n% Baclprop Hidden Layer\noutderv = W * outderv;\noutderv = outderv + params.lambda * (h .* K);\n\nW1grad = outderv * x';\nWgrad = W1grad + W2grad';\n\n% % unproject gradient for minFunc\ngrad = l2rowscaledg(Wold, W, Wgrad, 1);\ngrad = grad(:);\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/rica-1.0/softICACost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6943311831410239}} {"text": "function [scales,weights,covar]=realized_quantile_variance_scale(samplesperbin,quantiles,simulations,symmetric)\n% Computes the scales needed for estimating the integrated variance using Realized Quantile\n% Variance. Also computes the weights of the optimal combination and non-scaled covariance from\n% which the weights are derived.\n%\n% USAGE:\n% [SCALES,WEIGHTS,COVAR]=realized_quantile_variance_scale(SAMPLESPERBIN,QUANTILES,SIMULATIONS)\n%\n% INPUTS:\n% SAMPLESPERBIN - Number of returns to use in each bin when computing the quantiles. NOTE: The\n% number of returns produced by filtering according to SAMPLINGTYPE and\n% SAMPLINGINTERVAL must be an integer multiple of SAMPLESPERBIN.\n% QUANTILES - k by 1 vector of quantile values to use when computing RQ, must satisfy 0.5\n%\n% Please DO NOT distribute this code to anybody.\n% Copyright (c) by Li Wang\n%\n% Author: Li Wang\n% E-mail: li_wang@med.unc.edu\n% URL: http://www.unc.edu/~liwa/\n%\n% 2010-01-02 PM\n\nclc;clear all;close all;\n\nImg=imread('3.bmp');\nImg = double(Img(:,:,1));\n\nNumIter = 1000; %iterations\ntimestep=0.1; %time step\nmu=0.1/timestep;% level set regularization term, please refer to \"Chunming Li and et al. Level Set Evolution Without Re-initialization: A New Variational Formulation, CVPR 2005\"\nsigma = 3;%size of kernel\nepsilon = 1;\nc0 = 2; % the constant value \nlambda1=1.03;%outer weight, please refer to \"Chunming Li and et al, Minimization of Region-Scalable Fitting Energy for Image Segmentation, IEEE Trans. Image Processing, vol. 17 (10), pp. 1940-1949, 2008\"\nlambda2=1.0;%inner weight\n%if lambda1>lambda2; tend to inflate\n%if lambda1 0 \n solplot(x_gal,xy,x,y,10);\n title(['Q',int2str(qmethod),' solution'])\n drawnow\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/toms866/diffusion/quad_diff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.694254228444353}} {"text": "function [tdata, validIdx] = translate_movie(data, dv, ops)\n\n%% Parameters\n[ly, lx, nFrames] = size(data);\nif nargin < 3 \n ops = [];\nend\nsubpixel = getOr(ops, {'subPixel' 'SubPixel'}, 1);\nif isfinite(subpixel)\n dv = round(subpixel*dv)./subpixel;\nend\nuseGPU = getOr(ops, 'useGPU', false);\n\ndv = permute(dv, [2 3 1]);\nfy = ifftshift((-fix(ly/2):ceil(ly/2) - 1)/ly)';% freq along first dimension\nfx = ifftshift((-fix(lx/2):ceil(lx/2) - 1)/lx); % freq along second dimension\n\nif useGPU\n batchSize = 32;\n fx = gpuArray(fx);\n fy = gpuArray(fy);\n dv = gpuArray(dv);\nelse\n batchSize = 3;\nend\ntdata = zeros([ly, lx, nFrames], 'like', data);\n%% Work through data in batches\nnBatches = ceil(nFrames/batchSize);\nfor bi = 1:nBatches\n fi = (bi - 1)*batchSize + 1:min(bi*batchSize, nFrames);\n if useGPU\n batchData = gpuArray(single(data(:,:,fi)));\n else\n batchData = single(data(:,:,fi));\n end\n phaseShift = bsxfun(@times,...\n exp(-1j*2*pi*bsxfun(@times, fy, dv(1,:,fi))),... y rotation\n exp(-1j*2*pi*bsxfun(@times, fx, dv(2,:,fi)))); % x rotation\n tdata(:,:,fi) = gather(real(ifft2(fft2(batchData).*phaseShift)));\nend\nif nargout > 1\n dvMax = max(0, ceil(max(gather(dv), [], 3)));\n dvMin = min(0, floor(min(gather(dv), [], 3)));\n validX = (1 + dvMax(2)):(lx + dvMin(2));\n validY = (1 + dvMax(1)):(ly + dvMin(1));\n validIdx = {validY validX};\nend\n\nend\n", "meta": {"author": "cortex-lab", "repo": "Suite2P", "sha": "c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5", "save_path": "github-repos/MATLAB/cortex-lab-Suite2P", "path": "github-repos/MATLAB/cortex-lab-Suite2P/Suite2P-c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5/registration/old/translate_movie.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6942519444766355}} {"text": "%==============================================================================\n% This code is part of the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR and\n% - http://www.siam.org/books/fa06/\n% ##2\n%==============================================================================\n%\n% Tutorial for FAIR: regulariztion\n%\n% given a certain force field f on a 2D domain, this tutorial \n% computes and visualizes the elastic displacement u, such that \n%\n% B'*B u = f\n%\n% where B is the discrete elastic operator \n% see also getElasticMatrixStg\n%==============================================================================\n\nclear, close all, help(mfilename);\n\n % 2D example\nomega = [0,1,0,1]; % physical domain\nm = [16,12]; % number of discretization points\nmu = 1; % Lame constants, control elasticity properties\nlambda = 0; % Youngs modulus and Poisson ratio\nn = prod(m); % number of cells, and staggered dimensions\nns = [(m(1)+1)*m(2),m(1)*(m(2)+1)];\n\n% generate cell centered, staggered and nodal grids\n% note: computation is staggered, others used for visualization\nxc = getCellCenteredGrid(omega,m);\nxn = getNodalGrid(omega,m);\n\n% build elasticity operator on a staggered grid and visualize\nB = getElasticMatrixStg(omega,m,mu,lambda);\nFAIRfigure(1); clf; subplot(2,2,1); spy(B); title('B elastic on staggered grid')\n\n% create a force field o cell centered grid and visualize\nfc = [0*xc(1:n);-10*sin(pi*xc(1:n))];\n% computations on staggered grid\nfs = grid2grid(fc,m,'centered','staggered');\n\n% compute the displacement from (B'*B)*us = fs\n% note B is derivative operator and has null space (constants)\n\n% remove constant parts: E'*(f-E*w) = 0\nE = [ones(ns(1),1)*[1,0];ones(ns(2),1)*[0,1]];\nfs = fs - E*((E'*E)\\(E'*fs));\n\n% solve for displacements\nwarning off % matrix is singular, but MATLAB doesn't care\nus = (B'*B)\\fs;\nwarning on\n\n% visualization on cell centered and nodal grids\nuc = grid2grid(us,m,'staggered','centered');\nun = grid2grid(us,m,'staggered','nodal');\n\n% shortcuts for visualization, \nvecNorm = @(v) sqrt(sum(reshape(v,[],2).^2,2));\nviewField = @(v) viewImage2Dsc(vecNorm(v),omega,m); \nPG = @(x) plotGrid(x,omega,m);\n\n% visualize force field\nFAIRfigure(1); subplot(2,2,3);\nviewField(fc); hold on; colormap(gray); colorbar; PG(xn); \nqh = quiver(xc(1:n),xc(n+1:end),fc(1:n),fc(n+1:end),1);\nset(qh,'color','r','linewidth',1)\ntitle('a force field')\n\n% visualize displacement field\nFAIRfigure(1); subplot(2,2,4);\nviewField(uc); hold on; colormap(gray); colorbar; PG(xn);\nqh = quiver(xc(1:n),xc(n+1:end),uc(1:n),uc(n+1:end),1);\nset(qh,'color','g','linewidth',1)\ntitle('the displacement field')\n\n% visuaize the displaced grid\nFAIRfigure(1); subplot(2,2,2);\nxh = PG(xn); hold on; axis equal image; yh = PG(xn+un); \nset(xh,'linewidth',2); set(xh,'linewidth',2,'color','g');\ntitle('initial and displaced grids')\n\n%==============================================================================\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/examples/E8_forcesElastic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6942519378261487}} {"text": "function [h_1d, h_2d] = create_blur_kernel(Kx,opt)\n\nFIX_HSIZE = 1; % hsize = 11\nHSIZE = 15;\neps = 0.01;\n\nif FIX_HSIZE\n V = [Kx(1:floor(HSIZE/2)+1); Kx(opt.N-floor(HSIZE/2)+1:opt.N)];\n V = circshift(V, floor(HSIZE/2));\nelse\n for i = 1:length(Kx)\n if i>2 && Kx(i) < eps\n halflen = i-2;\n break\n end\n end\n\n len = 2*halflen + 1;\n V = zeros(1, len);\n for i = 1:halflen\n V(i) = Kx(opt.N - halflen + i);\n end\n for i = halflen+1:len\n V(i) = Kx(i-halflen);\n end\nend\n\nV = V / sum(V);\n\nh_1d = V';\nh_2d = h_1d'*h_1d;", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/BayesianVSR/functions/create_blur_kernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6942511886892495}} {"text": "function [oAllanDev] = calculateADEV(tau,sPeriod,readings)\n%Overlapping Allan (ADEV) function that uses phase error or time error values\n%input argument is readings already grouped as tau values. tau is the\n%desired gate or tau time needed for calculating overlap. \n%sPeriod is used to determine the overlap\n\nN = numel(readings); %get the reading count\nn = tau / sPeriod; %calculate averaging factor\nn = floor(n); %make sure this is an integer\nconst = 1/(2*(N - (2*n))*tau^2); %calculate the const mult 1/(2*(N - (2*n))*tau^2)\n%sum from i=1 to N-2n (Xi+2m - 2Xi+m + Xi)^2\nsum = 0; %variable to store summation calculation\n\n\n%loop for performing summation\nfor i = 1:(N-(2*n))\n sum = sum + (readings(i+(2*n)) - (2*readings(i+n)) + readings(i))^2; %previos sum + (yi+1 - yi)^2\nend\n\noAllanDev = sqrt(const*sum); %square root for Allan Dev", "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/31319-stability-analyzer-53230a/Stability Analyzer 2.0/calculateADEV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806521, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6942511853086726}} {"text": " function [cost grad] = mri_r2_fit_costgrad_pd(pd, data)\n%|function [cost grad] = mri_r2_fit_costgrad_pd(pd, data)\n%| gradient wrt \"proton density\" (pd) image\n%| for R2=1/T2 estimation from images\n\nif nargin == 1 && streq(pd, 'test'), mri_r2_fit_costgrad_pd_test, return, end\nif nargin < 2, ir_usage, end\n\nyi = data.yi; % [(nd) nt] images\nr2 = data.r2; % [(nd)] R2=1/T2 maps\nte = data.te; % echo times\n\n[yb yi] = mri_r2_fit_mean(pd, r2, yi, te);\ncost = sum(abs(yi(:) - yb(:)).^2) / 2;\n\ngrad = mri_r2_fit_grad_pd(pd, r2, yi - yb, te);\n\nif isfield(data, 'R')\n\tR = data.R;\n\tcost = cost + R.penal(R, pd);\n\tgrad = grad + R.cgrad(R, pd);\nend\ngrad = reshape(grad, size(pd));\n\n\n% mri_r2_fit_mean()\nfunction [yb yi] = mri_r2_fit_mean(pd, r2, yi, te)\n\nnt = numel(te);\nyi = reshapee(yi, [], nt); % [*nd nt]\nyb = zeros(size(yi)); % [*nd nt]\nfor it=1:nt\n\tyb(:,it) = pd(:) .* exp(-te(it) * r2(:));\nend\n\n\n% mri_r2_fit_grad_pd()\nfunction grad = mri_r2_fit_grad_pd(pd, r2, resid, te)\n\nnt = numel(te);\n\ngrad = 0;\nfor it=1:nt\n\ttmp = exp(-te(it) * r2(:));\n\tgrad = grad - tmp .* resid(:,it);\nend\n\n\nfunction mri_r2_fit_costgrad_pd_test\n\nr2 = 0.01;\nte = [0:3] * 20;\npd = 2;\nyb = pd .* exp(-te * r2);\nrng(0)\nyi = yb + 0.1 * randn(size(yb));\n\n%R = Reg1(true(1), 'beta', 3, 'order', 0, 'type_penal', 'mat');\n\ndata.yi = yi;\ndata.r2 = r2;\ndata.te = te;\n%data.R = R;\n\npdlist = linspace(0, 4, 101);\ncost = zeros(size(pdlist));\nfor ii=1:numel(pdlist)\n\tcost(ii) = mri_r2_fit_costgrad_pd(pdlist(ii), data);\nend\n\np0 = 1.5;\n[cost0 grad0] = mri_r2_fit_costgrad_pd(p0, data);\n\nif im\n\tclf\n\tplot(pdlist, cost, '-', pdlist, cost0 + grad0*(pdlist-p0), '--')\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/mri/mri_r2_fit_costgrad_pd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6942436454366981}} {"text": "function result=rsimpls(x,y,varargin)\n\n%RSIMPLS is a 'Robust method for Partial Least Squares Regression based on the\n% SIMPLS algorithm'. It can be applied to both low and high-dimensional predictor variables x\n% and to one or multiple response variables y. It is resistant to outliers in the data.\n% The RSIMPLS algorithm is built on two main stages. First, a matrix of scores is derived \n% based on a robust covariance criterion (see robpca.m),\n% and secondly a robust regression is performed based on the results from ROBPCA. \n% \n% The RSIMPLS method is described in: \n% Hubert, M., and Vanden Branden, K. (2003),\n% \"Robust Methods for Partial Least Squares Regression\",\n% Journal of Chemometrics, 17, 537-549.\n%\n% To select the number of components in the regression model, a robust RMSECV (root mean squared\n% error of cross validation) curve is drawn, based on a fast algorithm for\n% cross-validation. This approach is described in:\n%\n% Engelen, S., Hubert, M. (2005),\n% \"Fast model selection for robust calibration methods\",\n% Analytica Chimica Acta, 544, 219-228.\n%\n% Required input arguments:\n% x : Data matrix of the explanatory variables\n% (n observations in rows, p variables in columns)\n% y : Data matrix of the response variables\n% (n observations in rows, q variables in columns)\n% \n% Optional input arguments: \n% k : Number of components to be used. \n% (default = min(rank([x,y]),kmax)). If k is not specified,\n% it can be selected using the option 'rmsecv'. \n% kmax : Maximal number of components to be used (default = 9).\n% If k is provided, kmax does not need to be specified, unless k is larger\n% than 9. \n% alpha : (1-alpha) measures the fraction of outliers the algorithm should \n% resist. Any value between 0.5 and 1 may be specified. (default = 0.75)\n% h : (n-h+1) measures the number of observations the algorithm should \n% resist. Any value between n/2 and n may be specified. (default = 0.75*n)\n% Alpha and h may not both be specified.\n% rmsecv : If equal to zero and k is not specified, a robust R-squared curve\n% is plotted and an optimal k value can be chosen. (default)\n% If equal to one and k is not specified, a robust component selection-curve is plotted and\n% an optimal k value can be chosen. This curve computes a combination of\n% the cross-validated root mean squared error and the robust residual \n% sum of squares for k=1 to kmax. Rmsecv and k may not both\n% be specified.\n% rmsep : If equal to one, the robust RMSEP-value (root mean squared error of\n% prediction) for the model with k components (default = 0). This value\n% is automatically given if rmsecv = 1.\n% plots : If equal to one, a menu is shown which allows to draw several plots,\n% such as a robust score outlier map and a regression\n% outlier map are drawn. (default)\n% If the input argument 'classic' is equal to one, the classical\n% diagnostic plots are drawn as well.\n% If 'plots' is equal to zero, all plots are suppressed.\n% See also makeplot.m\n% labsd : The 'labsd' observations with largest score distance are\n% labeled on the outlier map (default = 3)\n% labod : The 'labod' observations with largest orthogonal distance are\n% labeled on the outlier map (default = 3) \n% labresd : The 'labresd' observations with largest residual distance are\n% labeled on the outlier map (default = 3) \n% classic : If equal to one, the classical SIMPLS analysis will be performed as well\n% (see also csimpls.m). (default = 0)\n%\n% Options for advanced users:\n% kr : Total number of components used by the ROBPCA method.\n% We advise to use kr=k+q. (default) \n% kmaxr : Maximal number of components used by the ROBPCA method. \n% default = min(kmax+q,rank([x,y]))\n% plotsrobpca : If equal to one, a robust score outlier map from ROBPCA is drawn. \n% If the input argument 'classic' is equal to one, the classical\n% outlier map is drawn as well.\n% If 'plotsrobpca' is equal to zero, all plots are suppressed. (default)\n% st : Indicates the current stage of the algorithm for cross-validation (RMSECV) \n% default = 0 -> performs all the stages of the algorithm and computes all the \n% parameters for the full model. \n% st=1, robpca is still performed, but when \n% st=2, the algorithm proceeds based on the previous knownledge of the output from robpca. \n% out : Is an empty structure, but is constructed while performing the cross-validation.\n% (see rrmse.m)\n%\n% I/O: result=rsimpls(x,y,'k',k,'kmax',10,'alpha',0.75,'h',h,'rmsecv',0,'rmsep',0,...\n% 'plots',1,'labsd',3,'labod',3,'labresd',3,'classic',1,'kr',kr,...\n% 'kmaxr',kmaxr,'plotsrobpca',0,'st',0,'out',[]);\n% The user should only give the input arguments that have to change their default value.\n% The name of the input arguments needs to be followed by their value.\n% The order of the input arguments is of no importance.\n%\n% Examples:\n% rsimpls(x,y,'k',5,'plots',1);\n% rsimpls(x,y,'classic',1,'rmsecv',1);\n%\n% The output of RSIMPLS is a structure containing:\n%\n% result.slope : Robust slope estimate\n% result.int : Robust intercept estimate\n% result.fitted : Robust fitted values\n% result.res : Robust residuals\n% result.cov : Estimated variance-covariance matrix of the residuals \n% result.T : Robust scores\n% result.weights.r : Robust simpls weights\n% result.weights.p : Robust simpls weights\n% result.Tcenter : Robust center of the scores\n% result.Tcov : Robust covariance matrix of the scores \n% result.rsquared : Robust R-squared value for the optimal k\n% result.rcs : Robust Component Selection Criterion:\n% This is a matrix with kmax columns. The first row contains the approximate\n% R-squared values (for k=1,...,kmax) and the second row the square root of the weighted\n% residuals sum of squares. This is equal to the RCS-value with \n% gamma = 0 (see Engelen and Hubert (2005) for the definition). \n% If the input argument rmsecv = 1, the third row contains the RCS-value for\n% gamma = 0.5 and the fourth for gamma = 1. The last one is equal to the robust \n% cross-validated RMSE values. \n% Note that all the entries in this matrix depend on the choice of kmax. \n% result.rmsep : Robust RMSEP value \n% result.k : Number of components used in the regression\n% result.h : The quantile h used throughout the algorithm\n% result.sd : Robust score distances\n% result.od : Robust orthogonal distances\n% result.resd : Residual distances (when there are several response variables).\n% If univariate regression is performed, it contains the standardized residuals.\n% result.cutoff : Cutoff values for the score (result.cutoff.sd), orthogonal \n% (result.cutoff.od) and residual distances (result.cutoff.resd).\n% We use 0.975 quantiles of the chi-squared distribution.\n% result.flag : The observations whose score distance is larger than \n% 'result.cutoff.sd' receive a flag 'result.flag.sd' equal\n% to zero (good leverage points). Otherwise 'result.flag.sd'\n% is equal to one. \n% The components 'result.flag.od' and 'result.flag.resd' are\n% defined analogously, and determine the orthogonal outliers, \n% resp. the bad leverage points/vertical outliers. \n% The observations with 'result.flag.od' and 'result.flag.resd'\n% equal to zero, can be considered as calibration outliers and receive\n% 'result.flag.all' equal to zero. The regular observations and the good leverage\n% points have 'result.flag.all' equal to one.\n% result.class : 'RSIMPLS'\n% result.classic : If the inputargument 'classic' is equal to 1, this structure\n% contains results of the classical SIMPLS analysis. (see also csimpls.m)\n% results.robpca : The results of robpca on [X,Y]. \n%\n% This function is part of LIBRA: the Matlab Library for Robust Analysis,\n% available at: \n% http://wis.kuleuven.be/stat/robust.html\n%\n% Written by Karlien Vanden Branden\n% Version date: 07/04/2004 \n% Last update: 04/08/2006\n\n%\n%initialization with defaults\n%\nif rem(nargin,2)~=0\n error('Number of input arguments must be even!');\nend\n[n,p1]=size(x);\n[n2,q1]=size(y);\nz=[x,y];\nrx=rank(x);\nrz=rank(z);\nif n~=n2\n error('The response variables and the predictor variables have a different number of observations.')\nend\nniter=100;counter=1;mcd=0;alfa=0.75;\nkmax=min([9,rx,floor(n/2),p1]);\nkmaxr=min([kmax+q1,rz]);\nh=floor(2*floor((n+kmaxr+1)/2)-n+2*(n-floor((n+kmaxr+1)/2))*alfa);\nlabsd=3;labod=3;labresd=3;\nplotsrobpca=0;plots=1;k=0;\nkr=k+q1;\nst=0;rmsecv=0;\nout=[];classic=0;rmsep=0;rmsep_value=nan;rmsecv_value = nan;rsquared_value = nan;rss_value = nan;\ndefault=struct('alpha',alfa,'h',h,'labsd',labsd,'labod',labod,'labresd',labresd,'k',k,'kr',kr,...\n 'plotsrobpca',plotsrobpca,'plots',plots,'kmax',kmax,'st',st,...\n 'out',out,'rmsecv',rmsecv,'classic',classic,'rmsep',rmsep,...\n 'kmaxr',kmaxr,'rmsep_value',rmsep_value,'rmsecv_value',rmsecv_value,'rsquared_value',...\n rsquared_value,'rss_value',rss_value);\nlist=fieldnames(default);\noptions=default;\nIN=length(list);\ni=1;\n%\nif nargin>2\n %\n %placing inputfields in array of strings\n %\n for j=1:nargin-3\n if rem(j,2)~=0\n chklist{i}=varargin{j};\n i=i+1;\n end\n end \n dummy=sum(strcmp(chklist,'h')+2*strcmp(chklist,'alpha'));\n switch dummy\n case 0 %Take on default values \n options.alpha=alfa;%0.75;\n options.h=h;\n case 3\n error('Both input arguments alpha and h are provided. Only one is required.')\n end\n %\n %Checking which default parameters have to be changed\n % and keep them in the structure 'options'.\n %\n while counter<=IN \n index=strmatch(list(counter,:),chklist,'exact');%contains the users input one by one\n if ~isempty(index) %in case of similarity\n for j=1:nargin-3 %searching the index of the accompanying field\n if rem(j,2)~=0 %fieldnames are placed on odd index\n if strcmp(chklist{index},varargin{j})\n I=j;\n end\n end\n end\n options=setfield(options,chklist{index},varargin{I+1});\n index=[];\n end\n counter=counter+1;\n end\n options.h=floor(options.h);\n options.kmax=floor(options.kmax);\n options.k=floor(options.k);\n options.kmaxr=floor(options.kmaxr);\n options.kr=floor(options.kr);\n kmax=min([options.kmax,floor(n/2),rz,p1]);\n kmaxr=max([min([options.kmaxr,rz]),kmax+q1]);\n k=min(options.k,kmax);\n while k<0\n k=input(['The number of components can not be negative.\\n'...\n 'How many principal components would you like to retain?\\n']);\n end\n if any(strcmp(chklist,'kr'))\n kr=floor(max([options.kr,k+q1]));\n else\n kr=k+q1;\n end\n if dummy==1 %checking inputvariable h\n if options.h-floor(options.h)~=0\n mess=sprintf('Attention (rsimpls.m): h must be an integer. \\n');\n disp(mess)\n end\n if kr==0\n if options.hn\n options.alpha=0.75;\n if kr==0\n options.h=floor(2*floor((n+kmaxr+1)/2)-n+2*(n-floor((n+kmaxr+1)/2))*options.alpha);\n else\n options.h=floor(2*floor((n+kr+1)/2)-n+2*(n-floor((n+kr+1)/2))*options.alpha);\n end \n mess=sprintf(['Attention (rsimpls.m): h should be smaller than n. \\n',...\n 'It is set to its default value ',num2str(options.h)]);\n disp(mess)\n end\n elseif dummy==2\n if options.alpha < 0.5\n options.alpha=0.5;\n mess=sprintf(['Attention (rsimpls.m): Alpha should be larger than 0.5. \\n',...\n 'It is set to 0.5.']);\n disp(mess)\n end\n if options.alpha > 1\n options.alpha=0.75;\n mess=sprintf(['Attention (rsimpls.m): Alpha should be smaller than 1.\\n',...\n 'It is set to 0.75.']);\n disp(mess)\n end\n if kr==0\n options.h=floor(2*floor((n+kmaxr+1)/2)-n+2*(n-floor((n+kmaxr+1)/2))*options.alpha);\n else\n options.h=floor(2*floor((n+kr+1)/2)-n+2*(n-floor((n+kr+1)/2))*options.alpha);\n end \n end\n h=options.h;alfa=options.alpha;labsd=max(0,min(floor(options.labsd),n));\n dummyh = strcmp(chklist,'h');\n dummykmax = strcmp(chklist,'kmax');\n if all(dummyh == 0) && any(dummykmax)\n h = floor(2*floor((n+kmax+1)/2)-n+2*(n-floor((n+kmax+1)/2))*alfa);\n end\n labod=max(0,min(floor(options.labod),n));labresd=max(0,min(floor(options.labresd),n));\n plotsrobpca=options.plotsrobpca;plots=options.plots;\n st=options.st;\n out=options.out;\n rmsecv=options.rmsecv;\n classic=options.classic;\n rmsep=options.rmsep;\n rmsep_value = options.rmsep_value;\n rmsecv_value = options.rmsecv_value;\n rmsecv = options.rmsecv;\n rsquared_value = options.rsquared_value;\n rss_value = options.rss_value;\nend\n\nif q1==1 && k>=(h-2)\n mess=sprintf(['Attention (rsimpls.m): The number of components, k = ',num2str(k),...\n '\\n is larger than our recommended maximum value of k = ',num2str(h-2)-1,'.']);\n disp(mess)\nelseif q1>1 && k>=((h/q1)-(q1/2)-0.5)\n mess=sprintf(['Attention (rsimpls.m): The number of components, k = ',num2str(k),...\n '\\n is larger than our recommended maximum value of k = ',num2str(floor((h/q1)-(q1/2)-1.5)),'.']);\n disp(mess)\nend\n\n%\n%MAIN PART\n%\n% selection of number of components\nif k == 0\n if rmsecv == 0\n [R2,final]=rsquared(x,y,kmax,'RSIMPLS',options.h);\n rss = final.rss;\n k = final.k;\n result=rsimpls(x,y,'k',k,'kr',k+q1,'h',h,'rmsecv',0,'rmsep',options.rmsep,'plots',0,'classic',classic,'rsquared_value',R2,'rss_value',rss); \n else\n out=rrmse(x,y,h,kmax,'RSIMPLS',1);\n R2 = out.R2;\n rss = out.rss;\n k=out.k;\n rmsecv_value = out.rmsecv;\n pred = rrmse(x,y,h,kmax,'RSIMPLS',0,k,out.weight,out.res);\n result=rsimpls(x,y,'k',k,'kr',k+q1,'h',h,'rmsecv',0,'rmsep',0,'plots',0,'classic',classic,'rmsep_value',pred.rmsep,'rmsecv_value',rmsecv_value,'rsquared_value',R2,'rss_value',rss); \n end\nelse\n if rmsecv\n error(['Both RMSECV and k were given.', ...\n 'Please rerun your analysis with one of these inputs. (see help file)'])\n end\n%First stage: Obtain the scores T by first performing ROBPCA on z: \n if st<=1\n out.robpca=robpca(z,'k',kr,'h',h,'plots',plotsrobpca,'kmax',kmaxr,'classic',classic,'mcd',mcd);\n out.h=h;\n out.centerz=out.robpca.M;\n out.sigmaxy=out.robpca.P(1:p1,:)*diag(out.robpca.L)*out.robpca.P(p1+1:p1+q1,:)';\n out.sigmax=out.robpca.P(1:p1,:)*diag(out.robpca.L)*out.robpca.P(1:p1,:)';\n out.xcentr=x-repmat(out.centerz(1:p1),n,1);\n out.ycentr=y-repmat(out.centerz(p1+1:p1+q1),n,1);\n out.weights2=out.robpca.flag.all; \n end\n if st\n i=k;\n else \n i=1;\n end\n while i<=k\n out.sigmayx=out.sigmaxy';\n if q1>p1 \n [RR,LL]=eig(out.sigmaxy*out.sigmayx); \n [LL,I]=greatsort(diag(LL));\n rr=RR(:,I(1));\n qq=out.sigmayx*rr; \t\t\t\t\t\t \n qq=qq/norm(qq); \n else\n [QQ,LL]=eig(out.sigmayx*out.sigmaxy);\t\n [LL,I]=greatsort(diag(LL));\n qq=QQ(:,I(1));\n rr=out.sigmaxy*qq;\n rr=rr/norm(rr); \n end\n tt=out.xcentr*rr;\n uu=out.ycentr*qq;\t\n pp=out.sigmax*rr/(rr'*out.sigmax*rr);\n vv=pp;\n if i>1 \t\t\t\t\t\t\t\t\t\t\t\t\n vv=vv-out.v*(out.v'*pp);\n end\n if vv'*vv==0\n error('The number of components is too large')\n end\n vv=vv./norm(vv);\t\t\t\t\t\t\t\t\t\n out.sigmaxy=out.sigmaxy-vv*(vv'*out.sigmaxy); \n out.v(:,i)=vv;\n out.q(:,i)=qq;\n out.t(:,i)=tt;\n out.u(:,i)=uu;\n out.p(:,i)=pp;\n out.r(:,i)=rr;\n i=i+1;\n end\n \n %Second Stage : Robust ROBPCA-regression\n robpcareg=robpcaregres(out.t,y,out.weights2);\n breg=robpcareg.coeffs(1:k,:);\n Yhat=out.t*breg+repmat(robpcareg.coeffs(k+1,:),n,1);\n b=out.r*breg; \n int=robpcareg.coeffs(k+1,:)-out.centerz(1:p1)*out.r*breg;\n\n if rmsep==1\n rmse=rrmse(x,y,h,kmax,'RSIMPLS',0,k); \n out.rmsep=rmse.rmsep;\n end\n \n % testing several output parameters\n if ~isnan(rmsep_value)\n out.rmsep = rmsep_value;\n options.rmsep = 1;\n end\n \n if ~isnan(rsquared_value)\n out.rcs = rsquared_value;\n end\n if ~isnan(rss_value)\n out.rcs = [out.rcs;sqrt(rss_value)];\n end\n if ~isnan(rmsecv_value)\n gammahalf = 0.5*sqrt(rss_value) + 0.5*rmsecv_value;\n out.rcs = [out.rcs;gammahalf;rmsecv_value];\n options.rmsecv = 1;\n end\n if any(isnan(rsquared_value)) && any(isnan(rss_value)) && any(isnan(rmsecv_value))\n out.rcs = 0;\n end\n\n %The output:\n out.T=out.t;\n out.weights.p=out.p;\n out.weights.r=out.r;\n out.kr=kr;\n out.h=h;\n out.alpha=alfa;\n out.slope=b;\n out.int=int;\n out.yhat=x*b+repmat(int,n,1);\n out.x=x;\n out.y=y;\n out.res=y-out.yhat;\n out.class='RSIMPLS';\n out.k=k;\n out.cov=robpcareg.cov;\n \n if ~st\n %calculation of robust distances\n %Score distance\n out.Tcov=robpcareg.sigma(1:k,1:k);\n out.Tcenter=robpcareg.center(1:k);\n out.sd=sqrt(mahalanobis(out.t,out.Tcenter,'cov',out.Tcov))';\n out.cutoff.sd=sqrt(chi2inv(0.975,k));\n %robust residual distance\n if q1==1\n out.resd=out.res/sqrt(out.cov);\n else\n out.resd=sqrt(mahalanobis(out.res,zeros(1,q1),'cov',out.cov))';\n end\n %robust orthogonal distances\n xtilde=out.t*out.p';\n Cdiff=out.xcentr-xtilde;\n for i=1:n\n out.od(i,1)=norm(Cdiff(i,:));\n end\n r=rank(x);\n if k~=r\n [m,s]=unimcd(out.od.^(2/3),out.h);\n out.cutoff.od = sqrt(norminv(0.975,m,s)^3);\n else\n out.cutoff.od=0;\n end\n out.cutoff.resd=sqrt(chi2inv(0.975,q1));\n\n %Computing flags\n out.flag.od=out.od<=out.cutoff.od;\n out.flag.resd=abs(out.resd)<=out.cutoff.resd;\n out.flag.all=(out.flag.od & out.flag.resd);\n\n\n %Multivariate Rsquared\n Yw=y(out.flag.all==1,:);\n cYw=mcenter(Yw);\n res=out.res(out.flag.all==1,:);\n out.rsquared=1-(det(res'*res)/det(cYw'*cYw));\n\n %Assigning output\n if options.rmsep~=1 && options.rmsecv~=1\n out.rmsep=0;\n end\n\n if classic\n resultclassic=csimpls(x,y,'k',k,'plots',0);\n else\n resultclassic=0;\n end\n result=struct('slope',{out.slope}, 'int',{out.int},'fitted',{out.yhat},'res',{out.res}, 'cov',{out.cov},...\n 'T',{out.T}, 'weights', {out.weights},'Tcenter',{out.Tcenter},'Tcov',{out.Tcov},'rsquared',{out.rsquared},'rcs',{out.rcs},'rmsep',{out.rmsep},...\n 'k',{out.k},'alpha',{out.alpha},'h',{out.h},'sd', {out.sd},'od',{out.od},...\n 'resd',{out.resd},'cutoff',{out.cutoff},'flag',{out.flag},'class',{out.class},'classic',{resultclassic},'robpca',{out.robpca});\n if result.rcs==0\n result=rmfield(result,'rcs');\n end\n if result.rmsep==0\n result=rmfield(result,'rmsep');\n end\n else\n result=out;\n end\nend\n\n% Plots\ntry\n if plots && options.classic\n makeplot(result,'classic',1,'labsd',labsd,'labod',labod,'labresd',labresd)\n elseif plots\n makeplot(result,'labsd',labsd,'labod',labod,'labresd',labresd)\n end\ncatch %output must be given even if plots are interrupted\nend\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/LIBRA/rsimpls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.6942436433939526}} {"text": "%MDL_PLANAR2 Create model of a simple planar 2-link mechanism\n%\n% MDL_PLANAR2 is a script that creates the workspace variable p2 which\n% describes the kinematic characteristics of a simple planar 2-link\n% mechanism.\n%\n% Also defines the vector:\n% qz corresponds to the zero joint angle configuration.\n%\n% Also defines the vector:\n% qz corresponds to the zero joint angle configuration.\n%\n% Notes::\n% - Moves in the XY plane.\n% - No dynamics in this model.\n%\n% See also mdl_twolink, mdl_planar1, mdl_planar3, SerialLink.\n\n\n% MODEL: generic, planar, 2DOF, symbolic, standard_DH\n\n\n% Copyright (C) 1993-2017, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser 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% RTB 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 Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\n\nsyms a1 a2 real;\n\np2 = SerialLink([\n Revolute('d', 0, 'a', a1, 'alpha', 0, 'standard')\n Revolute('d', 0, 'a', a2, 'alpha', 0, 'standard')\n ], ...\n 'name', 'two link');\nqz = [0 0];\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/models/mdl_planar2_sym.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.6942436345099902}} {"text": "function f = bilinear_kernel(k, num_input, num_output)\n% -------------------------------------------------------------------------\n% Description:\n% create bilinear interpolation kernel for the convt (deconv) layer\n%\n% Input:\n% - k : kernel size k x k\n% - num_input : number of input channels\n% - num_output : number of output channels\n%\n% Output:\n% - f : bilinear filter\n%\n% Citation: \n% Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution\n% Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang\n% IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017\n%\n% Contact:\n% Wei-Sheng Lai\n% wlai24@ucmerced.edu\n% University of California, Merced\n% -------------------------------------------------------------------------\n\n\n radius = ceil(k / 2);\n \n if rem(k, 2) == 1\n center = radius;\n else\n center = radius + 0.5;\n end\n \n C = 1:k;\n f = (ones(1, k) - abs(C - center) ./ radius)' ...\n * (ones(1, k) - abs(C - center) ./ radius);\n \n f = repmat(f, 1, 1, num_input, num_output);\n\n\nend\n\n", "meta": {"author": "phoenix104104", "repo": "LapSRN", "sha": "95154bba82a3aab9bdaec8e0eedd4187babc5ed2", "save_path": "github-repos/MATLAB/phoenix104104-LapSRN", "path": "github-repos/MATLAB/phoenix104104-LapSRN/LapSRN-95154bba82a3aab9bdaec8e0eedd4187babc5ed2/utils/bilinear_kernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.69424363450999}} {"text": "function y = l2lossForward( x,r )\n\ndelta = x - r;\n\ny = sum(delta(:).^2);\n\ny = y / (size(x,1)*size(x,2));\n\nend\n\n", "meta": {"author": "ybsong00", "repo": "Vital_release", "sha": "50de529396e2f452626aef41084972149cf4a7c7", "save_path": "github-repos/MATLAB/ybsong00-Vital_release", "path": "github-repos/MATLAB/ybsong00-Vital_release/Vital_release-50de529396e2f452626aef41084972149cf4a7c7/vital/l2lossForward.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7853085758631158, "lm_q1q2_score": 0.6942436341535003}} {"text": "function [M,E,EMAP] = crouzeix_raviart_massmatrix(V,F)\n % CROUZEIX_RAVIART_MASSMATRIX Compute the Crouzeix-Raviart mass matrix where\n % M(e,e) is just the sum of 1/3 the areas of the triangles on either side of\n % an edge e. For tets, edges are now faccets.\n %\n % See for example \"Discrete Quadratic Curvature Energies\" [Wardetzky, Bergou,\n % Harmon, Zorin, Grinspun 2007]\n %\n % Inputs:\n % V #V by dim list of vertex positions\n % F #F by element-size list of triangle indices\n % Outputs:\n % M #E by #E edge-based diagonal mass matrix\n % E #E by 2 list of edges\n %\n % See also: edge_laplacian, is_boundary_edge, crouzeix_raviart_cotmatrix,\n % massmatrix\n %\n\n switch size(F,2)\n case 3\n allE = [F(:,[2 3]);F(:,[3 1]);F(:,[1 2])];\n % Map duplicate edges to first instance\n [E,~,EMAP] = unique(sort(allE,2),'rows');\n TA = doublearea(V,F)/2;\n M = sparse(EMAP,EMAP,repmat(TA/3,3,1),size(E,1), size(E,1));\n case 4\n T = F;\n allF = [ ...\n T(:,2) T(:,4) T(:,3); ...\n T(:,1) T(:,3) T(:,4); ...\n T(:,1) T(:,4) T(:,2); ...\n T(:,1) T(:,2) T(:,3); ...\n ];\n vol = volume(V,T);\n [F,~,FMAP] = unique(sort(allF,2),'rows');\n M = sparse(FMAP,FMAP,repmat(vol/4,4,1),size(F,1), size(F,1));\n E = F;\n EMAP = FMAP;\n end\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/crouzeix_raviart_massmatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6942436293550293}} {"text": "function J=calcPolarConvJacob(zPolar,systemType,useHalfRange,lTx,lRx,M)\n%%CALCPOLARCONVJACOB Calculate the Jacobian for a monostatic or bistatic\n% range and polar angle measurement in 2D with respect to\n% Cartesian position. Atmospheric effects are ignored. This\n% type of Jacobian is useful when performing tracking using\n% Cartesian-converted measurements where the clutter density is\n% specified in the measurement coordinate system, not the\n% converted measurement coordinate system.\n%\n%INPUTS: zPolar A 2X1 point in polar coordinates in the format\n% [range;azimuth], where the angle is given in radians and the\n% range can be bistatic.\n% systemType An optional parameter specifying the axis from which the\n% azimuth angle is measured. It is assumed that the azimuth\n% angle is given in radians. Possible values are\n% 0 (The default if omitted) The azimuth angle is\n% counterclockwise from the x axis.\n% 1 The azimuth angle is measured clockwise from the y axis.\n% useHalfRange A boolean value specifying whether the bistatic range value\n% should be divided by two. This normally comes up\n% when operating in monostatic mode, so that the range reported is\n% a one-way range. The default if this parameter is not provided\n% is false.\n% lTx The 2X1 [x;y] location vector of the transmitter in Cartesian\n% coordinates. If this parameter is omitted or an empty matrix is\n% passed, then the transmitter is assumed to be at the origin.\n% lRx The 2X1 [x;y] location vector of the receiver in Cartesian\n% coordinates. If this parameter is omitted or an empty matrix is\n% passed, then the receiver is assumed to be at the origin.\n% M A 2X2 rotation matrices to go from the alignment of the global\n% coordinate system to that at the receiver. If omitted or an\n% empty matrix is passed, then it is assumed that the local\n% coordinate system is aligned with the global and M=eye(2,2)\n% --the identity matrix is used. \n%\n%OUTPUTS: J The 2X2 Jacobian matrix. Each row is a components of range, and\n% azimuth (in that order by row) with derivatives taken with\n% respect to [x,y] by column.\n%\n%This function converts the measurement into Cartesian coordinates and then\n%calls rangeGradient and polAngGradient.\n%\n%February 2017 David F.Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<6||isempty(M))\n M=eye(2,2); \nend\n\nif(nargin<5||isempty(lRx))\n lRx=zeros(2,1); \nend\n\nif(nargin<4||isempty(lTx))\n lTx=zeros(2,1); \nend\n\nif(nargin<3||isempty(useHalfRange))\n useHalfRange=true;\nend\n\nif(nargin<2||isempty(systemType))\n systemType=0;\nend\n\nx=pol2Cart(zPolar,systemType,useHalfRange,lTx,lRx,M);\n\nJ=zeros(2,2);\nJ(1,:)=rangeGradient(x,useHalfRange,lTx,lRx);\nJ(2,:)=polAngGradient(x,systemType,lRx);\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/Converted_Jacobians/calcPolarConvJacob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6942286039067473}} {"text": "function y = beta_pdf(x,a,b)\n%BETA_PDF Beta probability density function (pdf).\n%\n% Y = BETA_PDF(X,A,B) Returns the Beta pdf with\n% parameters A and B, at the values in X.\n%\n% The size of Y is the common size of the input arguments. A\n% scalar input functions as a constant matrix of the same size as\n% the other inputs.\n%\n% Default value for A and B is 1.\n\n% Copyright (c) 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 a = 1;\nend\n\nif nargin < 2;\n b = 1;\nend\n\nif nargin < 1, \n error('Requires at least one input argument.');\nend\n\ny=exp((a-1).*log(x) +(b-1).*log(1-x) -betaln(a,b));\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/beta_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021706, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6942286025283946}} {"text": "function result = lasso_cv(y, x, k, options)\n% -------------------------------------------------------------------------\n% function result = lasso_cv(y, x, k, options)\n% -------------------------------------------------------------------------\n% PURPOSE: fits the parameters of a linear model by using the lasso and \n% k-folds cross validation\n% -------------------------------------------------------------------------\n% INPUTS:\n% y: the values of the dependent variable\n% x: the values of the explanatory variables - constants will be \n% ignored\n% k: determine number of cross validation folds\n% n_div: \n% alignment: \n% cv_assignment: allows that the division within groups to be defined by\n% the user. cv_assignment is a nx1 vector where n is the\n% number of available observations. The second columns\n% defines which observations belongs to each group. \n% If this\n% parameter is used, k is ignored and set to be equal to the\n% number of unique elements of cv_assignment;\n% -------------------------------------------------------------------------\n% OUTPUTS:\n% a structure containing:\n% all the fields contained in the strucutre returned by the LASSO function\n% (see the lasso function help) plus the following fields:\n% result.CV.intercept : intercept for the model chosen by CV\n% result.CV.betas : coefficients for the model selected by CV\n% result.CV.fit : Fitted values for the cross-validated s\n% result.CV.residuals : Residuals for the cross-validated s\n% result.CV.SSR : Sum of squared residuals for the cross-validated\n% estimate\n% result.CV.MSE : minimum cross-validated MSE\n% result.CV.cv_assignment: a matrix determining which observations where \n% assigned to which CV groups\n% result.CV.k : number of CV folds\n% -------------------------------------------------------------------------\n% WARNING:\n% unless cv_assignment is provided, this function invokes ASSIGN_CV.\n% ASSIGN_CV calls randperm affecting the state of the random number gen.\n% -------------------------------------------------------------------------\n% Author: Guilherme V. Rocha\n% Department of Statistics\n% University of California, Berkeley\n% gvrocha@stat.berkeley.edu, gvrocha@gmail.com\n% 2006/09\n% -------------------------------------------------------------------------\n% See also: LASSO, ASSIGN_CV, RANDPERM\n\nif(nargin < 4)\n options = [];\nend;\n\nif(~isfield(options, 'alignment'))\n options.alignment = 'normalized_penalty';\nend;\nif(~isfield(options, 'cv_assignment'))\n assign_cv_flag = 1;\nelse\n assign_cv_flag = 0;\n cv_assignment = options.cv_assignment;\n k = length(unique(cv_assignment));\nend;\nif(~isfield(options, 'num_div'))\n options.num_div =100;\nend; \nn_div = options.num_div;\nalignment = options.alignment;\n\nn_obs = size(y, 1);\nmax_index = -Inf;\nif(assign_cv_flag)\n cv_assignment = assign_cv(n_obs, k);\nend;\n\nfor i = 1:k\n fit_indexes = find(cv_assignment~=i);\n y_fit = y(fit_indexes);\n x_fit = x(fit_indexes,:);\n res(i) = lasso_rocha(y_fit, x_fit, options);\n switch lower(alignment)\n case 'normalized_penalty'\n max_index = max(max_index, max(res(i).npenalty));\n case 'penalty'\n max_index = max(max_index, max(res(i).penalty));\n case 'lambda'\n max_index = max(max_index, max(res(i).lambda));\n end;\nend; \n\nindex_slices = 0:max_index/n_div:max_index;\n\nfor i = 1:k\n interpol = lasso_coefficients(res(i), index_slices, alignment);\n cv_indexes = find(cv_assignment==i);\n y_cv = y(cv_indexes);\n x_cv = x(cv_indexes,:);\n\n y_pred = lasso_predict(res(i), x_cv, index_slices, options);\n residuals = repmat(y_cv, 1, size(y_pred, 2)) - y_pred;\n if(size(residuals, 1)>1)\n MSE(i,:) = mean(residuals.^2);\n else\n MSE(i,:) = residuals.^2;\n end; \nend;\n\n[min_MSE, best_cv_MSE] = min(mean(MSE));\nbest_index = index_slices(best_cv_MSE);\nresult = lasso_rocha(y, x, options);\n\nresult.CV = lasso_coefficients(result, best_index, alignment);\nresult.CV.cv_index = best_cv_MSE;\nresult.CV.cv_assignment = cv_assignment;\nresult.CV.k = k;\nresult.CV.min_MSE = min_MSE;\nresult.CV.MSEs = MSE;\nresult.CV.path = lasso_coefficients(result, index_slices, alignment);\nresult.options = options;\nrm_fields = {'ny', 'nx', 'xtx', 'xty', 'beta', 'intercept', 'penalty', 'xtrs'};\nresult.CV.fold_results = rmfield(res, intersect(fieldnames(res), rm_fields));\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/lasso/lasso_cv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.694228597026434}} {"text": "function B = dtimatrix(bvalues,bvectors)\n% B = dtimatrix(bvalues,bvectors)\n%\n% Constructs a DTI design matrix from the bvalues and bvectors.\n% bvalues is a vector of length N\n% bvectors is a matrix either Nx3 or 3xN\n%\n% B will be N by 7\n% The 7th is the mean (all ones)\n% The tensor will be constructed using the following regressors\n% 1 2 3\n% 2 4 5\n% 3 5 6\n%\n% $Id: dtimatrix.m,v 1.2 2011/03/02 00:04:12 nicks Exp $\n\n%\n% dtimatrix.m\n%\n% Original Author: Doug Greve\n% CVS Revision Info:\n% $Author: nicks $\n% $Date: 2011/03/02 00:04:12 $\n% $Revision: 1.2 $\n%\n% Copyright \u00a9 2011 The General Hospital Corporation (Boston, MA) \"MGH\"\n%\n% Terms and conditions for use, reproduction, distribution and contribution\n% are found in the 'FreeSurfer Software License Agreement' contained\n% in the file 'LICENSE' found in the FreeSurfer distribution, and here:\n%\n% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense\n%\n% Reporting: freesurfer@nmr.mgh.harvard.edu\n%\n\n\nif(nargin ~= 2)\n fprintf('B = dtimatrix(bvalues,bvectors)\\n');\n return;\nend\n\nif(size(bvectors,2) ~= 3) bvectors = bvectors'; end\nif(size(bvectors,2) ~= 3) \n fprintf('ERROR: bvectors must be Nx3 or 3xN\\n');\n return;\nend\nNb = size(bvectors,1);\n\nif(Nb ~= length(bvalues))\n fprintf('ERROR: dimension mismatch between bvectors and bvalues\\n');\n return;\nend\n\nbvalues = bvalues(:);\n\nB = zeros(Nb,7);\nB(:,1) = bvalues .* bvectors(:,1).*bvectors(:,1);\nB(:,2) = 2 * bvalues .* bvectors(:,1).*bvectors(:,2);\nB(:,3) = 2 * bvalues .* bvectors(:,1).*bvectors(:,3);\nB(:,4) = bvalues .* bvectors(:,2).*bvectors(:,2);\nB(:,5) = 2 * bvalues .* bvectors(:,2).*bvectors(:,3);\nB(:,6) = bvalues .* bvectors(:,3).*bvectors(:,3);\nB(:,7) = 1;\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/freesurfer/dtimatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.6942214220350399}} {"text": "function [curve, params, errors, T] = fit_poly_to_fragment(fragment, order)\n%\n%[curve, params, errors] = fit_poly_to_fragment(fragment, order)\n% \n% Fit a polynomial curve of specified order to an edge fragment. A\n% fragment is simply an Nx2 vector of (x,y) coordinates.\n%\n% Can also return fit error and the polynomial parameters.\n%\n\n% Ensure there are enough points:\nif(isempty(fragment))\n error('Supplied fragment contains no points!');\nend\n\nN = size(fragment,1);\n\n% Reduce the order if not enough points are provided to fit the requested\n% order polynomial (e.g. we need N=4 points to fit a cubic, if only N=3 \n% points are provided, this will reduce the order to 2, thereby enabling\n% successful fitting of a quadratic)\nwhile( N < (order+1) )\n order = order-1;\nend\n \nt = linspace(0,1,N)';\n\nfit_normals = false;\n% if(nargin==2)\n% order = normal_angles;\n% fit_normals = false;\n% end\n\nT = ones(N,1);\nfor(i_order = 1:order)\n T = [t.^i_order T];\nend\n \nweights = ones(N, 1);\nweights(1) = N/4;\nweights(end) = N/4;\nif(~fit_normals)\n % Fit the polynomial so that it simply tries to pass through the\n % fragment's vertex coordinates.\n params = (T .* repmat(weights, [1, order+1])) \\ (fragment .* repmat(weights, [1, 2]));\n \n% % Constrained least squares to get the start and end points to exactly\n% % match up to the input coordinates:\n% for(i=1:2)\n% params(:,i) = lsqlin(T(2:end-1,:), fragment(2:end-1,i), ...\n% T([1 end],:), fragment([1 end],i),T([1 end],:), fragment([1 end],i));\n% end\nelse\n error(['Um, actually, trying to constrain the slopes this way will NOT ' ...\n 'work. It is not linear because we do not know the length of the ' ...\n 'normal vectors, only the direction.']);\n \n% params = T \\ fragment;\n% L = L_helper(params, t, order);\n% \n% % Fit the polynomial so that it tries to pass through the coordinates of the\n% % input fragment AND tries to have slope matching the orientations of\n% % each vertex in the fragment. \n% T_orient = [ones(N,1) zeros(N,1)];\n% for(i_order = 1:(order-1))\n% T_orient = [(i_order+1)*t.^i_order T_orient];\n% end\n% \n% for(i=1:100)\n% TT = [blkdiag(T,T); blkdiag(-T_orient, T_orient)];\n% \n% params = TT \\ [fragment(:); L.*sin(normal_angles); L.*cos(normal_angles)];\n% params = reshape(params, [order+1 2]);\n% \n% L = L_helper(params, t, order);\n% end\n \n \nend\n\ncurve = T*params;\nif(nargout>=3)\n errors = abs(curve - fragment);\nend\n\nreturn;\n\n\n\nfunction L = L_helper(params, t, order)\n\ndx = params(end-1,1);\ndy = params(end-1,2);\nfor(i_order = 2:order)\n dx = dx + i_order*params(end-i_order,1)*t.^(i_order-1);\n dy = dy + i_order*params(end-i_order,2)*t.^(i_order-1);\nend\n\nL = sqrt(dx.^2 + dy.^2);\nreturn;", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/rigor/rigor_src/extern_src/segmentation/stein_boundaryprocessing/fit_poly_to_fragment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6942214191470599}} {"text": "function [ fxx, fxy, fyy ] = f03_f2 ( n, x, y )\n\n%*****************************************************************************80\n%\n%% F03_F2 returns second derivatives of function 3.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 January 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(N,1), Y(N,1), the evalution points.\n%\n% Output, real FXX(N,1), FXY(N,1), FYY(N,1), second derivatives.\n%\n t1(1:n,1) = 5.4 * y(1:n,1);\n t2(1:n,1) = 1.0 + ( 3.0 * x(1:n,1) - 1.0 ).^2;\n\n fxx(1:n,1) = 3.0 * ( 1.25 + cos ( t1(1:n,1) ) ) .* ( 3.0 * t2(1:n,1) - 4.0 ) ...\n ./ ( t2(1:n,1).^3 );\n fxy(1:n,1) = 5.4 * ( 3.0 * x(1:n,1) - 1.0 ) .* sin ( t1(1:n,1) ) ...\n ./ ( t2(1:n,1) .* t2(1:n,1) );\n fyy(1:n,1) = - 4.86 * cos ( t1(1:n,1) ) ./ t2(1:n,1);\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_interp_2d/f03_f2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.694221417000562}} {"text": "function [pc,r]=circumcenter(p,t)\n\n% Copyright (C) 2004-2006 Per-Olof Persson. See COPYRIGHT.TXT for details.\n\nnt=size(t,1);\npc=zeros(nt,2);\nr=zeros(nt,1);\n\nfor it=1:nt\n ct=t(it,:);\n dp1=p(ct(2),:)-p(ct(1),:);\n dp2=p(ct(3),:)-p(ct(1),:);\n \n mid1=(p(ct(2),:)+p(ct(1),:))/2;\n mid2=(p(ct(3),:)+p(ct(1),:))/2;\n \n s=[-dp1(2),dp2(2);dp1(1),-dp2(1)]\\[-mid1+mid2]';\n \n cpc=mid1+s(1)*[-dp1(2),dp1(1)];\n cr=norm(p(ct(1),:)-cpc);\n \n pc(it,:)=cpc;\n r(it,1)=cr;\nend\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/mesh/distmeshModified/circumcenter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6942214080438291}} {"text": "function ncc_set_test ( )\n\n%*****************************************************************************80\n%\n%% NCC_SET_TEST tests NCC_SET.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 24 April 2015\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'NCC_SET_TEST\\n' );\n fprintf ( 1, ' NCC_SET sets up a Newton-Cotes Closed quadrature rule;\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Index X W\\n' );\n fprintf ( 1, '\\n' );\n\n for n = 1 : 10\n\n [ x, w ] = ncc_set ( n );\n\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n fprintf ( 1, ' %2d %12g %12g\\n', i, x(i), w(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/quadrule/ncc_set_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.6942179821268277}} {"text": "function beale_test ( )\n\n%*****************************************************************************80\n%\n%% BEALE_TEST works with the Beale function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BEALE_TEST:\\n' );\n fprintf ( 1, ' Test COMPASS_SEARCH with the Beale function.\\n' );\n m = 2;\n delta_tol = 0.00001;\n delta = 0.1;\n k_max = 20000;\n\n x = [ 1.0, 1.0 ];\n r8vec_print ( m, x, ' Initial point X0:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X0) = %g\\n', beale ( m, x ) );\n\n [ x, fx, k ] = compass_search ( @beale, m, x, delta_tol, delta, k_max );\n r8vec_print ( m, x, ' Estimated minimizer X1:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X1) = %g, number of steps = %d\\n', fx, k );\n%\n% Repeat with more difficult start.\n%\n x = [ 1.0, 4.0 ];\n r8vec_print ( m, x, ' Initial point X0:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X0) = %g\\n', beale ( m, x ) );\n\n [ x, fx, k ] = compass_search ( @beale, m, x, delta_tol, delta, k_max );\n r8vec_print ( m, x, ' Estimated minimizer X1:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X1) = %g, number of steps = %d\\n', fx, k );\n%\n% Demonstrate correct minimizer.\n%\n x = [ 3.0, 0.5 ];\n r8vec_print ( m, x, ' Correct minimizer X*:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X*) = %g\\n', beale ( m, x ) );\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/compass_search/beale_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.6941177736921619}} {"text": "function flag = isodd(n)\n%ISODD returns true if the input is odd.\n\nflag = mod(n,2);\n\n% Copyright 2002 - 2009 The MathWorks, Inc.", "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/1713-three-dimensional-reconstruction-from-planar-slices/isodd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.6941177553729609}} {"text": "function[num,a,b]=blocknum(x,delta)\n%BLOCKNUM Numbers the contiguous blocks of an array.\n%\n% Suppose X is a column vector which contains blocks of identical\n% values, e.g. X=[0 0 0 1 1 3 2 2 2]';\n%\n% N=BLOCKNUM(X) gives each contiguous block of identical values a\n% unique number, in order beginning with 1. Each elements of N\n% specifies the number of the block to which the corresponding\n% element of X belongs.\n%\n% In the above example, N=[1 1 1 2 2 3 4 4 4]';\n% \n% [N,A,B]=BLOCKNUM(X) also returns arrays A and B which are indices\n% into the first and last point, respectively, of each block. In\n% the above example, A=[1 4 6 7]' and B=[3 5 6 9]';\n%\n% [...]=BLOCKNUM(X,D) defines the junction between two blocks as\n% locations where ABS(DIFF(X))>D. Thus D=1 is a 'rate of change'\n% definition, and X=[1 2 3 5 6 10 16 17 18]'; will yield the same \n% result for N as in the previous example.\n%\n% See also BLOCKLEN.\n%\n% Usage: num=blocknum(x);\n% [num,a,b]=blocknum(x);\n% _________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information \n% (C) 2000--2014 J.M. Lilly --- type 'help jlab_license' for details\n \nif strcmpi(x,'--t')\n blocknum_test;return;\nend\n\nif nargin==1\n delta=0;\nend\n\ndx=diff(x);\nindex=find(abs(dx)>delta);\nnum=zeros(size(x));\nif ~isempty(index)\n num(index+1)=1;\nend\nnum(1)=1;\nnum=cumsum(num);\n\n\nif nargout>=2\n a=[1;find(diff(num)~=0)+1];\nend\nif nargout>=3\n b=[find(diff(num)~=0);length(num)];\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction[]=blocknum_test\nx= [0 0 0 1 1 3 2 2 2]';\ny= [1 1 1 2 2 3 4 4 4]';\n\nreporttest('BLOCKNUM with D==0',all(y==blocknum(x)))\n\nx=[1 2 3 5 6 10 16 17 18]';\nreporttest('BLOCKNUM with D==1',all(y==blocknum(x,1)))\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/blocknum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.6941177536748024}} {"text": "function [u,x]=initialvalues(uflux,a,b,init_f,N);\n%\n% Approximates the function init_f on the interval [a b] by a piecewise\n% constant function taking values in the set {uflux}.\n% The output is the location of the discontinuities x and u such that \n% the discontinuity between u(i-1) and u(i) is located at x(i).\n% \nif nargin<5,\n N=1/(uflux(2)-uflux(1));\nend;\nx=linspace(a,b,N);\nxf=0.5*(x(2:N)+x(1:N-1));\nu1=feval(init_f,xf);\nA=ones(size(u1))'*uflux;\nB=ones(size(uflux))'*u1;\n[m ind]=min(abs(A'-B));\nh=uflux(ind);\nx=x(2:N-1);\nd=diff(h);\nind=d~=0;\n[i s]=find(ind);\nu=[h(s) h(N-1)];\nx=x(s);\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/OperatorSplitting/AppendixA/Scalar_Fronttracking/initialvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.6940902716341505}} {"text": "function Y = sl2dpca_apply(Mm, PL, PR, data, matsiz, n)\n%SL2DPCA_APPLY Applies 2D PCA onto a set of matrices to extract features\n%\n% $ Syntax $\n% - Y = sl2dpca_apply(Mm, PL, PR, data, matsiz, n)\n%\n% $ Description $\n% - Mm: the mean matrix\n% - PL: the left projection matrix\n% - PR: the right projection matrix\n% - data: the matrix samples or the cell array of filenames\n% - matsiz: the original matrix size\n% - n: the number of samples\n% - Y: the extracted 2D features\n%\n% $ Description $\n% - Y = sl2dpca_apply(data, Mm, PL, PR) extracts 2D features for \n% the matrices given in data, in either a 3D array or a set of\n% array filenames. Suppose the original matrix size is d1 x d2,\n% PL be d1 x k1, PR be d2 x k2, then the feature matrix would be\n% of size k1 x k2. Y is a k1 x k2 x n array.\n%\n% $ History $\n% - Created by Dahua Lin, on Jul 31st, 2006\n%\n\n%% Parse and verify input arguments\n\nif nargin < 6\n raise_lackinput('sl2dpca_apply', 6);\nend\n\nmatsiz = matsiz(:)';\nif length(matsiz) ~= 2\n error('sltoolbox:invalidarg', ...\n 'matsiz should be a 2-elem vector');\nend\n\nif ~isequal(size(Mm), matsiz)\n error('sltoolbox:sizmismatch', ...\n 'the sample size does not match the model');\nend\nd1 = matsiz(1);\nd2 = matsiz(2);\n\nif size(PL, 1) ~= d1 || size(PR, 1) ~= d2\n error('sltoolbox:sizmismatch', ...\n 'the size of projection matrices are illegal');\nend\n\n%% Compute\n\nif isnumeric(data)\n \n if size(data, 3) ~= n\n error('sltoolbox:sizmismatch', ...\n 'The number of samples is not as specified');\n end\n \n Y = computeY(data, Mm, PL, PR);\n \nelseif iscell(data)\n \n Y = zeros(size(PL, 2), size(PR, 2), n);\n \n nfiles = length(data);\n cf = 0;\n for i = 1 : nfiles\n curdata = slreadarray(data{i});\n curn = size(curdata, 3);\n Y(:,:,cf+1:cf+curn) = computeY(curdata, Mm, PL, PR);\n cf = cf + curn;\n end\n \nelse\n error('sltoolbox:invalidarg', ...\n 'data should be a numeric array or a cell array of filenames'); \n \nend\n\n\n%% Core compute function\n\nfunction Y = computeY(X, Mm, PL, PR)\n\nn = size(X, 3);\nY = zeros(size(PL, 2), size(PR, 2), n);\nPLT = PL';\n\nfor i = 1 : n\n Y(:,:,i) = PLT * (X(:,:,i) - Mm) * PR;\nend\n\n\n\n\n\n \n\n\n\n\n", "meta": {"author": "lmthang", "repo": "nmt.hybrid", "sha": "50d5c025f18ed280ff0fd2e2adce327f4170a2c3", "save_path": "github-repos/MATLAB/lmthang-nmt.hybrid", "path": "github-repos/MATLAB/lmthang-nmt.hybrid/nmt.hybrid-50d5c025f18ed280ff0fd2e2adce327f4170a2c3/code/wordsim/code/sltoolbox_r101/sltoolbox_r101/sltoolbox/subspace_ex/sl2dpca_apply.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6940902563179006}} {"text": "function [h,g,a,info]=wfilt_remez(L,K,B)\n%WFILT_REMEZ Filters designed using Remez exchange algorithm\n% Usage: [h,g,a]=wfilt_remez(L,K,B)\n%\n% Input parameters:\n% L : Length of the filters.\n% K : Degree of flatness (regularity) at $z=-1$. \n% B : Normalized transition bandwidth.\n%\n% `[h,g,a]=wfilt_remez(L,K,B)` calculates a set of wavelet filters. \n% Regularity, frequency selectivity, and length of the filters can be\n% controlled by *K*, *B* and *L* parameters respectivelly.\n%\n% The filter desigh algorithm is based on a Remez algorithm and a \n% factorization of the complex cepstrum of the polynomial.\n%\n% Examples:\n% ---------\n% :::\n%\n% wfiltinfo('remez50:2:0.1');\n%\n% References: rioul94remez\n\n% Original copyright goes to:\n% Copyright (C) 1994, 1995, 1996, by Universidad de Vigo \n% Author: Jose Martin Garcia\n% e-mail: Uvi_Wave@tsc.uvigo.es\n\nif(nargin<3)\n error('%s: Too few input parameters.',upper(mfilename)); \nend\n\ncomplainif_notposint(L,'L',mfilename);\ncomplainif_notposint(L,'K',mfilename);\n\nif B>0.2\n error(['%s: Bandwidth of the transition band should not be',...\n ' bigger than 0.2.'],upper(mfilename));\nend\n\npoly=remezwav(L,K,B);\nrh=fc_cceps(poly);\n\ng{1} = flipud(rh(:));\ng{2} = -(-1).^(1:length(rh)).'.*flipud(g{1});\n\n% Default offset\nd = [0,0];\n % Do a filter alignment according to \"center of gravity\"\n d(1) = -floor(sum((1:L)'.*abs(g{1}).^2)/sum(abs(g{1}).^2));\n d(2) = -floor(sum((1:L)'.*abs(g{2}).^2)/sum(abs(g{2}).^2));\n if rem(d(1)-d(2),2)==1\n % Shift d(2) just a bit\n d(2) = d(2) + 1;\n end\n\n\ng = cellfun(@(gEl,dEl) struct('h',gEl,'offset',dEl),g,num2cell(d),...\n 'UniformOutput',0);\nh = g;\n\na= [2;2];\ninfo.istight = 1;\n\nfunction [p,r]=remezwav(L,K,B)\n\n%REMEZWAV P=REMEZWAV(L,K,B) gives impulse response of maximally\n%\t frequency selective P(z), product filter of paraunitary\n%\t filter bank solution H(z) of length L satisfying K flatness\n%\t constraints (wavelet filter), with normalized transition\n%\t bandwidth B (optional argument if K==L/2).\n% \n%\t [P,R]=REMEZWAV(L,K,B) also gives the roots of P(z) which can\n%\t be used to determine H(z).\n%\n%\t See also: REMEZFLT, FC_CCEPS.\n%\n%\t References: O. Rioul and P. Duhamel, \"A Remez Exchange Algorithm\n%\t\t\t for Orthonormal Wavelets\", IEEE Trans. Circuits and\n%\t\t\t Systems - II: Analog and Digital Signal Processing,\n%\t\t\t 41(8), August 1994\n% \n% Author: Olivier Rioul, Nov. 1, 1992 (taken from the\n%\t\tabove reference)\n% Modified by: Jose Martin Garcia\n% e-mail: Uvi_Wave@tsc.uvigo.es\n%--------------------------------------------------------\n\n\ncomputeroots=(nargout>1);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%% STEP 1 %%%%%%%%%%%%%%%%%%%%%%%%%%%\nif rem(L,2), error('L must be even'); end\nif rem(L/2-K,2), K=K+1; end\nN=L/2-K;\n%%%%%%%%%%%%%%%%%%%%%%%%%% STEP 2 %%%%%%%%%%%%%%%%%%%%%%%%%%\n% Daubechies solution\n% PK(z)=z^(-2K-1))+AK(z^2)\nif K==0, AK=0;\nelse\n binom=pascal(2*K,1);\n AK=binom(2*K,1:K)./(2*K-1:-2:1);\n AK=[AK AK(K:-1:1)];\n AK=AK/sum(AK);\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%% STEP 2' %%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Daubechies factor\n% PK(z)=((1+z^(-1))/2)^2*K QK(z)\nif computeroots && K>0\n QK=binom(2*K,1:K);\n QK=QK.*abs(QK);\n QK=cumsum(QK);\n QK=QK./abs(binom(2*K-1,1:K));\n QK=[QK QK(K-1:-1:1)];\n QK=QK/sum(QK)*2;\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%% STEP 3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% output Daubechies solution PK(z)\nif K==L/2\n p=zeros(1,2*L-1);\n p(1:2:2*L-1)=AK; p(L)=1;\n if computeroots\n r=[roots(QK); -ones(L,1)];\n end\n return\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%% STEP 4 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Daubechies polinomial\n% PK(x)=1+x*DK(x^2)\nif K==0, DK=0;\nelse\n binom=pascal(K,1);\n binom=binom(K,:);\n DK=binom./(1:2:2*K-1);\n DK=fliplr(DK)/sum(DK);\nend\n\nwp=(1/2-B)*pi; % cut-off frequency\ngridens=16*(N+1); % grid density\nfound=0; % boolean for Remez loop\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% STEP I %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Initial estimate of yk\na=min(4,K)/10;\nyk=linspace(0,1-a,N+1);\nyk=(yk.^2).*(3+a-(2+a)*yk);\nyk=1-(1-yk)*(1-cos(wp)^2);\nykold=yk;\n\niter=0;\nwhile 1 % REMEZ LOOP\niter=iter+1;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% STEP II %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Compute delta\nWyk=sqrt(yk).*((1-yk).^K);\nDyk=(1-sqrt(yk).*polyval(DK,yk))./Wyk;\nfor k=1:N+1\n dy=yk-yk(k); dy(k)=[];\n dy=dy(1:N/2).*dy(N:-1:N/2+1);\n Lk(k)=prod(dy);\nend\ninvW(1:2:N+1)=2./Wyk(1:2:N+1);\ndelta=sum(Dyk./Lk)/sum(invW./Lk);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% STEP III %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% compute R(y) on fine grid\nRyk=Dyk-delta.*invW; Ryk(N+1)=[];\nLk=(yk(1:N)-yk(N+1))./Lk(1:N);\ny=linspace(cos(wp)^2,1-K*1e-7,gridens);\nyy=ones(N,1)*y-yk(1:N)'*ones(1,gridens);\n% yy contain y-yk on each line\nind=find(yy==0); % avoid division by 0\nif ~isempty(ind)\n yy(ind)=1e-30*ones(size(ind));\nend\nyy=1./yy;\nRy=((Ryk.*Lk)*yy)./(Lk*yy);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% STEP IV %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% find next yk\nEy=1-delta-sqrt(y).*(polyval(DK,y)+((1-y).^K).*Ry);\nk=find(abs(diff(sign(diff(Ey))))==2)+1;\n% N extrema\nif length(k)>N\n% may happen if L and K are large \n k=k(1:N);\nend\nyk=[yk(1) y(k)];\n% N+1 extrema including wp\nif K==0, yk=[yk 1]; end\n% extrema at y==1 added\nif all(yk==ykold), break; end\nykold=yk;\n\nend % REMEZ LOOP\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% STEP A %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% compute impulse response\nw=(0:2*N-2)*pi/(2*N-1);\ny=cos(w).^2;\nyy=ones(N,1)*y-yk(1:N)'*ones(1,2*N-1);\nind=find(yy==0);\nif ~isempty(ind)\n yy(ind)=1e-30*ones(size(ind));\nend\nyy=1./yy;\nRy=((Ryk.*Lk)*yy)./(Lk*yy);\nRy(2:2:2*N-2)=-Ry(2:2:2*N-2);\nr=Ry*cos(w'*(2*(0:N-1)+1));\n% partial real IDFT done\nr=r/(2*N-1);\nr=[r r(N-1:-1:1)];\np1=[r 0]+[0 r];\npp=p1; % save p1 for later use\nfor k=1:2*K\n p1=[p1 0]-[0 p1];\nend\nif rem(K,2), p1=-p1; end\np1=p1/2^(2*K+1);\np1(N+1:N+2*K)=p1(N+1:N+2*K)+AK;\n% add Daubechies response:\np(1:2:2*L-1)=p1; p(L)=1;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% STEP A' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% compute roots\nif computeroots\n Q(1:2:2*length(pp)-1)=pp;\n for k=1:2*K\n Q=[Q 0]-[0 Q];\n end\n if rem(K,2), Q=-Q; end\n Q=Q/2;\n if K>0 % add Daubechies factor QK\n Q(2*N+1:L-1)=Q(2*N+1:L-1)+QK;\n else\n Q(L)=1;\n end\n r=[roots(Q); -ones(2*K,1)];\nend\n\n\n\nfunction h=fc_cceps(poly,ro)\n\n%FC_CCEPS Performs a factorization using complex cepstrum.\n%\n%\t H = FC_CCEPS (POLY,RO) provides H that is the spectral\n%\t factor of a FIR transfer function POLY(z) with non-negative \n%\t frequency response. This methode let us obtain lowpass\n%\t filters of a bank structure without finding the POLY zeros.\n%\t The filter obtained is minimum phase (all zeros are inside\n%\t unit circle).\n%\t\t\n%\t RO is a parameter used to move zeros out of unit circle.\n%\t It is optional and the default value is RO=1.02.\n%\n%\t See also: INVCCEPS, MYCCEPS, REMEZWAV.\n%\n%\t References: P.P Vaidyanathan, \"Multirate Systems and Filter\n%\t\t\t Banks\", pp. 849-857, Prentice-Hall, 1993\n\n\n%--------------------------------------------------------\n% Copyright (C) 1994, 1995, 1996, by Universidad de Vigo \n% \n% \n% Uvi_Wave is free software; you can redistribute it and/or modify it \n% under the terms of the GNU General Public License as published by the \n% Free Software Foundation; either version 2, or (at your option) any \n% later version. \n% \n% Uvi_Wave is distributed in the hope that it will be useful, but WITHOUT \n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or \n% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License \n% for more details. \n% \n% You should have received a copy of the GNU General Public License \n% along with Uvi_Wave; see the file COPYING. If not, write to the Free \n% Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. \n% \n% Author: Jose Martin Garcia\n% e-mail: Uvi_Wave@tsc.uvigo.es\n%--------------------------------------------------------\n\nif nargin < 2\n\tro=1.02;\nend\n\nL=4096; % number points of fft.\n\nN=(length(poly)-1)/2;\n\n%% Moving zeros out of unit circle\nroo=(ro).^[0:2*N];\ng=poly./roo;\n\n%% Calculate complex cepstrum of secuence g\nghat=mycceps(g,L);\n\n%% Fold the anticausal part of ghat, add it to the causal part and divide by 2\ngcausal=ghat(1 : L/2);\ngaux1=ghat(L/2+1 : L);\ngaux2=gaux1(L/2 :-1: 1);\ngantic=[0 gaux2(1 : L/2-1)];\n\nxhat=0.5*(gcausal+gantic);\n\n%% Calculate cepstral inversion\nh=invcceps(xhat,N+1);\n \n%% Low-pass filter has energie sqrt(2)\nh=h*sqrt(2)/sum(h);\n\n\nfunction x=invcceps(xhat,L)\n\n%INVCCEPS Complex cepstrum Inversion\n%\n%\t X= INVCCEPS (CX,L) recovers X from its complex cepstrum sequence \n%\t CX. X has to be real, causal, and stable (X(z) has no zeros \n%\t outside unit circle) and x(0)>0. L is the length of the \n%\t recovered secuence.\n%\n%\t See also: MYCCEPS, FC_CCEPS, REMEZWAV.\n%\n%\t References: P.P Vaidyanathan, \"Multirate Systems and Filter\n%\t\t\t Banks\", pp. 849-857, Prentice-Hall, 1993\n\n\n%--------------------------------------------------------\n% Copyright (C) 1994, 1995, 1996, by Universidad de Vigo \n% \n% \n% Uvi_Wave is free software; you can redistribute it and/or modify it \n% under the terms of the GNU General Public License as published by the \n% Free Software Foundation; either version 2, or (at your option) any \n% later version. \n% \n% Uvi_Wave is distributed in the hope that it will be useful, but WITHOUT \n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or \n% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License \n% for more details. \n% \n% You should have received a copy of the GNU General Public License \n% along with Uvi_Wave; see the file COPYING. If not, write to the Free \n% Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. \n% \n% Author: Jose Martin Garcia\n% e-mail: Uvi_Wave@tsc.uvigo.es\n%--------------------------------------------------------\n\n\nx=zeros(1,L);\n\n%% First point of x\nx(1)=exp(xhat(1));\n\n%% Recursion to obtain the other point of x\nfor muestra=1:L-1\n for k=1:muestra\n\tx(muestra+1)=x(muestra+1)+k/muestra*xhat(k+1)*x(muestra-k+1);\n end\nend\n\n\nfunction xhat=mycceps(x,L)\n\n%MYCCEPS Complex Cepstrum\n%\n%\t CX = MYCCEPS (X,L) calculates complex cepstrum of the\n%\t real sequence X. L is the number of points of the fft\n%\t used. L is optional and its default value is 1024 points.\n%\n%\t See also: FC_CEPS, INVCCEPS, REMEZWAV.\n\n\n%--------------------------------------------------------\n% Copyright (C) 1994, 1995, 1996, by Universidad de Vigo \n% \n% \n% Uvi_Wave is free software; you can redistribute it and/or modify it \n% under the terms of the GNU General Public License as published by the \n% Free Software Foundation; either version 2, or (at your option) any \n% later version. \n% \n% Uvi_Wave is distributed in the hope that it will be useful, but WITHOUT \n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or \n% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License \n% for more details. \n% \n% You should have received a copy of the GNU General Public License \n% along with Uvi_Wave; see the file COPYING. If not, write to the Free \n% Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. \n% \n% Author: Jose Martin Garcia\n% e-mail: Uvi_Wave@tsc.uvigo.es\n%--------------------------------------------------------\n\nif nargin < 2\n L=1024;\nend\n\nH = fft(x,L);\n\n%% H must not be zero\nind=find(abs(H)==0);\nif length(ind) > 0 \n H(ind)=H(ind)+1e-25;\nend\n\nlogH = log(abs(H))+sqrt(-1)*rcunwrap(angle(H));\n\nxhat = real(ifft(logH));\n\n\nfunction y = rcunwrap(x)\n%RCUNWRAP Phase unwrap utility used by CCEPS.\n%\tRCUNWRAP(X) unwraps the phase and removes phase corresponding\n%\tto integer lag. See also: UNWRAP, CCEPS.\n\n%\tAuthor(s): L. Shure, 1988\n%\t\t L. Shure and help from PL, 3-30-92, revised\n%\tCopyright (c) 1984-94 by The MathWorks, Inc.\n% $Revision: 1.4 $ $Date: 1994/01/25 17:59:42 $\n\nn = max(size(x));\ny = unwrap(x);\nnh = fix((n+1)/2);\ny(:) = y(:)' - pi*round(y(nh+1)/pi)*(0:(n-1))/nh;\n\n\n\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/wavelets/wfilt_remez.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6940902520909858}} {"text": "function p = predictOneVsAll(all_theta, X)\n%PREDICT Predict whether the label is 0 or 1 using learned logistic \n%regression parameters all_theta\n% p = PREDICT(all_theta, X) computes the predictions for X using a \n% threshold at 0.5 (i.e., if sigmoid(all_theta'*x) >= 0.5, predict 1)\n\nm = size(X, 1);\nnum_labels = size(all_theta, 1);\n\n% You need to return the following variables correctly \np = zeros(size(X, 1), 1);\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters (one-vs-all).\n% You should set p to a vector of predictions (from 1 to\n% num_labels).\n%\n% Hint: This code can be done all vectorized using the max function.\n% In particular, the max function can also return the index of the \n% max element, for more information see 'help max'. If your examples \n% are in rows, then, you can use max(A, [], 2) to obtain the max \n% for each row.\n% \n\n% train each row for all classes and keep the label with the highest probability\nhtheta = X * all_theta';\n[temp, p] = max(htheta, [], 2);\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/predictOneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.6940829250114011}} {"text": "function [R, scale]=arqr(v, p, mcor)\n%ARQR\tQR factorization for least squares estimation of AR model.\n%\n% [R, SCALE]=ARQR(v,p,mcor) computes the QR factorization needed in\n% the least squares estimation of parameters of an AR(p) model. If\n% the input flag mcor equals one, a vector of intercept terms is\n% being fitted. If mcor equals zero, the process v is assumed to have\n% mean zero. The output argument R is the upper triangular matrix\n% appearing in the QR factorization of the AR model, and SCALE is a\n% vector of scaling factors used to regularize the QR factorization.\n%\n% ARQR is called by ARFIT. \n%\n% See also ARFIT.\n\n% Modified 29-Dec-99\n% Author: Tapio Schneider\n% tapio@gps.caltech.edu\n\n % n: number of time steps; m: dimension of state vectors\n [n,m] = size(v); \n\n ne = n-p; % number of block equations of size m\n np = m*p+mcor; % number of parameter vectors of size m\n\n % If the intercept vector w is to be fitted, least squares (LS)\n % estimation proceeds by solving the normal equations for the linear\n % regression model\n %\n % v(k,:)' = Aaug*u(k,:)' + noise(C)\n %\n % with Aaug=[w A] and `predictors' \n %\n % u(k,:) = [1 v(k-1,:) ... v(k-p,:)]. \n %\n % If the process mean is taken to be zero, the augmented coefficient\n % matrix is Aaug=A, and the regression model\n %\n % u(k,:) = [v(k-1,:) ... v(k-p,:)]\n %\n % is fitted. \n % The number np is the dimension of the `predictors' u(k). \n\n % Assemble the data matrix K (of which a QR factorization will be computed)\n K = zeros(ne,np+m); % initialize K\n if (mcor == 1)\n % first column of K consists of ones for estimation of intercept vector w\n K(:,1) = ones(ne,1);\n end\n \n % Assemble `predictors' u in K \n for j=1:p\n K(:, mcor+m*(j-1)+1:mcor+m*j) = [v(p-j+1:n-j, :)];\n end\n % Add `observations' v (left hand side of regression model) to K\n K(:,np+1:np+m) = [v(p+1:n, :)];\n \n % Compute regularized QR factorization of K: The regularization\n % parameter delta is chosen according to Higham's (1996) Theorem\n % 10.7 on the stability of a Cholesky factorization. Replace the\n % regularization parameter delta below by a parameter that depends\n % on the observational error if the observational error dominates\n % the rounding error (cf. Neumaier, A. and T. Schneider, 2001:\n % \"Estimation of parameters and eigenmodes of multivariate\n % autoregressive models\", ACM Trans. Math. Softw., 27, 27--57.).\n q = np + m; % number of columns of K\n delta = (q^2 + q + 1)*eps; % Higham's choice for a Cholesky factorization\n scale = sqrt(delta)*sqrt(sum(K.^2)); \n R = triu(qr([K; diag(scale)]));", "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/174-arfit/arqr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.6940829152626058}} {"text": "function msm_to_mm_test03 ( )\n\n%*****************************************************************************80\n%\n%% MSM_TO_MM_TEST03 tests MSM_TO_MM_ARRAY_COMPLEX_SKEWSYMMETRIC.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 November 2008\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MSM_TO_MM_TEST03\\n' );\n fprintf ( 1, ' Convert an MSM to MM array complex skew-symmetric format.\\n' );\n\n output_filename = 'msm_to_mm_test03.mm';\n a = c8mat_indicator ( 4, 4 );\n for j = 1 : 4\n a(j,j) = 0.0;\n for i = j + 1 : 4\n a(i,j) = - a(j,i);\n end\n end\n%\n% Have MSM_TO_MM write the matrix to a file.\n%\n msm_to_mm ( output_filename, a, 'array', 'complex', 'skew-symmetric' );\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/msm_to_mm/msm_to_mm_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.6940532060777457}} {"text": "function c = tapas_gaussian_obs_config\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Contains the configuration for the Gaussian noise observation model for continuous responses\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% The Gaussian noise observation model assumes that responses have a Gaussian distribution around\n% the inferred mean of the relevant state. The only parameter of the model is the noise variance\n% (NOT standard deviation) zeta.\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2012-2013 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n\n% Config structure\nc = struct;\n\n% Model name\nc.model = 'tapas_gaussian_obs';\n\n% Sufficient statistics of Gaussian parameter priors\n%\n% Zeta\nc.logzemu = log(0.005);\nc.logzesa = 0.1;\n\n% Gather prior settings in vectors\nc.priormus = [\n c.logzemu,...\n ];\n\nc.priorsas = [\n c.logzesa,...\n ];\n\n% Model filehandle\nc.obs_fun = @tapas_gaussian_obs;\n\n% Handle to function that transforms observation parameters to their native space\n% from the space they are estimated in\nc.transp_obs_fun = @tapas_gaussian_obs_transp;\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_gaussian_obs_config.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6940451659438841}} {"text": "function dUpsilonS = lfmaaGradientSigmaUpsilonMatrix(gamma, sigma2, ...\n t1, t2, mode)\n\n% LFMAAGRADIENTSIGMAUPSILONMATRIX Gradient of upsilon matrix aa wrt sigma\n% FORMAT\n% DESC computes the gradient wrt sigma of a portion of the LFMAA kernel.\n% ARG gamma : Gamma value for system.\n% ARG sigma2 : length scale of latent process.\n% ARG t1 : first time input (number of time points x 1).\n% ARG t2 : second time input (number of time points x 1).\n% ARG mode : operation mode, according to the derivative (mode 0,\n% derivative wrt t1, mode 1 derivative wrt t2)\n% RETURN upsilon : result of this subcomponent of the kernel for the given values.\n%\n% COPYRIGHT : Mauricio Alvarez, 2010\n%\n% SEEALSO : lfmaaComputeUpsilonMatrix.m\n\n% KERN\n\nsigma = sqrt(sigma2);\ngridt1 = repmat(t1, 1, length(t2));\ngridt2 = repmat(t2', length(t1), 1);\ntimeGrid = gridt1 - gridt2;\n\ndUpsilon = lfmapGradientSigmaUpsilonMatrix(gamma, sigma2, t1, t2, 1-mode);\n\nif mode == 0\n dUpsilonS = (gamma^2)*dUpsilon - (2/(sqrt(pi)*sigma))*exp(-(timeGrid.^2)./sigma2).* ...\n ((2/sigma2- (2*timeGrid/sigma2).^2).*((gamma + 2*timeGrid/sigma2).* ...\n (1/sigma - 2*(timeGrid.^2)/sigma^3) + 4*timeGrid/sigma^3) ...\n - (gamma + 2*timeGrid/sigma2).*(-4/sigma^3 + 16*timeGrid.^2/sigma^5)) ...\n - (16/(sqrt(pi)*sigma^6))*timeGrid.*exp(-(timeGrid.^2)./sigma2).* ...\n (5 - 2*timeGrid.^2/sigma2);\nelse\n dUpsilonS = (gamma^2)*dUpsilon - (2/(sqrt(pi)*sigma))*exp(-(timeGrid.^2)./sigma2).* ...\n ((2/sigma2- (2*timeGrid/sigma2).^2).*((gamma + 2*timeGrid/sigma2).* ...\n (1/sigma - 2*(timeGrid.^2)/sigma^3) + 4*timeGrid/sigma^3) ...\n - (gamma + 2*timeGrid/sigma2).*(-4/sigma^3 + 16*timeGrid.^2/sigma^5)) ...\n - (16/(sqrt(pi)*sigma^6))*timeGrid.*exp(-(timeGrid.^2)./sigma2).* ...\n (5 - 2*timeGrid.^2/sigma2) - (2*gamma^2/(sqrt(pi)*sigma))*exp(-gamma*t1)* ...\n (((gamma-2*t2/sigma2).*(1/sigma - 2*t2.^2/sigma^3) - 4*t2/sigma^3).*exp(-t2.^2/sigma2)).'; \nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/lfmaaGradientSigmaUpsilonMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6940451609931445}} {"text": "%% housekeeping\nclear\nclc\nclose all\n\n%% create data\n\ntmp=importdata('ht2014data.txt');\n\nvnames={'real_pce','cpixfe','ffr','m2','fsi'};\n\nrawdb=ts('1988M12',tmp.data(:,2:end),vnames);\n\nrawdb=pages2struct(rawdb);\n\n%% plot the data\n\nfigure('name','raw data');\nfor ii=1:numel(vnames)\n v=vnames{ii};\n subplot(3,2,ii)\n plot(rawdb.(v))\n title(v)\nend\n\n%% transformed data\n% \n% we use levels of the federal funds rate and the stress index and growth\n% rates of real personal consumption expenditures (PCE), money and prices.\ndb=struct();\ndb.R=rawdb.ffr;\ndb.S=rawdb.fsi;\ndb.C=100*log(rawdb.real_pce/rawdb.real_pce{-1});\ndb.M=100*log(rawdb.m2/rawdb.m2{-1});\ndb.P=100*log(rawdb.cpixfe/rawdb.cpixfe{-1});\n\ndescr=struct('C','Consumption growth',...\n 'P','Inflation',...\n 'R','Feds Funds rate',...\n 'M','Money growth',...\n 'S','Financial stress index');\n\nvarlist=fieldnames(descr);\n\nfigure('name','Transformed data');\nfor ii=1:numel(varlist)\n v=varlist{ii};\n subplot(3,2,ii)\n plot(db.(v))\n title(descr.(v))\n axis tight\nend\n%% Model 1: SVAR models with cholesky identification\nclc\n\nmodels={'1v1c','2v1c','3v1c','1v2c','2v2c','3v2c',...\n '3vS2c','3vSC2c','3vSCP2c','3vSRM2c','3vRM2c','3vRMC2c'};\n\nnlags=2;\n\nexog={};\n\nconstant=true;\n\npanel=[];\n\npriors=struct();\npriors.var=svar.prior_template();\npriors.var.type='sz';\n\ndate_range={db.C.start,db.C.finish};\n\nsv0=svar.empty(1,0);\n\ntic\n\nfor ii=1:numel(models)\n \n fprintf(1,' -------------------- %s -------------------- \\n',models{ii});\n \n [markov_chains,switch_prior,restrictions]=build_model(models{ii},varlist);\n \n sv0(1,ii)=svar(varlist,exog,nlags,constant,panel,markov_chains);\n \n priors.nonvar=switch_prior;\n \n sv0(1,ii)=estimate(sv0(1,ii),db,date_range,priors,restrictions);\n \nend\n\ntoc\n\n% 2601.732325 seconds\n\n%% estimates\n\nfor ii=1:numel(models)\n clc, close all\n \n fprintf(1,' -------------------- %s -------------------- \\n',models{ii});\n \n pmode=posterior_mode(sv0(ii))\n \n pause\n % Printing estimates\n \n print_structural_form(sv0(ii))\n \n pause\n % Printing solution\n \n print_solution(sv0(ii))\n pause\n\n % historical probabilities\n plot_probabilities(sv0(ii))\n pause\n \n % plots probabilities against data\n close all\n plot_data_against_probabilities(sv0(ii),'regime')\n pause\n \nend\n\n%% A model with endogenous switching\n\nclc\n\n[mctvp,switch_prior,restrictions]=build_model('2v1c',varlist);\n\nmctvp.endogenous_probabilities={\n 'syncvol_tp_1_2=1/(1+exp(a12-b12*S))'\n 'syncvol_tp_2_1=a21'\n };\n\nmctvp.probability_parameters={'a12','b12','a21'};\n\nmctvp.controlled_parameters={'s(3)'};%'s(1)','s(2)','s(4)',\n\nswitch_prior=rmfield(switch_prior,{'syncvol_tp_1_2','syncvol_tp_2_1'});\n\nswitch_prior.a12={0.1,0,5,'normal'};\n\nswitch_prior.b12={0.1,2,5,'gamma'};\n\nswitch_prior.a21={0.2,0.2,0.2,'beta'};\n\nsvtvp=svar(varlist,exog,nlags,constant,panel,mctvp);\n \npriors.nonvar=switch_prior;\n \nsvtvp=estimate(svtvp,db,date_range,priors,restrictions);\n\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/examples/VariousModels/HubrichTetlow/ht2015.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.6940074977800886}} {"text": "function L = image_laplacian(varargin)\n % IMAGE_LAPLACIAN Compute the image laplacian for a given image in the manner\n % of \"Colorization using Optimization\" by [Levin et al. 2004]. This is a sort\n % of amalgamation of the literal description in the paper but the knowledge\n % that a Laplacian (rather than a bi-Laplacian) is being used.\n % \n % L = IMAGE_LAPLACIAN(im)\n % L = IMAGE_LAPLACIAN(im,'ParameterName',ParameterValue)\n %\n % Inputs:\n % im h by w by (3|1) image (expects double)\n % Optional:\n % 'Omega' followed by an omega value\n % Outputs:\n % L w*h by w*h sparse laplacian matrix\n %\n % See also: cotmatrix, levin, lischinski\n %\n\n im = varargin{1};\n\n % width and height\n h = size(im,1);\n w = size(im,2);\n % image size\n % w h c harmonic biharmonic\n % 185 138 1 0.05 0.1\n % 185 138 3 0.1\n % 93 69 3 0.1\n omega = 0.1;\n % number of vertices/pixels\n n = h*w;\n\n if ~strcmp(class(im),'double')\n warning('Casting input to double: `im = im2double(im)`');\n im = im2double(im);\n end\n\n ii = 2;\n while(ii <= nargin)\n switch varargin{ii}\n case 'Omega'\n ii = ii + 1;\n assert(ii<=nargin)\n omega = varargin{ii};\n otherwise\n error('Unsupported parameter');\n end\n ii = ii+1;\n end\n\n % runs across height fastest\n I = (1:n)';\n I = reshape(I,h,w);\n Ileft = I(1:h,1:(w-1));\n Iright = I(1:h,2:w);\n Ibottom = I(1:(h-1),1:w);\n Itop= I(2:h,1:w);\n % determine neighborhood via FD stencil\n E = [ ...\n Ileft(:) Iright(:);...\n Iright(:) Ileft(:);...\n Ibottom(:) Itop(:);...\n Itop(:) Ibottom(:);...\n ];\n assert(size(E,1) == ((h-1)*w + (w-1)*h)*2);\n r = E(:,1);\n s = E(:,2);\n imlong = reshape(im,size(im,1)*size(im,2),size(im,3));\n\n wrs = exp(-sum((imlong(r,:)-imlong(s,:)).^2,2)./(2*omega.^2));\n\n L = sparse(r,s,wrs,n,n);\n % We've made L(r,s) = wrs, now we need L(r,r) = \u2211L(r,s) and L(r,s) = -wrs\n L = diag(sum(L,2))-L;\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/imageprocessing/image_laplacian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.694007494769881}} {"text": "% plot of sampling location on warped grid\n\n\nrep = 'results/';\n\nif ~exist(rep)\n mkdir(rep);\nend\n\nsave_warped = 0;\nsave_dich = 1;\n\ns = 50;\nc = 0.45;\nn = 16;\nt = linspace(0,1,n);\n[Y,X] = meshgrid(t,t);\n\nx = X(:); y = Y(:);\n\nxw = x; \nyw = y + c * x.^2;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% plot of the warped locations\nclf;\nhold on;\nscatter(x,y, s, 'filled');\nplot(t, 1-c*t.^2);\nhold off;\n\nclf;\nscatter(x,y, s, 'filled');\naxis equal;\naxis off;\nif save_warped\nsaveas(gcf, [rep 'samples.eps'], 'epsc');\nend\n\nclf;\nscatter(xw,yw, 25, 'filled');\naxis equal; axis off;\nif save_warped\nsaveas(gcf, [rep 'samples_warped.eps'], 'epsc');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% plot of the grouping process\nposw = [xw, yw]';\npos = [x, y]';\noptions.part_type = '1axis';\nfor i=0:5\n options.depthmax = i;\n [part,B,G] = dichotomic_grouping([yw, xw]',options);\n options.point_size = 80;\n clf;\n plot_dichotomic_partition(posw, part, options);\n axis([0 1.5 0 1.5]); axis equal; axis off;\n if save_dich\n saveas(gcf, [rep '_dich_' num2str(i) '.eps'], 'epsc');\n end\n clf;\n plot_dichotomic_partition(pos, part, options);\n axis([0 1.5 0 1.5]); axis equal; axis off;\n if save_dich\n saveas(gcf, [rep '_dich_' num2str(i) 'w.eps'], 'epsc');\n end \nend", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_alpert/tests/test_warpsampling.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.6940074920320376}} {"text": "function [out, param] = pid_loop(y_c, y, dy, kp, ki, kd, limit, Ts, tau, param)\n\nintegrator = param.int;\ndifferentiator = param.diff;\nerror_prev = param.error_prev;\ny_c_prev = param.y_c_prev;\n\n\n% Update error\nerror = y_c - y; \n\n% Update integrator\nif isfinite(dy)\n integrator = integrator + Ts*(error + dy/2);\nelse\n integrator = integrator + (Ts/2)*(error + error_prev);\nend\n\n% Update differentiator\nif isfinite(1/kd)\n if isfinite(dy)\n dy_c = y_c - y_c_prev; % Compute command diff\n derror = dy_c - dy; % Compute error diff\n y_c_prev = y_c; % Update the command for next step\n else\n derror = error - error_prev; % Compute error diff\n error_prev = error; % Update the error for next step\n end\n differentiator = (2*tau-Ts)/(2*tau+Ts)*differentiator...\n + 2/(2*tau+Ts)*(derror);\nend\n\n% Update output before considering saturation\nout_unsat = kp*error + ki*integrator + kd*differentiator;\n% Check saturation\nout = saturate(out_unsat, limit);\n\n% Implement integrator anti-windup\n if ki~=0\n integrator = integrator + Ts/ki * (out - out_unsat);\n end\n \nparam.int = integrator;\nparam.diff = differentiator;\nparam.error_prev = error_prev;\nparam.y_c_prev = y_c_prev;\n \n \nend\n\nfunction out = saturate(out_unsat, limit)\n\n if out_unsat > limit \n out = limit;\n elseif out_unsat < -limit \n out = -limit;\n else\n out = out_unsat;\n end\n \nend", "meta": {"author": "lis-epfl", "repo": "swarmlab", "sha": "3574deddd2e4fdcc5696d08f93d6e888f45c8ecc", "save_path": "github-repos/MATLAB/lis-epfl-swarmlab", "path": "github-repos/MATLAB/lis-epfl-swarmlab/swarmlab-3574deddd2e4fdcc5696d08f93d6e888f45c8ecc/control/control_drone/pid_loop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213880824789, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6939809971595046}} {"text": "function tests = test_spx_norms\n tests = functiontests(localfunctions);\nend\n\n\nfunction test_lp_norms(testCase)\n x = [1 1 1 \n 2 2 2\n 3 3 3];\n verifyEqual(testCase, [6 6 6], spx.norm.norms_l1_cw(x));\n verifyEqual(testCase, [3 6 9]', spx.norm.norms_l1_rw(x));\n verifyEqual(testCase, sqrt([14 14 14]), spx.norm.norms_l2_cw(x));\n verifyEqual(testCase, sqrt([3 12 27]'), spx.norm.norms_l2_rw(x));\n verifyEqual(testCase, [3 3 3], spx.norm.norms_linf_cw(x));\n verifyEqual(testCase, [1 2 3]', spx.norm.norms_linf_rw(x));\n verifyEqual(testCase, 18, spx.norm.cr_l1_l1(x));\n verifyEqual(testCase, 18, spx.norm.rc_l1_l1(x));\n verifyEqual(testCase, sqrt(108), spx.norm.cr_l1_l2(x));\n verifyEqual(testCase, sqrt(126), spx.norm.rc_l1_l2(x), 'AbsTol', 1e-6);\n verifyEqual(testCase, 6, spx.norm.cr_l1_linf(x));\n verifyEqual(testCase, 9, spx.norm.rc_l1_linf(x));\n verifyEqual(testCase, 3*sqrt(14),spx.norm.cr_l2_l1(x));\n verifyEqual(testCase, sqrt(3) + sqrt(12) + sqrt(27), spx.norm.rc_l2_l1(x));\n verifyEqual(testCase, sqrt(42), spx.norm.cr_l2_l2(x), 'AbsTol', 1e-6);\n verifyEqual(testCase, sqrt(42), spx.norm.rc_l2_l2(x), 'AbsTol', 1e-6);\n verifyEqual(testCase, sqrt(14), spx.norm.cr_l2_linf(x));\n verifyEqual(testCase, sqrt(27), spx.norm.rc_l2_linf(x));\n verifyEqual(testCase, 9, spx.norm.cr_linf_l1(x));\n verifyEqual(testCase, 6, spx.norm.rc_linf_l1(x));\n verifyEqual(testCase, sqrt(27), spx.norm.cr_linf_l2(x), 'AbsTol', 1e-6);\n verifyEqual(testCase, sqrt(14), spx.norm.rc_linf_l2(x), 'AbsTol', 1e-6);\n verifyEqual(testCase, 3, spx.norm.cr_linf_linf(x));\n verifyEqual(testCase, 3, spx.norm.rc_linf_linf(x));\nend\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/library/tests/commons/test_spx_norms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6939809940787037}} {"text": "function [beta_median,beta_std,beta_lbound,beta_ubound,sigma_median,beta_mean_median,beta_mean_lbound,beta_mean_ubound,sigma_mean_median]...\n =panel4estimates(N,n,q,beta_gibbs,sigma_gibbs,cband, beta_mean,sigma_mean)\n\n\n% compute first the percentiles for the mean model values, i.e. beta_mean\n% and sigma_man\n% \n% for jj=1:n^2\n% sigma_mean_median(jj,1)=[quantile(sigma_mean(jj,:),0.5)];\n% end\n% for jj=1:q\n% beta_mean_median(jj,1)=[quantile(beta_mean(jj,:),0.5)];\n% beta_mean_lbound(jj,1)=[quantile(beta_gibbs(jj,1),(1-cband)/2)];\n% beta_mean_ubound(jj,1)=[quantile(beta_gibbs(jj,1),1-(1-cband)/2)];\n% end\n% as the VAR coefficients are estimated for each unit, loop over units\n% move to the country specific coefficients\nfor ii=1:N\n % loop over VAR coefficients\n for jj=1:q\n beta_median(jj,1,ii)=[quantile(beta_gibbs(jj,:,ii),0.5)];\n beta_std(jj,1,ii)=std(beta_gibbs(jj,:,ii));\n beta_lbound(jj,1,ii)=[quantile(beta_gibbs(jj,1,ii),(1-cband)/2)];\n beta_ubound(jj,1,ii)=[quantile(beta_gibbs(jj,1,ii),1-(1-cband)/2)];\n end\n % loop over sigma entries\n for jj=1:n^2\n sigma_median(jj,1,ii)=[quantile(sigma_gibbs(jj,:,ii),0.5)];\n end\nend\n\n\n\n\n\n\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/panel4estimates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6939809940787037}} {"text": "function [h, compUpV, compUp] = lfmComputeH4VP(gamma1_p, gamma1_m, sigma2, t1, ...\n preFactor, preExp, mode)\n\n% LFMCOMPUTEH4VP Helper function for computing part of the LFMVXLFM kernel.\n% FORMAT\n% DESC computes a portion of the LFMVXLFM kernel.\n% ARG gamma1 : Gamma value for first system.\n% ARG gamma2 : Gamma value for second system.\n% ARG sigma2 : length scale of latent process.\n% ARG t1 : first time input (number of time points x 1).\n% ARG t2 : second time input (number of time points x 1).\n% ARG mode: indicates in which way the vectors t1 and t2 must be transposed\n% RETURN h : result of this subcomponent of the kernel for the given values.\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n%\n% SEEALSO : lfmComputeH4Hat, lfmXlfmKernCompute\n\n% KERN\n\n% This could also be used with str2func changing between 'lfm' and 'lfmvp'\n\n\nif mode==0\n if nargout > 1\n [compUpV{1}, compUp{1}] = lfmvpComputeUpsilonVector(gamma1_p,sigma2, t1, 0);\n [compUpV{2}, compUp{2}] = lfmvpComputeUpsilonVector(gamma1_m,sigma2, t1, 0);\n h = compUpV{1}*( preExp(:,1)/preFactor(1) - preExp(:,2)/preFactor(2)).' ...\n + compUpV{2}*( preExp(:,2)/preFactor(3) - preExp(:,1)/preFactor(4)).';\n else\n h = lfmvpComputeUpsilonVector(gamma1_p,sigma2, t1, 0)*( preExp(:,1)/preFactor(1) - preExp(:,2)/preFactor(2)).' ...\n + lfmvpComputeUpsilonVector(gamma1_m,sigma2, t1, 0)*( preExp(:,2)/preFactor(3) - preExp(:,1)/preFactor(4)).';\n end\nelse\n if nargout > 1\n compUp{1} = lfmComputeUpsilonVector(gamma1_p,sigma2, t1);\n compUp{2} = lfmComputeUpsilonVector(gamma1_m,sigma2, t1);\n h = compUp{1}*( preExp(:,2)/preFactor(2) - preExp(:,1)/preFactor(1)).' ...\n + compUp{2}*( preExp(:,1)/preFactor(4) - preExp(:,2)/preFactor(3)).';\n compUpV = compUp;\n else\n h = lfmComputeUpsilonVector(gamma1_p,sigma2, t1)*( preExp(:,2)/preFactor(2) - preExp(:,1)/preFactor(1)).' ...\n + lfmComputeUpsilonVector(gamma1_m,sigma2, t1)*( preExp(:,1)/preFactor(4) - preExp(:,2)/preFactor(3)).';\n end\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/lfmComputeH4VP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6939809940787037}} {"text": "function nc=normcor(a,b)\nm=size(a);\nn=size(b);\na=im2double(a);\nb=im2double(b);\na1=mean2(a);\nb1=mean2(b);\nc1=0;c2=0;\nfor i=1:m\n for j=1:n\n c1=c1+(a(i,j)-a1);\n c2=c2+(b(i,j)-b1);\n num=c1*c2;\n c3=(c1^2)*(c2^2);\n dem=sqrt(c3);\n end\nend\nnc=num/dem;\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/30813-normalized-cross-correlation/normcor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6939809893599153}} {"text": "function [ywc1, ywt1, ywc2, ywt2] = wavefilter(X, fig)\n\n% wavelets (Haar) filtering: see Lubik, Matthes, Verona (2019)\n\n% ywc1 has the cycles at frequencies 8-32 quarters (loose 16 datapoints)\n% ywc2 has the cycles at frequencies 8-64 quarters (loose 32 datapoints)\n% ywt1 and ywt2 have the trends and are defined as residuals\n \n\nenddT=size(X,1);\nywc1=zeros(enddT,size(X,2)); ywt1=zeros(enddT,size(X,2)); \nywc2=zeros(enddT,size(X,2)); ywt2=zeros(enddT,size(X,2)); \n\nfor qq=1:size(X,2)\n% y=zeros(enddT,1); \n xx1=zeros(enddT,1); xx2=zeros(enddT,1); xx3=zeros(enddT,1);\n xx4=zeros(enddT,1); xx5=zeros(enddT,1); \n\n y=squeeze(X(:,qq));\n\n % 2-4 quarters cycles\n for tt=2:length(y)\n %xx1(tt,1)=(1/2)*(y(tt)-(y(tt)-y(tt-1)));\n xx1(tt,1)=(1/2)*(y(tt)-y(tt-1));\n end\n % 4-8 quarters cycles\n for tt=4:length(y)\n xx2(tt,1)=(1/4)*(y(tt)+y(tt-1)-(y(tt-2)+y(tt-3)) );\n end\n % 8-16 quarters cycles\n for tt=8:length(y)\n xx3(tt,1)=(1/8)*(y(tt)+y(tt-1)+y(tt-2)+y(tt-3)- ...\n (y(tt-4)+y(tt-5)+y(tt-6)+y(tt-7)) );\n end\n % 16-32 quarters cycles\n for tt=16:length(y)\n xx4(tt,1)=(1/16)*(y(tt)+y(tt-1)+y(tt-2)+y(tt-3)+y(tt-4)+ ...\n y(tt-5)+y(tt-6)+y(tt-7)-...\n (y(tt-8)+y(tt-9)+y(tt-10)+y(tt-11)+y(tt-12)+ ...\n y(tt-13)+y(tt-14)+y(tt-15)) );\n end\n % 32-64 quarters cycles\n for tt=32:length(y)\n xx5(tt,1)=(1/32)*(y(tt)+y(tt-1)+y(tt-2)+y(tt-3)+y(tt-4)+y(tt-5)+ ...\n y(tt-6)+y(tt-7)+y(tt-8)+y(tt-9)+y(tt-10)+ y(tt-11)+y(tt-12)+ ...\n y(tt-13)+ y(tt-14)+y(tt-15) - ...\n (y(tt-16)+y(tt-17)+y(tt-18)+y(tt-19)+y(tt-20)+y(tt-21)+ ...\n y(tt-22)+y(tt-23)+y(tt-24)+y(tt-25)+y(tt-26)+y(tt-27)+ ...\n y(tt-28)+y(tt-29)+y(tt-30)+y(tt-31) ) );\n end\n % cyclical components \n ywc1(16:length(y),qq)=xx3(16:length(y))+xx4(16:length(y));\n ywc2(32:length(y),qq)=xx3(32:length(y))+...\n xx4(32:length(y))+xx5(32:length(y));\n % trend components (actual-BC cycles-high frequnecy cycles)\n ywt1(16:length(y),qq)=y(16:length(y))-ywc1(16:length(y),qq) ...\n -xx1(16:length(y))-xx2(16:length(y));\n ywt2(32:length(y),qq)=y(32:length(y))-ywc2(32:length(y),qq) ...\n -xx1(32:length(y))-xx2(32:length(y));\n \n% xxx=[xx1 xx2 xx3 xx4 xx5]\n% figure(100)\n% plot(xxx)\n \n if fig==1\n % plot cyclical components\n figure(1)\n plot(ywc1(1:length(y),qq),'r', 'linewidth',2); hold on; \n plot(ywc2(1:length(y), qq),'b','linewidth',2); hold off; axis tight;\n legend('BC(8-32)','BC+LOW(8-64)')\n pause\n end\n end\n \n \nend\n\n", "meta": {"author": "naffe15", "repo": "BVAR_", "sha": "4c935f440a2e98475ead4f873ebdfd03378a0eee", "save_path": "github-repos/MATLAB/naffe15-BVAR_", "path": "github-repos/MATLAB/naffe15-BVAR_/BVAR_-4c935f440a2e98475ead4f873ebdfd03378a0eee/bvartools/wavefilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6939809772899455}} {"text": "%% Ex. 8 Another example of elementary functions with a vectorial variable\n\na = [2 3 5];\nb = 2*a.^2+3*a+4\n\n\n%Output:\n% b = 18 31 69\n% Remark: The content of b is\n% b = [2*(a(1))^2+3*a(1)+4 2*(a(2))^2+3*a(2)+4 2*(a(3))^2+3*a(3)+4].", "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/matlab_for_beginners/part_4(array_nd_matrix)/program8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037302939514, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6938822902010754}} {"text": "function par_estc \n% transport parameter estimation with derivatives Holzbecher January 2006\n\nglobal xfit cfit T D c0 c1\n\n% Example values for Chlorid in Marmara Sea Sediment Core \nT = 3.15e11; % [s] 10.000 years \nD = 1.0e-5; % [cm*cm/s]\nc0 = 0; % [mmol/l]\nc1 = 619; % [mmol/l]\nxmax = 4000; % [cm]\n\n% specify fitting data\nxfit = [0 20 40 60 100 120 140 160 215 255 275 300 375 450 525 600 750 1050 1200 1350 1650 1950 2250 2550 2700 3000 3450 3900];\ncfit = [619 597 608 615 619 615 621 571 621 618 619 625 577 612 608 612 609 590 582 582 556 494 457 489 487 444 381 371];\n\nx = [0:xmax/400:xmax];\noptions = optimset('Display','iter','TolFun',1e-9);\nv = fzero(@myfun,0.2e-8,options);\ndisplay (['Best fit for v = ' num2str(v)]);\n\nh = 1./(2.*sqrt(D*T)); e = diag(eye(size(x,2))); \nplot (xfit,cfit,'o',x,c0+0.5*c1*(erfc(h*(x-v*T*e'))+(exp((v/D)*x)).*erfc(h*(x+v*T*e'))),'-');\nlegend ('given','modelled');\nxlabel ('depth [cm]'); ylabel ('chloride concentration [mmol/l]');\ntext(0.1*xmax,c1*0.65,['sedimentation velocity [cm/a]: ' num2str(v*3.15e7)]);\ne = diag(eye(size(xfit,2))); \nnormc = norm(cfit-c0+0.5*c1*(erfc(h*(xfit-v*T*e'))+(exp((v/D)*xfit)).*erfc(h*(xfit+v*T*e'))));\ntext(0.1*xmax,c1*0.6,['norm of residuals: ' num2str(normc)]);\n\nfunction f = myfun(v); \nglobal xfit cfit T D c0 c1\n\ne=diag(eye(size(xfit,2))); h=1./(2.*sqrt(D*T));\narg1 = h*(xfit-v*T*e'); arg2 = h*(xfit+v*T*e'); arg3 = (v/D)*xfit;\n\n% solve advection diffusion equation for c with c(t=0)=c0 and c(x=0)=c1 \nc = c0 + 0.5*c1*(erfc(arg1)+(exp(arg3).*erfc(arg2)));\n\n% compute derivative of solution due to v\ncv = c1*((T*h/sqrt(pi))*(exp(-arg1.*arg1)-exp(arg3).*exp(-arg2.*arg2))+0.5*(xfit/D).*exp(arg3).*erfc(arg2));\n\n% specify function f to vanish\nf = 2*(c-cfit)*cv';\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/15646-environmental-modeling/par_estc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317888, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6938822859196223}} {"text": "function [xp,dxpdom,dxpdT,dxpdf,dxpdc,dxpdk,dxpdalpha] = project_points2(X,f,c,k,alpha)\n\n%project_points2.m\n%\n%[xp,dxpdom,dxpdT,dxpdf,dxpdc,dxpdk] = project_points2(X,om,T,f,c,k,alpha)\n%\n%Projects a 3D structure onto the image plane.\n%\n%INPUT: X: 3D structure in the world coordinate frame (3xN matrix for N points)\n% (om,T): Rigid motion parameters between world coordinate frame and camera reference frame\n% om: rotation vector (3x1 vector); T: translation vector (3x1 vector)\n% f: camera focal length in units of horizontal and vertical pixel units (2x1 vector)\n% c: principal point location in pixel units (2x1 vector)\n% k: Distortion coefficients (radial and tangential) (4x1 vector)\n% alpha: Skew coefficient between x and y pixel (alpha = 0 <=> square pixels)\n%\n%OUTPUT: xp: Projected pixel coordinates (2xN matrix for N points)\n% dxpdom: Derivative of xp with respect to om ((2N)x3 matrix)\n% dxpdT: Derivative of xp with respect to T ((2N)x3 matrix)\n% dxpdf: Derivative of xp with respect to f ((2N)x2 matrix if f is 2x1, or (2N)x1 matrix is f is a scalar)\n% dxpdc: Derivative of xp with respect to c ((2N)x2 matrix)\n% dxpdk: Derivative of xp with respect to k ((2N)x4 matrix)\n%\n%Definitions:\n%Let P be a point in 3D of coordinates X in the world reference frame (stored in the matrix X)\n%The coordinate vector of P in the camera reference frame is: Xc = R*X + T\n%where R is the rotation matrix corresponding to the rotation vector om: R = rodrigues(om);\n%call x, y and z the 3 coordinates of Xc: x = Xc(1); y = Xc(2); z = Xc(3);\n%The pinehole projection coordinates of P is [a;b] where a=x/z and b=y/z.\n%call r^2 = a^2 + b^2.\n%The distorted point coordinates are: xd = [xx;yy] where:\n%\n%xx = a * (1 + kc(1)*r^2 + kc(2)*r^4 + kc(5)*r^6) + 2*kc(3)*a*b + kc(4)*(r^2 + 2*a^2);\n%yy = b * (1 + kc(1)*r^2 + kc(2)*r^4 + kc(5)*r^6) + kc(3)*(r^2 + 2*b^2) + 2*kc(4)*a*b;\n%\n%The left terms correspond to radial distortion (6th degree), the right terms correspond to tangential distortion\n%\n%Finally, convertion into pixel coordinates: The final pixel coordinates vector xp=[xxp;yyp] where:\n%\n%xxp = f(1)*(xx + alpha*yy) + c(1)\n%yyp = f(2)*yy + c(2)\n%\n%\n%NOTE: About 90 percent of the code takes care fo computing the Jacobian matrices\n%\n%\n%Important function called within that program:\n%\n%rodrigues.m: Computes the rotation matrix corresponding to a rotation vector\n%\n%rigid_motion.m: Computes the rigid motion transformation of a given structure\n\n\n\n[m,n] = size(X);\n\nY = X;\n\ninv_Z = 1./Y(3,:);\n\nx = (Y(1:2,:) .* (ones(2,1) * inv_Z)) ;\n\n\nbb = (-x(1,:) .* inv_Z)'*ones(1,3);\ncc = (-x(2,:) .* inv_Z)'*ones(1,3);\n\nif nargout > 1,\n dxdom = zeros(2*n,3);\n dxdom(1:2:end,:) = ((inv_Z')*ones(1,3)) .* dYdom(1:3:end,:) + bb .* dYdom(3:3:end,:);\n dxdom(2:2:end,:) = ((inv_Z')*ones(1,3)) .* dYdom(2:3:end,:) + cc .* dYdom(3:3:end,:);\n\n dxdT = zeros(2*n,3);\n dxdT(1:2:end,:) = ((inv_Z')*ones(1,3)) .* dYdT(1:3:end,:) + bb .* dYdT(3:3:end,:);\n dxdT(2:2:end,:) = ((inv_Z')*ones(1,3)) .* dYdT(2:3:end,:) + cc .* dYdT(3:3:end,:);\nend;\n\n\n% Add distortion:\n\nr2 = x(1,:).^2 + x(2,:).^2;\n\nif nargout > 1,\n dr2dom = 2*((x(1,:)')*ones(1,3)) .* dxdom(1:2:end,:) + 2*((x(2,:)')*ones(1,3)) .* dxdom(2:2:end,:);\n dr2dT = 2*((x(1,:)')*ones(1,3)) .* dxdT(1:2:end,:) + 2*((x(2,:)')*ones(1,3)) .* dxdT(2:2:end,:);\nend;\n\n\nr4 = r2.^2;\n\nif nargout > 1,\n dr4dom = 2*((r2')*ones(1,3)) .* dr2dom;\n dr4dT = 2*((r2')*ones(1,3)) .* dr2dT;\nend\n\nr6 = r2.^3;\n\nif nargout > 1,\n dr6dom = 3*((r2'.^2)*ones(1,3)) .* dr2dom;\n dr6dT = 3*((r2'.^2)*ones(1,3)) .* dr2dT;\nend;\n\n% Radial distortion:\n\ncdist = 1 + k(1) * r2 + k(2) * r4 + k(5) * r6;\n\nif nargout > 1,\n dcdistdom = k(1) * dr2dom + k(2) * dr4dom + k(5) * dr6dom;\n dcdistdT = k(1) * dr2dT + k(2) * dr4dT + k(5) * dr6dT;\n dcdistdk = [ r2' r4' zeros(n,2) r6'];\nend;\n\nxd1 = x .* (ones(2,1)*cdist);\n\nif nargout > 1,\n dxd1dom = zeros(2*n,3);\n dxd1dom(1:2:end,:) = (x(1,:)'*ones(1,3)) .* dcdistdom;\n dxd1dom(2:2:end,:) = (x(2,:)'*ones(1,3)) .* dcdistdom;\n coeff = (reshape([cdist;cdist],2*n,1)*ones(1,3));\n dxd1dom = dxd1dom + coeff.* dxdom;\n\n dxd1dT = zeros(2*n,3);\n dxd1dT(1:2:end,:) = (x(1,:)'*ones(1,3)) .* dcdistdT;\n dxd1dT(2:2:end,:) = (x(2,:)'*ones(1,3)) .* dcdistdT;\n dxd1dT = dxd1dT + coeff.* dxdT;\n\n dxd1dk = zeros(2*n,5);\n dxd1dk(1:2:end,:) = (x(1,:)'*ones(1,5)) .* dcdistdk;\n dxd1dk(2:2:end,:) = (x(2,:)'*ones(1,5)) .* dcdistdk;\nend;\n\n\n% tangential distortion:\n\na1 = 2.*x(1,:).*x(2,:);\na2 = r2 + 2*x(1,:).^2;\na3 = r2 + 2*x(2,:).^2;\n\ndelta_x = [k(3)*a1 + k(4)*a2 ;\n k(3) * a3 + k(4)*a1];\n\n\n%ddelta_xdx = zeros(2*n,2*n);\naa = (2*k(3)*x(2,:)+6*k(4)*x(1,:))'*ones(1,3);\nbb = (2*k(3)*x(1,:)+2*k(4)*x(2,:))'*ones(1,3);\ncc = (6*k(3)*x(2,:)+2*k(4)*x(1,:))'*ones(1,3);\n\nif nargout > 1,\n ddelta_xdom = zeros(2*n,3);\n ddelta_xdom(1:2:end,:) = aa .* dxdom(1:2:end,:) + bb .* dxdom(2:2:end,:);\n ddelta_xdom(2:2:end,:) = bb .* dxdom(1:2:end,:) + cc .* dxdom(2:2:end,:);\n\n ddelta_xdT = zeros(2*n,3);\n ddelta_xdT(1:2:end,:) = aa .* dxdT(1:2:end,:) + bb .* dxdT(2:2:end,:);\n ddelta_xdT(2:2:end,:) = bb .* dxdT(1:2:end,:) + cc .* dxdT(2:2:end,:);\n\n ddelta_xdk = zeros(2*n,5);\n ddelta_xdk(1:2:end,3) = a1';\n ddelta_xdk(1:2:end,4) = a2';\n ddelta_xdk(2:2:end,3) = a3';\n ddelta_xdk(2:2:end,4) = a1';\nend;\n\n\nxd2 = xd1 + delta_x;\n\nif nargout > 1,\n dxd2dom = dxd1dom + ddelta_xdom ;\n dxd2dT = dxd1dT + ddelta_xdT;\n dxd2dk = dxd1dk + ddelta_xdk ;\nend;\n\n\n% Add Skew:\n\nxd3 = [xd2(1,:) + alpha*xd2(2,:);xd2(2,:)];\n\n% Compute: dxd3dom, dxd3dT, dxd3dk, dxd3dalpha\nif nargout > 1,\n dxd3dom = zeros(2*n,3);\n dxd3dom(1:2:2*n,:) = dxd2dom(1:2:2*n,:) + alpha*dxd2dom(2:2:2*n,:);\n dxd3dom(2:2:2*n,:) = dxd2dom(2:2:2*n,:);\n dxd3dT = zeros(2*n,3);\n dxd3dT(1:2:2*n,:) = dxd2dT(1:2:2*n,:) + alpha*dxd2dT(2:2:2*n,:);\n dxd3dT(2:2:2*n,:) = dxd2dT(2:2:2*n,:);\n dxd3dk = zeros(2*n,5);\n dxd3dk(1:2:2*n,:) = dxd2dk(1:2:2*n,:) + alpha*dxd2dk(2:2:2*n,:);\n dxd3dk(2:2:2*n,:) = dxd2dk(2:2:2*n,:);\n dxd3dalpha = zeros(2*n,1);\n dxd3dalpha(1:2:2*n,:) = xd2(2,:)';\nend;\n\n\n\n% Pixel coordinates:\nif length(f)>1,\n xp = xd3 .* (f(:) * ones(1,n)) + c(:)*ones(1,n);\n if nargout > 1,\n coeff = reshape(f(:)*ones(1,n),2*n,1);\n dxpdom = (coeff*ones(1,3)) .* dxd3dom;\n dxpdT = (coeff*ones(1,3)) .* dxd3dT;\n dxpdk = (coeff*ones(1,5)) .* dxd3dk;\n dxpdalpha = (coeff) .* dxd3dalpha;\n dxpdf = zeros(2*n,2);\n dxpdf(1:2:end,1) = xd3(1,:)';\n dxpdf(2:2:end,2) = xd3(2,:)';\n end;\nelse\n xp = f * xd3 + c*ones(1,n);\n if nargout > 1,\n dxpdom = f * dxd3dom;\n dxpdT = f * dxd3dT;\n dxpdk = f * dxd3dk;\n dxpdalpha = f .* dxd3dalpha;\n dxpdf = xd3(:);\n end;\nend;\n\nif nargout > 1,\n dxpdc = zeros(2*n,2);\n dxpdc(1:2:end,1) = ones(n,1);\n dxpdc(2:2:end,2) = ones(n,1);\nend;\n\n\nreturn;\n\n% Test of the Jacobians:\n\nn = 10;\n\nX = 10*randn(3,n);\nom = randn(3,1);\nT = [10*randn(2,1);40];\nf = 1000*rand(2,1);\nc = 1000*randn(2,1);\nk = 0.5*randn(5,1);\nalpha = 0.01*randn(1,1);\n\n[x,dxdom,dxdT,dxdf,dxdc,dxdk,dxdalpha] = project_points2(X,om,T,f,c,k,alpha);\n\n\n% Test on om: OK\n\ndom = 0.000000001 * norm(om)*randn(3,1);\nom2 = om + dom;\n\n[x2] = project_points2(X,om2,T,f,c,k,alpha);\n\nx_pred = x + reshape(dxdom * dom,2,n);\n\n\nnorm(x2-x)/norm(x2 - x_pred)\n\n\n% Test on T: OK!!\n\ndT = 0.0001 * norm(T)*randn(3,1);\nT2 = T + dT;\n\n[x2] = project_points2(X,om,T2,f,c,k,alpha);\n\nx_pred = x + reshape(dxdT * dT,2,n);\n\n\nnorm(x2-x)/norm(x2 - x_pred)\n\n\n\n% Test on f: OK!!\n\ndf = 0.001 * norm(f)*randn(2,1);\nf2 = f + df;\n\n[x2] = project_points2(X,om,T,f2,c,k,alpha);\n\nx_pred = x + reshape(dxdf * df,2,n);\n\n\nnorm(x2-x)/norm(x2 - x_pred)\n\n\n% Test on c: OK!!\n\ndc = 0.01 * norm(c)*randn(2,1);\nc2 = c + dc;\n\n[x2] = project_points2(X,om,T,f,c2,k,alpha);\n\nx_pred = x + reshape(dxdc * dc,2,n);\n\nnorm(x2-x)/norm(x2 - x_pred)\n\n% Test on k: OK!!\n\ndk = 0.001 * norm(k)*randn(5,1);\nk2 = k + dk;\n\n[x2] = project_points2(X,om,T,f,c,k2,alpha);\n\nx_pred = x + reshape(dxdk * dk,2,n);\n\nnorm(x2-x)/norm(x2 - x_pred)\n\n\n% Test on alpha: OK!!\n\ndalpha = 0.001 * norm(k)*randn(1,1);\nalpha2 = alpha + dalpha;\n\n[x2] = project_points2(X,om,T,f,c,k,alpha2);\n\nx_pred = x + reshape(dxdalpha * dalpha,2,n);\n\nnorm(x2-x)/norm(x2 - x_pred)\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/depthImproveStructureIO/project_points2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6938822804404111}} {"text": "\n\nclf reset;\necho on\n\n% This script demonstrates the use of the RSOM.\nclc;\n\n% load the example dissimilarity data\nload exampleDissimilarity.mat;\n\n% display the eigenvalue spectrum\n[V, D] = eig(Dissim);\neVals = diag(D);\nfigure; bar(eVals);\n\n\npause % Strike any key to continues...\nclc;\n\n\n% init RSOM\nsMap = rsom_lininit(Dissim, [10 10]);\n\n% train the RSOM\nsMap = rsom_batchtrain(sMap, Dissim);\n\n\n% Display the U-Matrix\nfigure;\nrsom_show(sMap, Dissim);\n\n% The U-Matrix shows clearly the structure of the data, i.e. that two\n% clusters are available\n\npause % Strike any key to continues...\nclc;\n\n% do linear embedding of the distance matrix into a 3 dimensional space\nx = cmdscale(Dissim.^(1/2));\nx = x(:,1:3);\n\n% plot the resulting data\nh = figure; hold on;\nplot3(x(1:100, 1), x(1:100, 2), x(1:100, 3), '.b');\nplot3(x(101:200, 1), x(101:200, 2), x(101:200, 3), '.r');\n\n% Since approximated vectorial data are available now, we can compute\n% the (approximated) neuron positions and plot them\nNeurons = sMap.cCodebook * x;\nfigure(h);\n\n% create a som struct\nsMapSOM = som_map_struct(3, sMap.topol); \nsom_grid(sMapSOM,'Coord',Neurons);\n\necho off;\n\n\n", "meta": {"author": "ilarinieminen", "repo": "SOM-Toolbox", "sha": "f2597abc1ae33c2060e0443d49e854011ff21831", "save_path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox", "path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox/SOM-Toolbox-f2597abc1ae33c2060e0443d49e854011ff21831/contrib/rsom/rsom_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6938822789164236}} {"text": "function par_estc \n% transport parameter estimation with derivatives Holzbecher January 2006\n\nglobal xfit cfit T D c0 c1\n\n% Example values for Chlorid in Marmara Sea Sediment Core \nT = 3.15e11; % [s] 10.000 years \nD = 1.0e-5; % [cm*cm/s]\nc0 = 0; % [mmol/l]\nc1 = 619; % [mmol/l]\nxmax = 4000; % [cm]\n\n% specify fitting data\nxfit = [0 20 40 60 100 120 140 160 215 255 275 300 375 450 525 600 750 1050 1200 1350 1650 1950 2250 2550 2700 3000 3450 3900];\ncfit = [619 597 608 615 619 615 621 571 621 618 619 625 577 612 608 612 609 590 582 582 556 494 457 489 487 444 381 371];\n\nx = [0:xmax/400:xmax];\noptions = optimset('Display','iter','TolFun',1e-9);\nv = fzero(@myfun,0.2e-8,options);\ndisplay (['Best fit for v = ' num2str(v)]);\n\nh = 1./(2.*sqrt(D*T)); e = diag(eye(size(x,2))); \nplot (xfit,cfit,'o',x,c0+0.5*c1*(erfc(h*(x-v*T*e'))+(exp((v/D)*x)).*erfc(h*(x+v*T*e'))),'-');\nlegend ('given','modelled');\nxlabel ('depth [cm]'); ylabel ('chloride concentration [mmol/l]');\ntext(0.1*xmax,c1*0.65,['sedimentation velocity [cm/a]: ' num2str(v*3.15e7)]);\ne = diag(eye(size(xfit,2))); \nnormc = norm(cfit-c0+0.5*c1*(erfc(h*(xfit-v*T*e'))+(exp((v/D)*xfit)).*erfc(h*(xfit+v*T*e'))));\ntext(0.1*xmax,c1*0.6,['norm of residuals: ' num2str(normc)]);\n\nfunction f = myfun(v) \nglobal xfit cfit T D c0 c1\n\ne=diag(eye(size(xfit,2))); h=1./(2.*sqrt(D*T));\narg1 = h*(xfit-v*T*e'); arg2 = h*(xfit+v*T*e'); arg3 = (v/D)*xfit;\n\n% solve advection diffusion equation for c with c(t=0)=c0 and c(x=0)=c1 \nc = c0 + 0.5*c1*(erfc(arg1)+(exp(arg3).*erfc(arg2)));\n\n% compute derivative of solution due to v\ncv = c1*((T*h/sqrt(pi))*(exp(-arg1.*arg1)-exp(arg3).*exp(-arg2.*arg2))+0.5*(xfit/D).*exp(arg3).*erfc(arg2));\n\n% specify function f to vanish\nf = 2*(c-cfit)*cv';\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/41147-environmental-modeling-using-matlab/par_estc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6938822633503187}} {"text": "function [ r, seed ] = r8col_uniform_abvec ( m, n, a, b, seed )\n\n%*****************************************************************************80\n%\n%% R8COL_UNIFORM_ABVEC fills an R8COL with scaled pseudorandom numbers.\n%\n% Discussion:\n%\n% An R8COL is an array of R8 values, regarded as a set of column vectors.\n%\n% The user specifies a minimum and maximum value for each row.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 December 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Paul Bratley, Bennett Fox, Linus Schrage,\n% A Guide to Simulation,\n% Springer Verlag, pages 201-202, 1983.\n%\n% Bennett Fox,\n% Algorithm 647:\n% Implementation and Relative Efficiency of Quasirandom\n% Sequence Generators,\n% ACM Transactions on Mathematical Software,\n% Volume 12, Number 4, pages 362-376, 1986.\n%\n% Peter Lewis, Allen Goodman, James Miller,\n% A Pseudo-Random Number Generator for the System/360,\n% IBM Systems Journal,\n% Volume 8, pages 136-143, 1969.\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns in\n% the array.\n%\n% Input, real A(M), B(M), the lower and upper limits.\n%\n% Input/output, integer SEED, the \"seed\" value, which\n% should NOT be 0. On output, SEED has been updated.\n%\n% Output, real R(M,N), the array of pseudorandom values.\n%\n i4_huge = 2147483647;\n\n for j = 1 : n\n\n for i = 1 : m\n\n k = floor ( seed / 127773 );\n\n seed = 16807 * ( seed - k * 127773 ) - k * 2836;\n\n if ( seed < 0 )\n seed = seed + i4_huge;\n end\n\n r(i,j) = a(i) + ( b(i) - a(i) ) * seed * 4.656612875E-10;\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/uniform/r8col_uniform_abvec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.6938413889153461}} {"text": "function [ r, seed ] = r8row_uniform_abvec ( m, n, a, b, seed )\n\n%*****************************************************************************80\n%\n%% R8ROW_UNIFORM_ABVEC fills an R8ROW with scaled pseudorandom numbers.\n%\n% Discussion:\n%\n% An R8ROW is an array of R8 values, regarded as a set of row vectors.\n%\n% The user specifies a minimum and maximum value for each column.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 January 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Paul Bratley, Bennett Fox, Linus Schrage,\n% A Guide to Simulation,\n% Springer Verlag, pages 201-202, 1983.\n%\n% Bennett Fox,\n% Algorithm 647:\n% Implementation and Relative Efficiency of Quasirandom\n% Sequence Generators,\n% ACM Transactions on Mathematical Software,\n% Volume 12, Number 4, pages 362-376, 1986.\n%\n% Peter Lewis, Allen Goodman, James Miller,\n% A Pseudo-Random Number Generator for the System/360,\n% IBM Systems Journal,\n% Volume 8, pages 136-143, 1969.\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns in\n% the array.\n%\n% Input, real A(N), B(N), the lower and upper limits.\n%\n% Input/output, integer SEED, the \"seed\" value, which\n% should NOT be 0. On output, SEED has been updated.\n%\n% Output, real R(M,N), the array of pseudorandom values.\n%\n i4_huge = 2147483647;\n\n for i = 1 : m\n\n for j = 1 : n\n\n k = floor ( seed / 127773 );\n\n seed = 16807 * ( seed - k * 127773 ) - k * 2836;\n\n if ( seed < 0 )\n seed = seed + i4_huge;\n end\n\n r(i,j) = a(j) + ( b(j) - a(j) ) * seed * 4.656612875E-10;\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/uniform/r8row_uniform_abvec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.6938413796803331}} {"text": "function btv_test05 ( )\n\n%*****************************************************************************80\n%\n%% BTV_TEST05 tests BURGERS_TIME_VISCOUS with the expansion initial condition.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 April 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BTV_TEST05\\n' );\n fprintf ( 1, ' Test BURGERS_TIME_VISCOUS with the expansion initial condition.\\n' );\n fprintf ( 1, ' Use periodic boundaries.\\n' );\n\n nx = 81;\n nt = 200;\n t_max = 2.0;\n nu = 0.01;\n bc = 4;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Initial condition: expansion\\n' );\n fprintf ( 1, ' Number of space nodes = %d\\n', nx );\n fprintf ( 1, ' Number of time steps = %d\\n', nt );\n fprintf ( 1, ' Final time T_MAX = %g\\n', t_max );\n fprintf ( 1, ' Viscosity = %g\\n', nu );\n fprintf ( 1, ' Boundary condition = %d\\n', bc );\n\n U = burgers_time_viscous ( @ic_expansion, nx, nt, t_max, nu, bc );\n\n x = linspace ( -1.0, +1.0, nx );\n\n figure ( 5 )\n\n plot ( x, U(1:50:(nt+1),:), 'Linewidth', 3 )\n grid on\n xlabel ( '<-- X -->' )\n ylabel ( '<-- U(X,T) -->' )\n title ( 'Burgers equation solutions over time, initial condition expansion' )\n\n filename = 'btv_test05.png';\n print ( '-dpng', filename )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Saved plot as \"%s\"\\n', filename );\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/burgers_time_viscous/btv_test05.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.6938413691418484}} {"text": "function [pos, vel] = vectrs (ra, dec, pmra, pmdec, parllx, rv)\n\n% this function converts angular quantities related to a star's\n% position and motion to vectors.\n\n% input\n\n% ra = right ascension in hours\n\n% dec = declination in degrees\n\n% pmra = proper motion in ra in milliarcseconds per year\n\n% pmdec = proper motion in dec in milliarcseconds per year\n\n% parllx = parallax in milliarcseconds\n\n% rv = radial velocity in kilometers/second\n\n% output\n\n% pos = position vector, equatorial rectangular coordinates,\n% with respect to solar system barycenter, components in au\n\n% vel = velocity vector, equatorial rectangular coordinates,\n% with respect to solar system barycenter, components in au/day\n\n% ported from NOVAS 3.0\n\n%%%%%%%%%%%%%%%%%%%%%%%\n\nseccon = 180.0d0 * 3600.0d0 / pi;\n\n% speed of light in kilometers/second\n\nc = 1.0d-3 * 2997924580.0d0;\n\n% au in kilometers\n\naukm = 1.0d-3 * 499.0047838061d0 * c;\n\n% if parallax is unknown, undetermined, or zero, set it to 1e-6\n% milliarcsecond, corresponding to a distance of 1 gigaparsec\n\nparalx = parllx;\n\nif ( paralx <= 0.0d0 )\n paralx = 1.0d-6;\nend\n\n% convert right ascension, declination, and parallax to position\n% vector in equatorial system with units of au\n\ndist = 1.0d0 / sin (paralx * 1.0d-3 / seccon);\n\nr = ra * 54000.0d0 / seccon;\n\nd = dec * 3600.0d0 / seccon;\n\ncra = cos(r);\n\nsra = sin(r);\n\ncdc = cos(d);\n\nsdc = sin(d);\n\npos(1) = dist * cdc * cra;\n\npos(2) = dist * cdc * sra;\n\npos(3) = dist * sdc;\n\n% compute doppler factor, which accounts for change in\n% light travel time to star\n\nk = 1.d0 / (1.0d0 - rv / c);\n\n% convert proper motion and radial velocity to orthogonal components\n% of motion with units of au/day\n\npmr = pmra / (paralx * 365.25d0) * k;\n\npmd = pmdec / (paralx * 365.25d0) * k;\n\nrvl = rv * 86400.0d0 / aukm * k;\n\n% transform motion vector to equatorial system\n\nvel(1) = - pmr * sra - pmd * sdc * cra + rvl * cdc * cra;\n\nvel(2) = pmr * cra - pmd * sdc * sra + rvl * cdc * sra;\n\nvel(3) = pmd * cdc + rvl * sdc;\n\n", "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/sun_moon/novas/vectrs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947179030095, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6937390807272176}} {"text": "\n%----------------------------------------------------------------------\n%Find the largest eigenvalue\n%----------------------------------------------------------------------\n\nfunction [ opts ] = find_max_eigenv ( matrix )\n\n[v,s] = eig(matrix);\nsort_s = sort(diag(s),'descend');\nopts = sort_s(1);", "meta": {"author": "hiroyuki-kasai", "repo": "ClassifierToolbox", "sha": "63aa78304a8ac10c432840c45d63170ea2bbabb0", "save_path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox", "path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox/ClassifierToolbox-63aa78304a8ac10c432840c45d63170ea2bbabb0/lib/JDDLDR_PR/utilities/find_max_eigenv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6937390761782725}} {"text": "function out = chebcoeffs(f, N, kind)\n%CHEBCOEFFS Chebyshev polynomial coefficients of a TRIGTECH.\n% A = CHEBCOEFFS(F, N) or A = CHEBCOEFFS(F, N, 1) returns a column vector of\n% the first N coefficients in the expansion of F in a series of Chebyshev\n% polynomials of the first kind, ordered starting with the coefficient of\n% T_0(x).\n%\n% A = CHEBCOEFFS(F, N, 2) does the same but for a series expansion in\n% Chebyshev polynomials of second kind, ordered starting with the coefficient\n% of U_0(x).\n%\n% If F is array-valued with P columns, then A is an NxP matrix.\n%\n% See also LEGCOEFFS, TRIGCOEFFS.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( (nargin < 2) || isempty(N) )\n error('CHEBFUN:TRIGTECH:chebcoeffs:input', ...\n 'F does not have a finite Chebyshev series. Please input N.');\nend\n\n% Use first-kind Chebyshev polynomials by default.\nif ( (nargin < 3) || isempty(kind) )\n kind = 1;\nend\n\n% Trivial empty case:\nif ( N <= 0 )\n out = [];\n return\nend\n\n% [TODO]: Is there a fast transfrom from TRIGTECH to CHEBTECH?\n% Since f is a TRIGTECH it is assumed to be smooth and periodic on [-1,1].\n% Computing the chebyshev coefficients via innner products requires working with\n% non-periodic, but smooth functions on [-1,1]. The right representation for f\n% is then a Chebyshev expansion. We therefore convert f to a (happy) Chebyshev\n% interpolant and return the coefficients. As an arbitrary choice we will\n% convert f to a chebtech1 and then compute the resulting coefficients.\nout = chebcoeffs(chebtech1(@(x) f.feval(x)), N, kind);\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/@trigtech/chebcoeffs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6937150115830623}} {"text": "function sol = Inverse_Kinematics(q,pd,l)\n% \npx = pd(1);\npy = pd(2);\nl1 = l(1);\nl2 = l(2);\ndistance = px^2 + py^2;\nif distance > (l1+l2)^2 \n k = pd/norm(pd);\n p = (l1+l2)*k;\n px = p(1);\n py = p(2);\nelseif distance < (l1-l2)^2\n k = pd/norm(pd);\n p = (l1-l2)*k;\n px = p(1);\n py = p(2);\nend\n\ncosq2 = (distance - l1^2 - l2^2)/2/l1/l2;\nsinq2 = sqrt(1-cosq2^2);\nsincosq2 = zeros(2,2);\nsincosq2(:,1) = [sinq2;cosq2];\nsincosq2(:,2) = [-sinq2;cosq2];\nsolutions = zeros(2,4);\nfor i=1:2\n sinq2 = sincosq2(1,i);\n cosq2 = sincosq2(2,i);\n A = l1 + l2*cosq2;\n B = l2*sinq2;\n sinq1 = (px*A - py*B)/(A^2+B^2);\n cosq1 = (px*B + py*A)/(A^2+B^2);\n q1 = atan2(sinq1,cosq1);\n q2 = atan2(sinq2,cosq2);\n solutions(:,i) = [q1;q2];\nend\n\nif solutions(1,1) > solutions(1,2)\n solutions(1,3) = solutions(1,1) - 2*pi;\n solutions(1,4) = solutions(1,2) + 2*pi;\nelse\n solutions(1,3) = solutions(1,1) + 2*pi;\n solutions(1,4) = solutions(1,2) - 2*pi;\nend\n\nif solutions(2,1) > solutions(2,2)\n solutions(2,3) = solutions(2,1) - 2*pi;\n solutions(2,4) = solutions(2,2) + 2*pi;\nelse\n solutions(2,3) = solutions(2,1) + 2*pi;\n solutions(2,4) = solutions(2,2) - 2*pi;\nend\n\ndelta = 10000;\nindex = 0;\nfor i=1:4\n if norm(q - solutions(:,i)) [V,D]=eig(A,B).\nPhiXYp = V\\(PsiXYp*V);\nPhiXYm = V\\(PsiXYm*V);\nPhiZ = V\\(PsiZ*V);\nphiX = real(diag(PhiXYp+PhiXYm)/2);\nphiY = real(diag(PhiXYp-PhiXYm)/(2i));\nphiZ = real(diag(PhiZ));\n\nazim = atan2(phiY,phiX);\nelev = atan2(phiZ,sqrt(phiX.^2+phiY.^2));\nsrc_dirs_rad = [azim elev];\n\nend\n\n\nfunction Ynimu = getYnimu(Ynm, ni, mu)\n\nN = sqrt(size(Ynm,2))-1;\n[idx_nimu, idx_nm] = muni2q(N,ni,mu);\nYnimu = zeros(size(Ynm,1),N^2);\nYnimu(:,idx_nimu) = Ynm(:,idx_nm);\n\nend\n\n\nfunction [idx_nimu, idx_nm] = muni2q(order,ni,mu)\n\nnm = [];\nfor n=0:order-1\n nm = [nm; n*ones(2*n+1,1) (-n:n)'];\nend\nnimu = [nm(:,1)+ni nm(:,2)+mu];\nqnm = nm(:,1).^2+nm(:,1)+nm(:,2)+1;\nqnimu = nimu(:,1).^2+nimu(:,1)+nimu(:,2)+1;\nidx_valid = find(abs(nimu(:,2))<=nimu(:,1));\nidx_nm = qnimu(idx_valid);\nidx_nimu = qnm(idx_valid);\n\nend\n\n\nfunction Wnimu = getWnimu(order, mm, ni, mu)\n\nnm = [];\nfor n=0:order-1\n nm = [nm; n*ones(2*n+1,1) (-n:n)'];\nend\nif mm==1\n nimu = [nm(:,1)+ni nm(:,2)+mu];\nelseif mm==-1\n nimu = [nm(:,1)+ni -nm(:,2)+mu];\nend\nw_nimu = sqrt( (nimu(:,1)-nimu(:,2)-1).*(nimu(:,1)-nimu(:,2))./((2*nimu(:,1)-1).*(2*nimu(:,1)+1)) );\nWnimu = diag(w_nimu);\n\nend\n\n\nfunction Vnimu = getVnimu(order, ni, mu)\n\nnm = [];\nfor n=0:order-1\n nm = [nm; n*ones(2*n+1,1) (-n:n)'];\nend\nnimu = [nm(:,1)+ni nm(:,2)+mu];\nv_nimu = sqrt( (nimu(:,1)-nimu(:,2)).*(nimu(:,1)+nimu(:,2)) ./((2*nimu(:,1)-1).*(2*nimu(:,1)+1)) );\nVnimu = diag(v_nimu);\n\nend\n\n\nfunction [PsiXYp, PsiXYm, PsiZ] = getPsi(Us, LambdaXYp, LambdaXYm, LambdaZ)\n\npinvUs = pinv(getYnimu(Us.',0,0).');\nPsiXYp = pinvUs*LambdaXYp;\nPsiXYm = pinvUs*LambdaXYm;\nPsiZ = pinvUs*LambdaZ;\n\nend\n\n\nfunction [PhiXYp, PhiXYm, PhiZ] = getPhi(src_dirs_rad)\n\nPhiZ = diag(cos(src_dirs_rad(:,2)));\nPhiXYp = diag( sin(src_dirs_rad(:,2)).*exp(1i*src_dirs_rad(:,1)) );\nPhiXYm = diag( sin(src_dirs_rad(:,2)).*exp(-1i*src_dirs_rad(:,1)) );\n\nend\n\n\nfunction [LambdaXYp, LambdaXYm, LambdaZ] = getLambda(Us)\n\norder = sqrt(size(Us,1))-1;\nLambdaXYp = getWnimu(order, 1,1,-1)*getYnimu(Us.', 1,-1).' - getWnimu(order,-1,0,0)*getYnimu(Us.',-1,-1).';\nLambdaXYm = -getWnimu(order,-1,1,-1)*getYnimu(Us.', 1, 1).' + getWnimu(order, 1,0,0)*getYnimu(Us.',-1, 1).';\nLambdaZ = getVnimu(order, 0, 0)*getYnimu(Us.',-1, 0).' + getVnimu(order, 1,0)*getYnimu(Us.', 1, 0).';\n\nend\n", "meta": {"author": "polarch", "repo": "Spherical-Array-Processing", "sha": "f08bed9b80ce580f9056fd6573ab0c08588ebc11", "save_path": "github-repos/MATLAB/polarch-Spherical-Array-Processing", "path": "github-repos/MATLAB/polarch-Spherical-Array-Processing/Spherical-Array-Processing-f08bed9b80ce580f9056fd6573ab0c08588ebc11/sphESPRIT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932333, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6936493609231419}} {"text": "function A = metric_03 ( p )\n\n%*****************************************************************************80\n%\n%% METRIC_03 evaluates metric #3 at any point.\n%\n% Discussion:\n%\n% This routine evaluates the matrix that determines the metric\n% at a point.\n%\n% This particular matrix exaggerates distances in the Y direction.\n%\n% It is diagonal, and it is spatially constant.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 May 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real P(2), the point at which the metric matrix is to\n% be evaluated.\n%\n% Output, real A[2,2], the metric matrix.\n%\n A = [ 1.0, 0.0; 0.0, 100.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/cvt_metric/metric_03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6936493174567798}} {"text": "function [ a_lu, info ] = r83_np_fa ( n, a )\n\n%*****************************************************************************80\n%\n%% R83_NP_FA factors a R83 matrix without pivoting.\n%\n% Discussion:\n%\n% The R83 storage format is used for a tridiagonal matrix.\n% The superdiagonal is stored in entries (1,2:N), the diagonal in\n% entries (2,1:N), and the subdiagonal in (3,1:N-1). Thus, the\n% original matrix is \"collapsed\" vertically into the array.\n%\n% Because this routine does not use pivoting, it can fail even when\n% the matrix is not singular, and it is liable to make larger\n% errors.\n%\n% R83_NP_FA and R83_NP_SL may be preferable to the corresponding\n% LINPACK routine SGTSL for tridiagonal systems, which factors and solves\n% in one step, and does not save the factorization.\n%\n% Example:\n%\n% Here is how a R83 matrix of order 5 would be stored:\n%\n% * A12 A23 A34 A45\n% A11 A22 A33 A44 A55\n% A21 A32 A43 A54 *\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 November 2003\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be at least 2.\n%\n% Input, real A(3,N), the tridiagonal matrix.\n%\n% Output, integer INFO, singularity flag.\n% 0, no singularity detected.\n% nonzero, the factorization failed on the INFO-th step.\n%\n% Output, real A_LU(3,N), factorization information.\n%\n info = 0;\n\n a_lu(1:3,1:n) = a(1:3,1:n);\n\n for i = 1 : n-1\n\n if ( a_lu(2,i) == 0.0E+00 )\n info = i;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R83_NP_FA - Fatal error!\\n' );\n fprintf ( 1, ' Zero pivot on step %d\\n', info );\n return;\n end\n%\n% Store the multiplier in L.\n%\n a_lu(3,i) = a_lu(3,i) / a_lu(2,i);\n%\n% Modify the diagonal entry in the next column.\n%\n a_lu(2,i+1) = a_lu(2,i+1) - a_lu(3,i) * a_lu(1,i+1);\n\n end\n\n if ( a_lu(2,n) == 0.0E+00 )\n info = n;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R83_NP_FA - Fatal error!\\n' );\n fprintf ( 1, ' Zero pivot on step %d\\n', info );\n return;\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/r83_np_fa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.6936492976184739}} {"text": "function [x,state] = struct_triu(z,task)\n%STRUCT_TRIU Upper triangular matrix.\n% [x,state] = struct_triu(z) generates x as a lower triangular matrix by\n% using the vector z to fill the matrix column by column. For a matrix x\n% of order n, the vector z should have length n*(n+1)/2. The structure\n% state stores information which is reused in computing the right and\n% left Jacobian-vector products.\n%\n% struct_triu(z,task) computes the right or left Jacobian-vector\n% product of this transformation, depending on the structure task. Use\n% the structure state and add the field 'r' of the same shape as z or the\n% field 'l' of the same shape as x to obtain the structure task for\n% computing the right and left Jacobian-vector products\n% \n% (dF(:)/dz(:).')*task.r(:) and\n% (dF(:)/dz(:).')'*task.l(:) + conj((dF(:)/dconj(z(:)).')'*task.l(:)),\n% \n% respectively. Here, F(z) represents this transormation, (:) signifies\n% vectorization and the derivative w.r.t. z (conj(z)) is a partial\n% derivative which treats conj(z) (z) as constant. The output has the\n% same shape as x or z for the right and left Jacobian-vector products,\n% respectively.\n% \n% See also struct_band, struct_diag, struct_tridiag, struct_tril.\n\n% Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)\n% Marc Van Barel (Marc.VanBarel@cs.kuleuven.be)\n% Lieven De Lathauwer (Lieven.DeLathauwer@kuleuven-kulak.be)\n%\n% References:\n% [1] L. Sorber, M. Van Barel, L. De Lathauwer, \"Structured data fusion,\"\n% ESAT-SISTA Internal Report 13-177, KU Leuven, 2013.\n\nif nargin < 2, task = []; end\nn = 0.5*(-1+sqrt(1+8*length(z)));\n[x,state] = struct_band(z,task,[n n],[0 n-1]);\n\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/+tensorlab/struct_triu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138364, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.6936492917417014}} {"text": "% Computes the hessian numerically\n% \n% ::\n% \n% [H,issue]=numerical(fh,xbest,hessian_type)\n% \n% Args:\n% \n% - **fh** [char|function handle]: one-dimensional objective function\n% - **xbest** [vector]: point at which the hessian has to be computed\n% - **hessian_type** [{'fd'}|'opg']: type of hessian computed : finite\n% differences or outer-product-gradient\n% \n% Returns:\n% :\n% \n% - **H** [d x d matrix]: hessian\n% - **issue** [''|char]: description of any problem encountered during the\n% calculation of the hessian.\n% \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/+utils/+hessian/numerical.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6934535243505073}} {"text": "function engine = bk_ff_hmm_inf_engine(bnet)\n% BK_FF_HMM_INF_ENGINE Naive (HMM-based) implementation of fully factored form of Boyen-Koller \n% engine = bk_ff_hmm_inf_engine(bnet)\n%\n% This is implemented on top of the forwards-backwards algo for HMMs,\n% so it is *less* efficient than exact inference! However, it is good for educational purposes,\n% because it illustrates the BK algorithm very clearly.\n\n[persistent_nodes, transient_nodes] = partition_dbn_nodes(bnet.intra, bnet.inter);\nassert(isequal(sort(bnet.observed), transient_nodes));\n[engine.prior, engine.transmat] = dbn_to_hmm(bnet);\n\nss = length(bnet.intra);\n\nengine.bel = [];\nengine.bel_marginals = [];\nengine.marginals = [];\n\n\nengine = class(engine, 'bk_ff_hmm_inf_engine', inf_engine(bnet));\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/inference/dynamic/@bk_ff_hmm_inf_engine/bk_ff_hmm_inf_engine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.6934535213601697}} {"text": "function [r1,r2] = quad_roots(a1, a2, a3)\n\nt1 = -a2/2./a1;\nt2 = sqrt(a2.^2 - 4*a1.*a3)/2./a1;\nr1 = t1 + t2;\nr2 = t1 - t2;\n", "meta": {"author": "FuzhenZhuang", "repo": "Transfer-Learning-Toolkit", "sha": "24b5323b354aee844b8b7df9fcad17fdfb191dc4", "save_path": "github-repos/MATLAB/FuzhenZhuang-Transfer-Learning-Toolkit", "path": "github-repos/MATLAB/FuzhenZhuang-Transfer-Learning-Toolkit/Transfer-Learning-Toolkit-24b5323b354aee844b8b7df9fcad17fdfb191dc4/utilities/TLLibrary64/LR/fastfit/quad_roots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741241296944, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6934505812513111}} {"text": "function [ds, S, p] = multivar_dist(X, varargin)\n% multivariate normality checking and diagnostic plots\n%\n% :Usage:\n% ::\n%\n% [ds, S, p] = multivar_dist(X)\n%\n% :Input:\n%\n% given matrix X with cases = rows, cols = variables\n%\n% :Optional input:\n%\n% 'noplot' : suppress plot\n%\n% :Outputs:\n%\n% **ds:**\n% is matrix of squared distances, case numbers, and\n% expected chi2 values (in columns in this order)\n% rows are cases\n%\n% NOTE: Sorted in order of ascending distance!\n%\n% **S:**\n% estimated covariance matrix\n%\n% **mv_distance:**\n% squared distances in original order of rows\n%\n% **p:**\n% p-values in original order of rows\n%\n% ..\n% by Tor Wager\n% ..\n\n % ..\n % determine multivariate standard deviation matrix S\n % ..\n\n doplot = true;\n doverbose = true;\n \n if any(strcmp(varargin, 'noplot')), doplot = false; end\n if any(strcmp(varargin, 'noverbose')), doverbose = false; end\n \n % center\n Xs = X - repmat(mean(X), size(X, 1), 1);\n\n % covariance matrix S\n S = (Xs' * Xs) ./ (size(Xs, 1)-1);\n\n % -----------------------------------------------------\n % * get squared distance\n % -----------------------------------------------------\n\n % squared distance, Johnson & Wichern p. 201\n % (X-mean(X))' * inv(S) * (X - mean(X)) generalized to matrices\n d = Xs * inv(S) * Xs';\n d = diag(d); % what do the off-diagonals signify?\n\n % -----------------------------------------------------\n % * compare with chi2 distribution\n % -----------------------------------------------------\n\n % calculate chi2 threshold\n % chi2 value compares the number of points within the ellipsoid\n % contour to those outside; roughly alpha of the squared distances\n % should be within the ellipsoid (for rough general test of normality).\n % outliers will have very high chi2 values\n\n t = chi2inv(.5, size(X, 2)); % for general test\n p50 = 100 * (sum(d > t) ./ length(d));\n \n if doverbose\n fprintf(1, 'Expected 50%% of points within 50%% normal ellipsoid, found %3.2f%%\\n', p50);\n end\n \n t = chi2inv(.95, size(X, 2)); % for general test\n p95 = sum(d > t);\n \n if doverbose\n fprintf(1, 'Expected %3.2f outside 95%% ellipsoid, found %3.0f\\n', .05*length(d), p95);\n end\n \n % -----------------------------------------------------\n % * get case numbers and sort by distance\n % -----------------------------------------------------\n d(:,2) = (1:length(d))';\n ds = sortrows(d, 1);\n\n\n % -----------------------------------------------------\n % * get chi2 quantiles for qd plot\n % -----------------------------------------------------\n q = (((1:size(ds, 1)) - .5) ./ size(ds, 1))';\n q = chi2inv(q, size(X, 2));\n ds(:,3) = q;\n\n % -----------------------------------------------------\n % * get distance^2 in original order and p-values\n % -----------------------------------------------------\n ds = sortrows(ds, 2);\n p = 1 - chi2cdf(ds(:,1), size(X, 2));\n\n\n % -----------------------------------------------------\n % * plot the results in a figure\n % -----------------------------------------------------\n if doplot\n \n figure('color', 'w');\n subplot(1, 3, 1); hold on; grid on\n plot([1:size(d, 1); 1:size(d, 1)], [zeros(size(d, 1), 1) d(:,1)]', 'b', 'LineWidth', 1.5);\n xlabel('Case number');\n ylabel('Squared stat. distance from origin');\n wh = (d(:,1) > t); d2 = d; d2(:,1) = d2(:,1) .* wh; % zero out the non-\"significant\" chi2 cases\n plot([1:size(d2, 1); 1:size(d2, 1)], [zeros(size(d2, 1), 1) d2(:,1)]', 'r', 'LineWidth', 1.5);\n title('d^2, red cases outside 95% normal ellipsoid');\n plot([0 size(d, 1)], [t t], 'k');\n set(gca, 'YLim', [0 max(t+.5, max(d(:,1)))]);\n \n subplot(1, 3, 2); hold on; grid on\n plot(ds(:,3), ds(:,1), 'MarkerSize', 0.01, 'Color', 'w');\n for i = 1:size(ds, 1)\n text(ds(i,3), ds(i, 1), num2str(ds(i, 2)), 'Color', 'k');\n end\n xlabel('Expected chi2 value'), ylabel('Squared distance');\n plot([0 max([ds(:,3);ds(:,1)])], [0 max([ds(:,3);ds(:,1)])], 'k', 'LineWidth', 1.5);\n title('Line with slope = 1 is normal');\n \n subplot(1, 3, 3);\n imagesc(cov(X'));\n colorbar\n \n end\n \nend\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/diagnostics/multivar_dist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6933745064318633}} {"text": "function M = getmassmat(node,elem2dof,area,type,K)\n%% GETMASSMAT Get mass matrix of the finite element space\n%\n% M = GETMASSMAT(elem2edge,area,Dlambda,elemType,K) get mass matrix of the finite element\n% space specified by elemType. \n%\n% The type can be: \n% - lump: lumped mass matrix for P1 element\n% - HB: Hierarchical basis for P2 element\n% - NB: Nodal basis for P2 element\n% - NBB: Nodal basis with bubble functions for P2 element\n%\n% All cases for P2 element are added by Lin Zhong.\n\nN = size(node,1);\nNT = length(area);\nNdof = double(max(elem2dof(:)));\n\n%% Coefficients\nif ~exist('type','var'), type = 'P1'; end\nif ~exist('K','var'), K = []; end\n\n%% Assembling\nn = size(elem2dof,2);\nswitch n\n case 3 %% P1 element\n %% Assemble the mass matrix by the mass lumping\n if strcmp(type,'lump')\n M = accumarray([elem2dof(:,1);elem2dof(:,2);elem2dof(:,3)],...\n [area;area;area]/3,[Ndof,1]);\n if exist('K','var') && ~isempty(K) && ~isnumeric(K) % K is a function\n M = K(node).*M;\n elseif exist('K','var') && ~isempty(K) && isnumeric(K) && size(K,1) == N \n M = K.*M;\n end \n M = spdiags(M,0,N,N);\n else %% Assemble the full mass matrix\n if exist('K','var') && ~isempty(K) && ~isnumeric(K) % K is a function\n center = (node(elem2dof(:,1),:) + node(elem2dof(:,2),:) + ...\n node(elem2dof(:,3),:))/3;\n area = K(center).*area;\n elseif exist('K','var') && ~isempty(K) && isnumeric(K) && size(K,1) == NT \n area = K.*area;\n end \n M = sparse(N,N);\n for i = 1:3\n for j = 1:3\n Mij = area*((i==j)+1)/12;\n M = M + sparse(elem2dof(:,i),elem2dof(:,j),Mij,Ndof,Ndof); \n end\n end\n end\n case 6 %% P2 element\n %% Mass matrices for NBB bases\n if strcmp(type,'NBB')\n elem2dof(:,7) = uint32(Ndof+(1:NT)'); % add bubble index \n Ndof = double(max(elem2dof(:)));\n elemM(1:NT,7) = 9/20;\n elemM(1:NT,1:3) = 1/20;\n elemM(1:NT,4:6) = 2/15;\n elemM = elemM.*repmat(area,1,7);\n diagM = accumarray(elem2dof(:), elemM(:), [Ndof 1]);\n M = spdiags(double(diagM),0,Ndof,Ndof);\n return;\n end\n %% Mass matrices for HB or NB bases\n [lambda, w] = quadpts(4);\n nQuad = size(lambda,1);\n if strcmp(type,'HB')\n phi(:,1) = lambda(:,1);\n phi(:,2) = lambda(:,2);\n phi(:,3) = lambda(:,3);\n elseif strcmp(type,'NB')\n phi(:,1) = lambda(:,1).*(2*lambda(:,1)-1);\n phi(:,2) = lambda(:,2).*(2*lambda(:,2)-1);\n phi(:,3) = lambda(:,3).*(2*lambda(:,3)-1);\n end\n phi(:,4) = 4*lambda(:,2).*lambda(:,3);\n phi(:,5) = 4*lambda(:,3).*lambda(:,1);\n phi(:,6) = 4*lambda(:,1).*lambda(:,2);\n\n Nbases = 6; NMhalf = 21;\n ii = zeros(NMhalf*NT,1); \n jj = zeros(NMhalf*NT,1); \n sM = zeros(NMhalf*NT,1);\n index = 0;\n for i = 1:Nbases\n for j = i:Nbases\n Mij = 0;\n for p = 1:nQuad\n Mij = Mij + w(p)*phi(p,i).*phi(p,j);\n end\n Mij = Mij.*area;\n ii(index+1:index+NT) = double(elem2dof(:,i)); \n jj(index+1:index+NT) = double(elem2dof(:,j));\n sM(index+1:index+NT) = Mij;\n index = index + NT;\n end\n end\n clear Mij\n diagIdx = (ii == jj); upperIdx = ~diagIdx;\n M = sparse(ii(diagIdx),jj(diagIdx),sM(diagIdx),Ndof,Ndof);\n MU = sparse(ii(upperIdx),jj(upperIdx),sM(upperIdx),Ndof,Ndof);\n M = M + MU + MU';\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/iFEM/afem/getmassmat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802529509911, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6933745030301948}} {"text": "%%%\n%> @brief computes the pose vector v from an homogeneous transformation A\n%> param A homogeneous transformation\n%> return v pose vector\n%> @author Giorgio Grisetti\n%%%\nfunction v = t2v(A)\n% T2V homogeneous transformation to vector\nv(1:2,1) = A(1:2,3);\nv(3,1) = atan2(A(2,1), A(1,1));\nend", "meta": {"author": "versatran01", "repo": "graphslam", "sha": "c09bb80285e7356897b5cb39f236f84731bc976f", "save_path": "github-repos/MATLAB/versatran01-graphslam", "path": "github-repos/MATLAB/versatran01-graphslam/graphslam-c09bb80285e7356897b5cb39f236f84731bc976f/lsslam/t2v.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6933744996611187}} {"text": "% Nonlinear model of two CSTRs in series from\n%\n% Henson, M.A. and Seborg, D.E., Feedback Linearizing Control, Chap. 4 of Nonlinear Process\n% Control, Edited by Hensen, M.A. and Seborg, D.E., Prentice Hall (1997)\n%\n% t -- time (not used)\n% y -- state value vector\n% xdot -- set to the vector of state derivatives\n\nfunction xdot = cstr5(t,y)\n\nglobal u\n\n% Input (1):\n% Coolant Flowrate (L/min)\nqc = u;\n\n% States (4):\n% Concentration of A in Reactor #1 (mol/L)\nCa1 = y(1);\n% Temperature of Reactor #1 (K)\nT1 = y(2);\n% Concentration of A in Reactor #2 (mol/L)\nCa2 = y(3);\n% Temperature of Reactor #2 (K)\nT2 = y(4);\n\n% Parameters\n% Flowrate (L/min) \nq = 100;\n% Feed Concentration of A (mol/L)\nCaf = 1.0;\n% Feed Temperature (K)\nTf\t= 350.0 ;\n% Coolant Temperature (K)\nTcf = 350.0;\n% Volume of Reactor #1 (L)\nV1 = 100;\n% Volume of Reactor #2 (L)\nV2 = 100;\n% UA1 or UA2 - Overall Heat Transfer Coefficient (J/min-K)\nUA1 = 1.67e5;\nUA2 = 1.67e5;\n% Pre-exponential Factor for A->B Arrhenius Equation\nk0 = 7.2e10;\n% EoverR - E/R (K) - Activation Energy (J/mol) / Gas Constant (J/mol-K)\nEoverR = 1e4;\n% Heat of Reaction - Actually (-dH) for an exothermic reaction (J/mol)\ndH = 4.78e4;\n% Density of Fluid (g/L)\nrho = 1000;\n% Density of Coolant Fluid (g/L)\nrhoc = 1000;\n% Heat Capacity of Fluid (J/g-K)\nCp = 0.239;\n% Heat Capacity of Coolant Fluid (J/g-K)\nCpc = 0.239;\n\n%\tDynamic Balances\n \n%\tdCa1/dt\nxdot(1,1) = q*(Caf-Ca1)/V1 - k0*Ca1*exp(-EoverR/T1);\n%\tdT1/dt\nxdot(2,1) = q*(Tf-T1)/V1 + (dH*k0/rho/Cp)*Ca1*exp(-EoverR/T1) + ...\n rhoc*Cpc/rho/Cp/V1 * qc * (1-exp(-UA1/qc/rhoc/Cpc)) * (Tcf-T1);\n%\tdCa2/dt\nxdot(3,1) = q*(Ca1-Ca2)/V2 - k0*Ca2*exp(-EoverR/T2);\n%\tdT2/dt\nxdot(4,1) = q*(T1-T2)/V2 + (dH*k0/rho/Cp)*Ca2*exp(-EoverR/T2) + ...\n rhoc*Cpc/rho/Cp/V2 * qc * (1-exp(-UA2/qc/rhoc/Cpc)) * ...\n (T1 - T2 + exp(-UA1/qc/rhoc/Cpc)*(Tcf-T1));\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/15240-dual-cstr-nonlinear-differential-equation-model/cstr5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6933744979765807}} {"text": "function [rc,rcb,Pf,Pb] = pc2rcv(pc,R0)\n\n%function [rc,rcb] = pc2rcv(pc,R0)\n% Transforms normalized correlation matrices pc into \n% forward and backward reflection coefficients rc and rcb.\n\n% S. de Waele, March 2003.\n\nif ~isstatv(pc), error('Partial correlations non-stationairy!'), end\n\ns = kingsize(pc);\norder = s(3)-1;\ndim = s(1); I = eye(dim);\n%if nargin == 1, R0 = I; end\n\nrc = zeros(s); rc(:,:,1) = I; \nPf = zeros(s); Pf(:,:,1) = R0;\n\nrcb = zeros(s); rcb(:,:,1) = I; \nPb = zeros(s); Pb(:,:,1) = R0;\n\nfor p = 1:order,\n TsqrtPf = Tsqrt( Pf(:,:,p)); %square root M defined by: M=Tsqrt(M)*Tsqrt(M)'\n TsqrtPb= Tsqrt(Pb(:,:,p)); \n %reflection coefficients\n rc(:,:,p+1) = -TsqrtPf *pc(:,:,p+1) *inv(TsqrtPb);\t\n rcb(:,:,p+1)= -TsqrtPb*pc(:,:,p+1)'*inv(TsqrtPf ); \n %residual matrices\n Pf(:,:,p+1) = (I-TsqrtPf *pc(:,:,p+1) *pc(:,:,p+1)'*inv(TsqrtPf ))*Pf(:,:,p); \n Pb(:,:,p+1) = (I-TsqrtPb*pc(:,:,p+1)'*pc(:,:,p+1) *inv(TsqrtPb))*Pb(:,:,p); \nend %for p = 2:order,\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/3680-automatic-spectral-analysis/AutomaticSpectra/Vectors/conversions/pc2rcv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.693374491227564}} {"text": "function complextest_AD1()\n% Test AD for a complex optimization problem on a product manifold (struct)\n\n % Verify that Manopt was indeed added to the Matlab path.\n if isempty(which('spherecomplexfactory'))\n error(['You should first add Manopt to the Matlab path.\\n' ...\n\t\t 'Please run importmanopt.']);\n end\n \n % Verify that the deep learning tool box was installed\n assert(exist('dlarray', 'file') == 2, ['Deep learning tool box is '... \n 'needed for automatic differentiation.\\n Please install the'...\n 'latest version of the deep learning tool box and \\nupgrade to Matlab'...\n ' R2021b if possible.'])\n \n % Generate the problem data.\n n = 100;\n A = randn(n) + 1i*randn(n);\n A = .5*(A+A');\n \n % Create the product manifold\n S = spherecomplexfactory(n);\n manifold.x = S;\n manifold.y = S;\n problem.M = productmanifold(manifold); %struct\n \n % For Matlab R2021b or later, define the problem cost function as usual\n % problem.cost = @(X) -real(X.x'*A*X.y);\n \n % For Matlab R2021a or earlier, translate the cost function into a \n % particular format with the basic functions in /functions_AD\n problem.cost = @(X) -creal(cprod(cprod(ctransp(X.x), A), X.y));\n\n % Define the gradient and the hessian via automatic differentiation\n problem = manoptAD(problem);\n\n % Numerically check gradient and Hessian consistency.\n figure;\n checkgradient(problem);\n figure;\n checkhessian(problem);\n \n % Solve.\n [x, xcost, info] = trustregions(problem); %#ok\n \n % Test\n ground_truth = svd(A);\n distance = abs(ground_truth(1) - (-problem.cost(x)));\n fprintf('The distance between the ground truth and the solution is %e \\n',distance);\n\n \nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/autodiff/basic_examples_AD/complextest_AD1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6933067992424615}} {"text": "function A = create_2d_image_downsample_matrix(szin, k)\n szout = ceil(szin / k);\n \n npixin = prod(szin);\n npixout = prod(szout);\n \n A = sparse(npixout, npixin);\n [m1, m2] = ndgrid(1:szin(1), 1:szin(2));\n \n mm1 = ceil(m1 / k);\n mm2 = ceil(m2 / k);\n \n m1 = m1(:); m2 = m2(:);\n mm1 = mm1(:); mm2 = mm2(:);\n \n rr = (mm2-1)*szout(1) + mm1;\n cc = (m2-1)*szin(1) + m1;\n A = sparse(rr, cc, 1/k^2, npixout, npixin);\n \n% return;\n \nend", "meta": {"author": "visva89", "repo": "pTVreg", "sha": "c359620e3c8435392db02354274d6c74d682d437", "save_path": "github-repos/MATLAB/visva89-pTVreg", "path": "github-repos/MATLAB/visva89-pTVreg/pTVreg-c359620e3c8435392db02354274d6c74d682d437/mutils/My/deformation_tools_cpp/create_2d_image_downsample_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6933067924796423}} {"text": "function [fSignificanceLevel] = pf_OverallSignificance(nNumberNodesTotal, nNumberNodesHit, fHitProbability)\n\nfIncSumProb = [];\nfSumProb = 0;\nfor nCnt_= 0:nNumberNodesTotal\n nNumberCombinations = nchoosek(nNumberNodesTotal, nCnt_);\n fProbCombination = ((1 - fHitProbability)^(nNumberNodesTotal - nCnt_) * fHitProbability^nCnt_) * nNumberCombinations;\n fSumProb = fSumProb + fProbCombination;\n fIncSumProb = [fIncSumProb; fSumProb];\nend\nfSignificanceLevel = 1 - (fIncSumProb(nNumberNodesHit + 1));\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/danijel/probfore/pf_OverallSignificance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6932968166744191}} {"text": "function pass = test_harmonic( ) \n% simple tests for cylindrical harmonic command.\n\ntol = 3e2*chebfunpref().cheb2Prefs.chebfun2eps;\n\n\n%example: build via jbessel w/known bessel root \n %L = 5, m = 3; \n F = diskfun(@(t,r) sqrt(2)/ (sqrt(pi)*abs(besselj(5+1, 15.7001740797116)))...\n *besselj(5, 15.7001740797116*r).*cos(5*t), 'polar'); \n G = diskfun.harmonic(5,3); \n pass(1) = norm( F-G ) < tol;\n \n F = diskfun(@(t,r) sqrt(2)/ (sqrt(pi)*abs(besselj(5+1, 15.7001740797116)))...\n *besselj(5, 15.7001740797116*r).*sin(5*t), 'polar'); \n G = diskfun.harmonic(-5,3); \n pass(2) = norm( F-G ) < tol;\n \n%L = 0, m = 5; \n F = diskfun(@(t,r) sqrt(2)/ (sqrt(2*pi)*abs(besselj(0+1, 14.9309177084877)))...\n *besselj(0, 14.9309177084877*r), 'polar'); \n G = diskfun.harmonic(0,5); \n pass(3) = norm(F-G) < tol;\n\n%test orthonormality \n\nA=diskfun.harmonic(29,10);\nB=diskfun.harmonic(6,23);\nC = diskfun.harmonic(-4, 3); \npass(4) = abs(sum2(A.*A)-1) < tol; \npass(5) = abs(sum2(B.*B)-1) < tol; \npass(6) = abs(sum2(A.*B)) < tol; \npass(7) = abs(sum2(A.*C)) < tol; \npass(8) = abs(sum2(C.*C)-1) < tol; \n\n%neumann conditions, test orthonormal\nA = diskfun.harmonic(10,8, 'neumann'); \nB = diskfun.harmonic(-4, 3, 'neumann'); \npass(8) = abs(sum2(A.*A)-1) < tol; \npass(9) = abs(sum2(B.*B)-1) < tol; \npass(10) = abs(sum2(A.*B)) < tol; \n\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/diskfun/test_harmonic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6932968115505389}} {"text": "function S=triplyPeriodicMinimal(varargin)\n\n% function S=triplyPeriodicMinimal(X,Y,Z,typeStr)\n% ------------------------------------------------------------------------\n% This function creates the image S which can be used to define triply\n% periodic minimal surfaces. The input consists of a grid of coordinates\n% (X,Y,Z) and the surface type (typeStr). \n%\n% 2009 Created\n% 2016 Updated input handling\n% 2018/12/13 Added comments at top of function\n% ------------------------------------------------------------------------\n\n%%\n%Parse input\nswitch nargin\n case 2\n P=varargin{1};\n X=P(:,1); Y=P(:,2); Z=P(:,3); %Get coordinates\n typeStr=varargin{2}; %Get the surface type string\n case 4\n X=varargin{1};\n Y=varargin{2};\n Z=varargin{3};\n typeStr=varargin{4};\n otherwise\n error('False number of input arguments.');\nend\n\n%Evaluate metric on coordinates\nswitch typeStr\n case 'p' %Schwarz P\n S=(cos(X)+cos(Y)+cos(Z));\n case 'd' %Schwarz D\n S=(sin(X).*sin(Y).*sin(Z))...\n +(sin(X).*cos(Y).*cos(Z))...\n +(cos(X).*sin(Y).*cos(Z))...\n +(cos(X).*cos(Y).*sin(Z));\n case 'g' %Schoen Gyroid\n S=(sin(X).*cos(Y))+(sin(Y).*cos(Z))+(cos(X).*sin(Z)); \n case 'n' %Neovius\n S=3*(cos(X)+ cos(Y)+ cos(Z))+ (4*cos(X).*cos(Y).*cos(Z));\n case 'w'\n S=2*(cos(X).*cos(Y)+cos(Z).*cos(X)+cos(Y).*cos(Z))-(cos(2*X)+cos(2*Y)+cos(2*Z));\n case 'pw'\n S=(4.*(cos(X).*cos(Y)+cos(Y).*cos(Z)...\n +cos(Z).*cos(X))-3.*cos(X).*cos(Y).*cos(Z))+2.4;\n otherwise\n error('unknown surface type requested')\nend\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/triplyPeriodicMinimal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.6932768097054856}} {"text": "function [dateV] = doy2date(doyV,yearV)\n% DOY2DATE.m will convert a vector of day of year numbers and years\n% and convert them to MATLAB date format.\n%\n% Sample Call:\n% doyV = [54;200.4315];\n% yearV = [2009;2009];\n% [dateV] = doy2date(doyV,yearV);\n%\n% Inputs:\n% doyV -> vector of day of year numbers (n x 1)\n% yearV -> vector of years (n x 1)\n%\n% Outputs:\n% dateV -> vector of MATLAB dates (n x 1)\n%\n% AUTHOR : A. Booth (ashley [at] boothfamily [dot] com)\n% DATE : 22-May-2009 09:34:53\n% Revision : 1.00\n% DEVELOPED : 7.4.0.287 (R2007a) Windows XP\n% FILENAME : doy2date.m\n\n%Check size of incoming vectors\nif (size(doyV,1)== 1) | (size(doyV,2) == 1) %Make sure only a nx1 vector\n if size(doyV,1) length(Y)\n warning('The number of requested divisions is larger than the amount of data. The number of divisions was changed to the length of the data.')\n nDivisions = length(Y);\nend\n\n% Leave One Out quick method...\nif nDivisions == length(Y)\n groupAssignment = randperm(nDivisions)';\n return\nend\n\n% Y may contain NaNs. These are treated at missing data. All NaNs are\n% distributed evenly across the folds. To do this we make a virtual class\n% for nan and then use the same code below.\nnanVals = isnan(Y);\nif any(nanVals)\n Y(nanVals) = max(Y(~nanVals))+1;\nend\n\nsortedY = sort(Y);\nnSamples = length(Y);\nsortedGroupAssignment = repmat((1:nDivisions)',ceil(nSamples/nDivisions),1);\nsortedGroupAssignment = sortedGroupAssignment(1:nSamples);\n\n% Randomize within each class and revert back to the original order\ngroupAssignment = zeros(size(Y));\nuY = unique(Y);\nnClasses = length(uY);\nfor iClass = 1:nClasses\n cSortedGroupAssignment = sortedGroupAssignment(sortedY == uY(iClass));\n groupAssignment(Y==uY(iClass)) = cSortedGroupAssignment(randperm(sum(sortedY == uY(iClass))));\nend\n\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/util/prtUtilEquallySubDivideData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.6932767839494621}} {"text": "function bessel_i1_values_test ( )\n\n%*****************************************************************************80\n%\n%% BESSEL_I1_VALUES_TEST demonstrates the use of BESSEL_I1_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 February 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BESSEL_I1_VALUES_TEST:\\n' );\n fprintf ( 1, ' BESSEL_I1_VALUES stores values of \\n' );\n fprintf ( 1, ' the Bessel I1 function.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X I1(X)\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, x, fx ] = bessel_i1_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %12f %24.16f\\n', x, fx );\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/test_values/bessel_i1_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.6932767808082848}} {"text": "function a = conex2_inverse ( alpha )\n\n%*****************************************************************************80\n%\n%% CONEX2_INVERSE returns the inverse of the CONEX2 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real ALPHA, the scalar defining A. \n% A common value is 100.0. ALPHA must not be zero.\n%\n% Output, real A(3,3), the matrix.\n%\n a = zeros ( 3, 3 );\n\n if ( alpha == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CONEX2_INVERSE - Fatal error!\\n' );\n fprintf ( 1, ' The input value of ALPHA was zero.\\n' );\n error ( 'CONEX2_INVERSE - Fatal error!' );\n end\n\n a(1,1) = 1.0;\n a(1,2) = ( 1.0 - alpha * alpha ) / alpha;\n a(1,3) = ( 1.0 + alpha * alpha ) / alpha^2;\n\n a(2,1) = 0.0;\n a(2,2) = alpha;\n a(2,3) = 1.0;\n\n a(3,1) = 0.0;\n a(3,2) = 0.0;\n a(3,3) = 1.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/test_mat/conex2_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253257, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6932358557952908}} {"text": "function circle2 = transformCircle3d(circle, tfm)\n%TRANSFORMCIRCLE3D Transform a 3D circle with a 3D affine transformation.\n%\n% CIRCLE2 = transformPlane3d(CIRCLE, TFM)\n%\n% Example\n% circle = [1 1 1 2 45 45 0];\n% tfm = createRotationOz(pi);\n% circle2 = transformCircle3d(circle, tfm);\n% figure('color','w'); hold on; axis equal tight; view(-10,25);\n% xlabel('x'); ylabel('y'); zlabel('z');\n% drawCircle3d(circle,'r'); drawPoint3d(circle(1:3),'r+')\n% drawCircle3d(circle2,'g'); drawPoint3d(circle2(1:3),'g+')\n%\n% See also \n% transforms3d, transformPoint3d, transformVector3d, transformLine3d, \n% transformPlane3d\n%\n\n% ------\n% Author: oqilipo\n% E-mail: N/A\n% Created: 2022-12-03, using MATLAB 9.13.0.2080170 (R2022b) Update 1\n% Copyright 2022\n\nparser = inputParser;\naddRequired(parser, 'circle', @(x) validateattributes(x, {'numeric'},...\n {'ncols',7,'real','finite','nonnan'}));\naddRequired(parser, 'tfm', @isTransform3d);\nparse(parser, circle, tfm);\ncircle = parser.Results.circle;\ntfm = parser.Results.tfm;\n\n% Compute transformation from local basis to world basis\ninitialTfm = localToGlobal3d(circle(1:3), circle(5), circle(6), circle(7));\n% Add the additional transformation\nnewTfm = tfm*initialTfm;\n\n% Convert to Euler angles\n[phi, theta, psi] = rotation3dToEulerAngles(newTfm, 'ZYZ');\n\n% Create transformed circle\ncircle2 = [transformPoint3d(circle(1:3), tfm), circle(4), theta, phi, psi];\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/transformCircle3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6932358557952907}} {"text": "clear;\nbeta1=[2 0.9];\nbeta0=[3 2 ];\n% fitfunc=@(x,betav)(betav(1)*x.^2+betav(2)*x+betav(3));\nfitfunc=@(x,betav) betav(1)*x.^3.*1./(exp(x./betav(2))-1);\n% fitfunc=@(x,betav) (sin(betav(1).*x)+0.1*cos(betav(2).*x)+0.15*sin(betav(3).*x));\n% fitfunc=@(x,betav) betav(1).*x+betav(2)+betav(3)*x.^2+betav(4).*x.^3;\n% fitfunc=@(x,betav) betav(3)*sqrt(2*pi)*abs(betav(2)) *normpdf(x,betav(1),abs(betav(2)));\n% fitfunc=@(x,betav) betav(1).*x+betav(2)+betav(3)*x.^2+betav(4).*x.^3+...\n% betav(5).*x.^4+betav(6).*x.^5+betav(7).*x.^6+betav(8).*x.^7;\n\nerror=0.01 ;\nx=[10*eps:0.5:10];\ny=fitfunc(x,beta1);\ny=y+(randn(size(y)))*error;\nyerr=error.*ones(size(y));\n\n\nerrorbarm([x; y; yerr; ])\n% pause\ntextposition=[];\nplotbool=true;\naxisin=[-10 15 0 12];\naxisin=[];\nheadercell={'Nonlinear Fit' '$f(x)=\\frac{A_0}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\frac{-(x-\\mu)^2}{2\\sigma}}$' ''};\nmylabel={'xaxis','yaxis [cm]','$\\mu$','$\\sigma$' '$A_0$'};\n\n\n[beta betaerr chi prob chiminvec]=wnonlinfit(x,y,yerr,fitfunc,beta0...\n ,'chitol',5,'label',mylabel,'position',textposition,...\n 'header',headercell,...\n 'printchi','off','axis',axisin,'errprec',2);\n\n\n print -dpdf -cmyk test.pdf\n\n \n% figure(2)\n% print -dpdf -cmyk testres.pdf \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/35565-weighted-nonlinear-curve-fit-script-with-plotter/example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6932279533735991}} {"text": "function Ht = riskmetrics(data,lambda,backCast)\n% Computes the Riskmetrics or other EWMA covariance\n%\n% USAGE:\n% [HT] = riskmetrics(DATA,LAMBDA,BACKCAST)\n%\n% INPUTS:\n% DATA - A T by K matrix of zero mean residuals -OR-\n% K by K by T array of covariance estimators (e.g. realized covariance)\n% LAMBDA - EWMA smoothing parameter 0=1\n error('LAMBDA must be between 0 and 1.')\nend\n\nif isempty(backCast)\n endPoint = max(min(floor(log(.01)/log(lambda)),T),k);\n weights = (1-lambda).*lambda.^(0:endPoint-1);\n weights = weights/sum(weights);\n backCast = zeros(k);\n for i=1:endPoint\n backCast = backCast + weights(i)*data(:,:,i);\n end\n \nend\n\nbackCast = (backCast+backCast)/2;\nif min(eig(backCast))<0\n error('BACKCAST must be positive semidefinite if provided.')\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nHt = zeros(k,k,T);\nHt(:,:,1) = backCast;\nfor i=2:T\n Ht(:,:,i) = (1-lambda)*data(:,:,i-1) + lambda * Ht(:,:,i-1);\nend", "meta": {"author": "bashtage", "repo": "mfe-toolbox", "sha": "9622b6c546bc6d649fd9bf0a36a7fcd53872e04a", "save_path": "github-repos/MATLAB/bashtage-mfe-toolbox", "path": "github-repos/MATLAB/bashtage-mfe-toolbox/mfe-toolbox-9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/multivariate/riskmetrics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.6932255672459509}} {"text": "%%\n% Test for power diagrams\n\naddpath('../toolbox/');\naddpath('power_bounded/');\naddpath('power_diagrams/');\n\nrep = 'results/semi-discrete/';\n[~,~] = mkdir(rep);\n\n% number of sites\nN = 200;\n% x and y coordinate of the sites\nxy = rand(N, 2);\nsigma = .1;\nxy = sigma*randn(N, 2)+1/2;\n\n% weights\nw = ones(N,1);\n\n% the bounding box in clockwise order\nbb = [0,0; 0,1; 1,1; 1,0];\n% get the power diagram\n[V,C] = power_bounded(xy(:,1),xy(:,2), w, bb);\n% [PD, PDinf] = powerDiagramWrapper(xy, w);\n% draw the resulted power diagram\nplot_power(xy,V,C,bb);\n\nq = .01;\naxis([-q 1+q -q 1+q]);\n\n% target histogram\nAtgt = ones(N,1)/N;\n\n% optimization run\ntau = .0004 * N; % gradient step size\nniter = 200;\niter_disp = round( [1:8 niter/16 niter/8 niter/4 niter/2 niter] );\niter_disp = 1:2:niter;\nerr = []; kdisp = 0;\nfor i=1:niter\n progressbar(i,niter);\n [V,C] = power_bounded(xy(:,1),xy(:,2), w, bb);\n A = area_power(xy,V,C,bb);\n if intersect(i,iter_disp)\n kdisp = kdisp+1;\n clf; plot_power(xy,V,C,bb); axis([-q 1+q -q 1+q]);\n saveas(gcf, [rep 'iteration-' num2str(kdisp), '.eps'], 'epsc');\n drawnow;\n end\n A = A/sum(A); % be sure to be normalized ...\n wnew = w - tau * (A(:)-Atgt(:));\n err(i) = norm(w-wnew);\n w = wnew;\nend\n\n% error decay\nplot(err); axis tight;\n\n% plot final OT\nclf; plot_power(xy,V,C,bb, 2);\nsaveas(gcf, [rep 'matching.eps'], 'epsc');\naxis([-q 1+q -q 1+q]);\n", "meta": {"author": "optimaltransport", "repo": "optimaltransport.github.io", "sha": "2fa6db6e6a48ab9bd6676088db00bd7c5c8b4203", "save_path": "github-repos/MATLAB/optimaltransport-optimaltransport.github.io", "path": "github-repos/MATLAB/optimaltransport-optimaltransport.github.io/optimaltransport.github.io-2fa6db6e6a48ab9bd6676088db00bd7c5c8b4203/_site/code/semi-discrete/test_semidiscrete.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.6932255626495242}} {"text": "function f = tsfilter(ts,flt,mode)\n\n% function f = tsfilter(ts,flt,mode)\n%\n% is a b x t matrix with time-series data oriented along the rows\n% is a row vector with the filter (in either the Fourier domain or space domain)\n% (optional) is\n% 0 means interpret as a magnitude filter in the Fourier domain,\n% and do the filtering in the Fourier domain.\n% [1 sz A] means interpret as a magnitude filter in the Fourier domain,\n% but do the filtering in the space domain using imfilter.m and 'replicate'.\n% in order to convert the Fourier filter to the space domain, we use\n% fouriertospace1D.m and sz and use A as the input to fouriertospace1D.m.\n% you can omit A, in which case we default A to 1 (which means to ensure that\n% the space filter sums to 1).\n% 2 means interpret as a space-domain filter and do the filtering in the\n% space domain using imfilter.m and 'replicate'.\n% default: 0.\n%\n% return the filtered time-series data. we force the output to be real-valued.\n% in general, beware of wraparound and edge issues!\n%\n% history:\n% - 2017/10/30 - speed-ups\n%\n% example:\n% flt = zeros(1,100);\n% flt(40:60) = 1;\n% flt = ifftshift(flt);\n% figure; plot(tsfilter(randn(1,100),flt));\n\n% SEE ALSO IMAGEFILTER.M\n\n% constants\nnum = 1000; % number to do at a time\n\n% input\nif ~exist('mode','var') || isempty(mode)\n mode = 0;\nend\nif length(mode)==2\n mode = [mode 1];\nend\n\n% construct space filter if necessary\nif mode(1)==1\n flt = fouriertospace1D(flt,mode(2),[],mode(3));\nend\n\n% do it\nswitch mode(1)\ncase 0\n f = zeros(size(ts),class(ts));\n for p=1:ceil(size(ts,1)/num)\n% statusdots(p,ceil(size(ts,1)/num));\n mn = (p-1)*num+1;\n mx = min(size(ts,1),(p-1)*num+num);\n f(mn:mx,:) = real(ifft(fft(ts(mn:mx,:),[],2) .* repmat(flt,[mx-mn+1 1]),[],2));\n%SLOW:\n% f = cat(1,f,real(ifft(fft(ts(mn:mx,:),[],2) .* repmat(flt,[mx-mn+1 1]),[],2)));\n end\ncase {1 2}\n f = processmulti1D(@imfilter,ts,flt,'replicate','same','conv');\nend\n", "meta": {"author": "cvnlab", "repo": "GLMsingle", "sha": "e37bbc9f26362094e3a574f8d6c2156f5fa92077", "save_path": "github-repos/MATLAB/cvnlab-GLMsingle", "path": "github-repos/MATLAB/cvnlab-GLMsingle/GLMsingle-e37bbc9f26362094e3a574f8d6c2156f5fa92077/matlab/utilities/tsfilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6932255536100879}} {"text": "function [C1, C2, U1, U2, H, K, N] = meshCurvatures(vertices, faces, varargin)\n%MESHCURVATURES Compute principal curvatures on mesh vertices.\n%\n% [C1, C2] = meshCurvatures(VERTICES, FACES)\n% Computes the principal curvatures C1 and C2 for each vertex of the mesh\n% defined by VERTICES and FACES.\n%\n% [C1, C2] = meshCurvatures(..., PNAME, PVALUE)\n% Provides additional input arguments based on a list of name-value pairs\n% of arguments. Parameter names can be:\n% * 'SmoothingSteps' (integer, default: 3) \n% Specifies the number of steps for smoothing vertex curvature\n% tensors. \n% * 'Verbose' (boolean, default: true) \n% Displays details about algorithm processing. \n% * 'ShowProgress' (boolean, default: true) \n% Displays a text-based progress bar.\n%\n% Algorithm\n% The function is adapted from the \"compute_curvature\" function, in the\n% \"toolbox_graph\" fro Gabriel Peyre.\n% The basic idea is to define a curvature tensor for each edge, by\n% assigning a minimum curvature equal to zero along the edge, and a\n% maximum curvature equal to the dihedral angle across the edge.\n% Averaging around the neighbors of a vertex v yields a summation formula\n% over the neighbor edges to compute the curvature tensor of a vertex:\n% 1\n% C(v) = ---- Sum \\beta(e) || e \\cap A(v) || ebar ebar^t\n% A(v) {e \\in A(v)}\n% where:\n% * A(v) is the neighborhood region, usually defined as a 'ring' around\n% the vertex v\n% * beta(e) is the dihedral angle between the normals of the two faces\n% incident to edge e\n% * || e \\cap A(v) || is the length of e (more exactly, the length of the\n% part of e contained within the neighborhood region\n% * ebar is the normalized edge\n%\n% The curvature tensor is then decomposed into C = P D P^-1, with P\n% containing main direction vectors and normal, and D being a diagonal\n% matrix with the two main curvatures and zero along the diagonal.\n% \n% References\n% * David Cohen-Steiner and Jean-Marie Morvan (2003). \n% \"Restricted Delaunay triangulations and normal cycle\". \n% In Proc. 19th Annual ACM Symposium on Computational Geometry, \n% pages 237-246. \n% * Pierre Alliez, David Cohen-Steiner, Olivier Devillers, Bruno Levy,\n% and Mathieu Desbrun (2003). \"Anisotropic Polygonal Remeshing\". \n% ACM Transactions on Graphics. \n% (SIGGRAPH '2003 Conference Proceedings)\n% * Mario Botsch, Leif Kobbelt, M. Pauly, P. Alliez, B. Levy (2010).\n% \"Polygon Mesh Processing\", Taylor and Francis Group, New York.\n% \n% Example\n% [v, f] = torusMesh;\n% f2 = triangulateFaces(f);\n% [c1, c2] = meshCurvatures(v, f2);\n% figure; hold on; axis equal; view(3);\n% drawMesh(v, f2, 'VertexColor', c1 .* c2);\n%\n% See also \n% meshes3d, drawMesh, triangulateFaces\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inrae.fr\n% Created: 2021-09-21, using Matlab 9.10.0.1684407 (R2021a) Update 3\n% Copyright 2021-2022 INRAE - BIA Research Unit - BIBS Platform (Nantes)\n\n%% Process input arguments\n\n% default values for options\nnIters = 3;\nverbose = true;\nshowProgress = true;\n\nwhile length(varargin) > 1\n name = varargin{1};\n if strcmpi(name, 'SmoothingSteps')\n nIters = varargin{2};\n elseif strcmpi(name, 'Verbose')\n verbose = varargin{2};\n elseif strcmpi(name, 'ShowProgress')\n showProgress = varargin{2};\n else\n error('Unknown option: %s', name);\n end\n varargin(1:2) = [];\nend\n\n% validate vertices\nif ~isnumeric(vertices) || size(vertices, 2) ~= 3\n error('Requires vertices to be a N-by-3 numeric array');\nend\n\n% ensure faces are triangular\nif ~isnumeric(faces) || size(faces, 2) > 3\n warning('requires triangle mesh, forces triangulation');\n faces = triangulateFaces(faces);\nend\n\n\n%% Retrieve adjacency relationships\n\nif verbose\n disp('compute adjacencies');\nend\n\n% number of elements of each type\nnv = size(vertices, 1);\nnf = size(faces, 1);\n\n% ev1 and ev2 are indices of source and target vertex of each edge\n% (recomputed later)\nev1 = [faces(:,1); faces(:,2); faces(:,3)];\nev2 = [faces(:,2); faces(:,3); faces(:,1)];\n\n% Compute sparse matrix representing edge-to-face adjacency\ns = [1:nf 1:nf 1:nf]';\nA = sparse(ev1, ev2, s, nv, nv); \n\n% converts sparse matrix to indices of adjacent vertices and faces\n[~, ~, ef1] = find(A); % index of 'right' face\n[ev1, ev2, ef2] = find(A'); % index of 'left' face, and of vertices\n\n% edges are consdered twice (one for each vertex)\n% keep only the edge with lower source index\ninds = find(ev1 < ev2);\nef1 = ef1(inds);\nef2 = ef2(inds);\nev1 = ev1(inds); \nev2 = ev2(inds);\n\n% number of edges\nne = length(ev1);\n\n\n%% Compute geometry features\n\n% compute edge direction vectors\nedgeVectors = vertices(ev2,:) - vertices(ev1,:);\n\n% normalize edge direction vecotrs\nd = sqrt(sum(edgeVectors.^2, 2));\nedgeVectors = bsxfun(@rdivide, edgeVectors, d);\n\n% avoid too large numerics\nd = d ./ mean(d);\n\n% normals to faces\nnormals = meshFaceNormals(vertices, faces);\n\n% ensure normals point outward the mesh\nif meshVolume(vertices, faces) < 0\n normals = -normals;\nend\n\n% inner product of normals\ndp = sum(normals(ef1, :) .* normals(ef2, :), 2);\n\n% compute the (unsigned) dihedral angle between the normals of the two\n% faces incident to each edge\nbeta = acos(min(max(dp, -1), 1));\n\n% relatice orientation of face normals cross product and edge orientation\ncp = crossProduct3d(normals(ef1, :), normals(ef2, :));\nsi = sign(sum(cp .* edgeVectors, 2));\n\n% compute signed dihedral angle\nbeta = beta .* si;\n\n\n%% Compute tensors\n\nif verbose\n disp('compute edge tensors');\nend\n\n% curvature tensor of each edge\nT = zeros(3, 3, ne);\nfor i = 1:3\n for j = 1:i\n T(i, j, :) = reshape(edgeVectors(:,i) .* edgeVectors(:,j), 1, 1, ne);\n T(j, i, :) = T(i, j, :);\n end\nend\nT = bsxfun(@times, T, reshape(d .* beta, [1 1 ne]));\n\n% curvature tensor of each vertex by pooling edge tensors\nTv = zeros(3, 3, nv);\nw = zeros(1, 1, nv);\nfor k = 1:ne\n if showProgress\n displayProgress(k, ne);\n end\n Tv(:,:,ev1(k)) = Tv(:,:,ev1(k)) + T(:,:,k);\n Tv(:,:,ev2(k)) = Tv(:,:,ev2(k)) + T(:,:,k);\n w(:,:,ev1(k)) = w(:,:,ev1(k)) + 1;\n w(:,:,ev2(k)) = w(:,:,ev2(k)) + 1;\nend\nw(w < eps) = 1;\nTv = Tv ./ repmat(w, [3 3 1]);\n\nif verbose\n disp('average vertex tensors');\nend\n\n% apply smoothing on the tensor field\nfor i = 1:3\n for j = 1:3\n a = Tv(i, j, :);\n a = smoothMeshFunction(vertices, faces, a(:), nIters);\n Tv(i, j, :) = reshape(a, [1 1 nv]);\n end\nend\n\n\n%% Retrieve curvatures and eigen vectors from tensors\n\nif verbose\n disp('retrieve curvatures');\nend\n\n% allocate memory\nU = zeros(3, 3, nv);\nD = zeros(3, nv);\n\n% iterate over vertices\nfor k = 1:nv\n % display progress\n if showProgress\n displayProgress(k,nv);\n end\n \n % extract eigenvectors and eigenvalues for current vertex\n [u, d] = eig(Tv(:,:,k));\n d = real(diag(d));\n \n % sort acording to [normal, min curv, max curv]\n [~, I] = sort(abs(d)); \n D(:, k) = d(I);\n U(:, :, k) = real(u(:,I));\nend\n\n% retrieve main curvatures and associated directions\nC1 = D(2,:)';\nC2 = D(3,:)';\nU1 = squeeze(U(:,3,:))';\nU2 = squeeze(U(:,2,:))';\n\n% enforce C1 < C2\ninds = find(C1 > C2);\nC1tmp = C1; \nU1tmp = U1;\nC1(inds) = C2(inds); \nC2(inds) = C1tmp(inds);\nU1(inds,:) = U2(inds,:); \nU2(inds,:) = U1tmp(inds,:);\n\n% compute optional output arguments\nif nargout > 4\n % average and gaussian curvatures\n H = (C1 + C2) / 2;\n K = C1 .* C2;\n \n if nargout > 6\n % normal vector for each vertex\n N = squeeze(U(:,1,:))';\n end\nend\n\n\nfunction displayProgress(n, N)\n% Display the progress of current step using a text-based progress bar.\n%\n% based on the 'progressbar' function in G. Peyre's Graph Toolbox.\n\n% width of the progress bar\nw = 20;\n\n% compute progress ratio as an integer betsween 0 and w\np = min( floor(n/N*(w+1)), w);\n\nglobal pprev;\nif isempty(pprev)\n pprev = -1;\nend\n\nif p ~= pprev\n str1 = repmat('*', 1, p);\n str2 = repmat('.', 1, w-p);\n str = sprintf('[%s%s]', str1, str2);\n if n > 1\n % clear previous string\n fprintf(repmat('\\b', [1 length(str)]));\n end\n fprintf(str);\nend\n\npprev = p;\nif n == N\n fprintf('\\n');\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/meshes3d/meshCurvatures.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6932255443660954}} {"text": "function [R,eff] = randmio_und_signed(W, ITER)\n%RANDMIO_UND Random graph with preserved signed degree distribution\n%\n% R = randmio_und_signed(W,ITER);\n% [R,eff] = randmio_und_signed(W,ITER);\n%\n% This function randomizes an undirected network with positively and\n% negatively signed connections, while preserving the positively and\n% negatively signed degree distribution. The function does not preserve\n% the strength distribution in weighted networks.\n%\n% Input: W, undirected (binary/weighted) connection matrix\n% ITER, rewiring parameter\n% (each edge is rewired approximately ITER times)\n%\n% Output: R, randomized network\n% eff, number of actual rewirings carried out\n%\n% Reference: Maslov and Sneppen (2002) Science 296:910\n%\n%\n% 2011-2015\n% Dani Bassett, UCSB\n% Olaf Sporns, Indiana U\n% Mika Rubinov, U Cambridge\n\n% Modification History:\n% Mar 2011: Original (Dani Bassett, based on randmio_und.m)\n% Mar 2012: Limit number of rewiring attempts,\n% count number of successful rewirings (Olaf Sporns)\n% Dec 2015: Rewritten the core of the rewiring algorithm to allow\n% unbiased exploration of all network configurations. The new\n% algorithm allows positive-positive/negative-negative\n% rewirings, in addition to the previous positive-positive/0-0\n% and negative-negative/0-0 rewirings (Mika Rubinov). \n\nif nargin('randperm')==1\n warning('This function requires a recent (>2011) version of MATLAB.')\nend\n\nR = double(W); % sign function requires double input\nn = size(R,1);\nITER = ITER*n*(n-1)/2;\n\n% maximal number of rewiring attempts per 'iter'\nmaxAttempts = round(n/2);\n% actual number of successful rewirings\neff = 0;\n\nfor iter=1:ITER\n att=0;\n while (att<=maxAttempts) %while not rewired\n %select four distinct vertices\n nodes = randperm(n,4);\n a = nodes(1);\n b = nodes(2);\n c = nodes(3);\n d = nodes(4);\n \n r0_ab = R(a,b);\n r0_cd = R(c,d);\n r0_ad = R(a,d);\n r0_cb = R(c,b);\n \n %rewiring condition\n if (sign(r0_ab)==sign(r0_cd)) && ...\n (sign(r0_ad)==sign(r0_cb)) && ...\n (sign(r0_ab)~=sign(r0_ad))\n \n R(a,d)=r0_ab; R(a,b)=r0_ad;\n R(d,a)=r0_ab; R(b,a)=r0_ad;\n R(c,b)=r0_cd; R(c,d)=r0_cb;\n R(b,c)=r0_cd; R(d,c)=r0_cb;\n \n eff = eff+1;\n break;\n end %rewiring condition\n att=att+1;\n end %while not rewired\nend %iterations", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/bct/randmio_und_signed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.693225539871947}} {"text": "% DEMVOWELS2 Model the vowels data with a 2-D FGPLVM using RBF kernel.\n\n% FGPLVM\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'vowels';\nexperimentNo = 2;\n\n% load data\n[Y, lbls] = lvmLoadData(dataSetName);\n\n% Set up model\noptions = fgplvmOptions('fitc');\noptions.numActive = 200;\nlatentDim = 2;\nd = size(Y, 2);\n\nmodel = fgplvmCreate(latentDim, d, Y, options);\n\n% Optimise the model.\niters = 1000;\ndisplay = 1;\n\nmodel = fgplvmOptimise(model, display, iters);\n\n% Save the results.\ncapName = dataSetName;;\ncapName(1) = upper(capName(1));\nsave(['dem' capName num2str(experimentNo) '.mat'], 'model');\n\nif exist('printDiagram') & printDiagram\n fgplvmPrintPlot(model, lbls, capName, experimentNo);\nend\n\n% Load the results and display dynamically.\nfgplvmResultsDynamic(dataSetName, experimentNo, 'vector')\n\nerrors = fgplvmNearestNeighbour(model, lbls);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/demVowels2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6932046177197921}} {"text": "function [kWh] = eV2kWh(eV)\n% Convert energy or work from electron volts to kilowatt-hours.\n% Chad A. Greene 2012\nkWh = eV*4.4504925e-26;", "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/35258-unit-converters/unit_converters/eV2kWh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6932046064137448}} {"text": "% StackExchange Signal Processing Q81493\n% https://dsp.stackexchange.com/questions/81493\n% Applying 2D Sinc Interpolation for Upsampling in the Fourier Domain (DFT / FFT)\n% References:\n% 1. \n% Remarks:\n% 1. B\n% TODO:\n% \t1. C\n% Release Notes\n% - 1.0.000 29/12/2021\n% * First release.\n\n\n%% General Parameters\n\nsubStreamNumberDefault = 79;\n\nrun('InitScript.m');\n\nfigureIdx = 0;\nfigureCounterSpec = '%04d';\n\ngenerateFigures = ON;\n\n\n%% Simulation Parameters\n\nnumRowsI = 5000;\nnumColsI = 5200;\n\nnumRowsO = 10000;\nnumColsO = 10400;\n\nsincRadius = 5;\n\n\n%% Generate / Load Data\n\nmX = GenTest([numRowsI, numColsI], sincRadius);\nmYRef = GenTest([numRowsO, numColsO], sincRadius);\n\nmY = DftReSample2D(mX, [numRowsO, numColsO]);\n\n\n%% Analysis\n\ndisp(['The interpolation error is given by: ', num2str(max(abs(mYRef - mY), [], 'all'))]);\n\n\n%% Auxilizary Function\n\nfunction [ mX ] = GenTest( vSize, sincRadius )\n\nvX = linspace(-sincRadius, sincRadius, vSize(2) + 1);\nvX(end) = [];\nvY = linspace(-sincRadius, sincRadius, vSize(1) + 1);\nvY = vY(:);\nvY(end) = [];\n\n% mX = abs(vX) + abs(vY) + sinc(sqrt(vX .^2 + vY .^2));\nmX = sinc(sqrt(vX .^2 + vY .^2));\n\nend\n\n\n%% Restore Defaults\n\n% set(0, 'DefaultFigureWindowStyle', 'normal');\n% set(0, 'DefaultAxesLooseInset', defaultLoosInset);\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/SignalProcessing/Q81493/Q81493.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.693204601682347}} {"text": "function plot2dGaussian(Priors,Mus,Sigmas)\n%PLOT2DGAUSSIAN Summary of this function goes here\n% Detailed explanation goes here\n\ndisp('in plot2dGaussians');\n\nGMM=struct('Priors',Priors,'Mus',Mus,'Sigmas',Sigmas,'K',size(Mus,2));\n\nspacing=1000;\nxGMM=marginalizeGMM(GMM,1);\nxs=linspace(min(xGMM.Mus'-2*sqrt(squeeze(xGMM.Sigmas))),max(xGMM.Mus'+2*sqrt(squeeze(xGMM.Sigmas))),spacing);\nyGMM=marginalizeGMM(GMM,2);\nys=linspace(min(yGMM.Mus'-2*sqrt(squeeze(yGMM.Sigmas))),max(yGMM.Mus'+2*sqrt(squeeze(yGMM.Sigmas))),spacing);\npdraw=zeros(1,spacing^2);\n[X Y]=meshgrid(xs,ys);\nx=X(:);\ny=Y(:);\nvtests2=[x y]';\nGMM.K\nfor k=1:GMM.K\n pdraw=pdraw+GMM.Priors(k).*gaussPDF(vtests2,GMM.Mus(:,k),GMM.Sigmas(:,:,k))';\nend\n\nppdraw=reshape(pdraw,spacing,spacing);\n\ncontourf(xs,ys,ppdraw);\n%pcolor(xs,ys,ppdraw);\n%shading interp;\n\n\nset(gca,'YDir','normal');\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/functions/plot_functions/gmm_plot/plotGaussians/plot_2d_gaussian/plot2dGaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6932045974733956}} {"text": "function jed = moon_phase_to_jed ( n, phase )\n\n%*****************************************************************************80\n%\n%% MOON_PHASE_TO_JED calculates the JED of a moon phase.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 March 2013\n%\n% Reference:\n%\n% William Press, Brian Flannery, Saul Teukolsky, William Vetterling,\n% Numerical Recipes: The Art of Scientific Computing,\n% Cambridge University Press.\n%\n% Parameters:\n%\n% Input, integer N, specifies that the N-th such phase\n% of the moon since January 1900 is to be computed.\n%\n% Input, integer PHASE, specifies which phase is to be computed.\n% 0=new moon,\n% 1=first quarter,\n% 2=full,\n% 3=last quarter.\n%\n% Output, real JED, the Julian Ephemeris Date on which the\n% requested phase occurs.\n%\n degrees_to_radians = pi / 180.0;\n%\n% First estimate.\n%\n j = 2415020 + 28 * n + 7 * phase;\n%\n% Compute a correction term.\n%\n c = n + phase / 4.0;\n\n t = c / 1236.85;\n\n xtra = 0.75933 + 1.53058868 * c + ( 0.0001178 - 0.000000155 * t ) * t * t;\n\n as = degrees_to_radians * ( 359.2242 + 29.105356 * c );\n\n am = degrees_to_radians * ( 306.0253 + 385.816918 * c + 0.010730 * t * t );\n\n if ( phase == 0 || phase == 2 )\n\n xtra = xtra + ( 0.1734 - 0.000393 * t ) * sin ( as ) - 0.4068 * sin ( am );\n\n elseif ( phase == 1 || phase == 3 )\n\n xtra = xtra + ( 0.1721 - 0.0004 * t ) * sin ( as ) - 0.6280 * sin ( am );\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MOON_PHASE_TO_JED - Fatal error!\\n' );\n fprintf ( 1, ' Illegal PHASE option = %d\\n', phase );\n error ( 'MOON_PHASE_TO_JED - Fatal error!' );\n\n end\n\n jed = j + xtra;\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/calpak/moon_phase_to_jed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6932045973427843}} {"text": "function varargout = power_internal1(varargin)\n%power_internal1\n% Used for cases such as 2^x, and is treated as evaluation-based operators\n\nswitch class(varargin{1})\n\n case 'double'\n varargout{1} = varargin{2}.^varargin{1};\n\n case 'sdpvar'\n if isa(varargin{2},'sdpvar')\n x = varargin{2};\n y = varargin{1};\n varargout{1} = exp(y*log(x)); %x^y = exp(log(x^y)) \n else\n if length(varargin{1}) > 1 || size(varargin{2},1) ~= size(varargin{2},2)\n error('Inputs must be a scalar and a square matrix. To compute elementwise POWER, use POWER (.^) instead.');\n end\n x = varargin{2};\n y = varargin{1};\n if isa(x,'double') && x==1 && length(y)==1\n varargout{1} = 1;\n else \n varargout{1} = InstantiateElementWise(mfilename,varargin{:});\n end\n end\n\n case 'char'\n \n X = varargin{3};\n Y = varargin{4};\n F=[];\n if Y>=1\n operator = struct('convexity','none','monotonicity','increasing','definiteness','positve','model','callback');\n elseif Y>=0\n operator = struct('convexity','none','monotonicity','decreasing','definiteness','positive','model','callback');\n else\n % Base is negative, so the power has to be an integer\n F = (integer(X));\n operator = struct('convexity','none','monotonicity','decreasing','definiteness','none','model','callback');\n end\n\n operator.bounds = @bounds_power;\n operator.convexhull = @convexhull_power;\n operator.derivative = @(x)derivative(x,Y);\n if Y >= 0\n operator.inverse = @(x,Y)inverse(x,Y);\n end\n\n varargout{1} = F;\n varargout{2} = operator;\n varargout{3} = [X(:);Y(:)];\n otherwise\n error('SDPVAR/power_internal1 called with CHAR argument?');\nend\n\n% This should not be hidden here....\nfunction [L,U] = bounds_power(xL,xU,base)\nif base >= 1\n L = base^xL;\n U = base^xU;\nelseif base>= 0\n L = base^xU;\n U = base^xL;\nelse\n disp('Not implemented yet. Report bug if you need this')\n error\nend\n\nfunction x = inverse(y,base)\nif y <=0\n x = -inf;\nelse\n x = log(y)/log(base);\nend\n\nfunction df = derivative(x,base)\nif length(base)~=length(x)\n base = base*ones(size(x));\nend\nf = base.^x;\ndf = log(base)*f;\n\nfunction [Ax, Ay, b] = convexhull_power(xL,xU,base)\nfL = base^xL;\nfU = base^xU;\ndfL = log(base)*fL;\ndfU = log(base)*fU;\n[Ax,Ay,b] = convexhullConvex(xL,xU,fL,fU,dfL,dfU);", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/operators/power_internal1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6932045927419984}} {"text": "\n% This code demonstrates how the boundary matching code works,\n% and how the benchmark uses it. This is not meant to show\n% how to run the benchmark. See the README file for that.\n\n% setup\npresent = 'color';\niid = 101085;\nnthresh = 10;\n\n% read the image\nim = rgb2gray(double(imread(imgFilename(iid)))/255);\nfigure(1); clf;\nimshow(im);\n\n% create a pb image \n%pb = pbNitzberg(im);\npb = pbGM(im);\nfigure(2); clf;\nimagesc(pb,[0 1]); \naxis image; axis off; truesize;\n\n% read segmentations\nsegs = readSegs(present,iid);\n\n% match the first seg and a thresholded pb\nbmap1 = double(seg2bmap(segs{1}));\nbmap2 = double(pb > 0.5);\n[match1,match2,cost,oc] = correspondPixels(bmap1,bmap2,0.01,1000);\nh=figure(3); clf;\nplotMatch(h,bmap1,bmap2,match1,match2);\ntitle('Seg1 vs. Pb>0.5','Color',[1 1 1]);\n\n% compare the pb and segs\n[thresh,cntR,sumR,cntP,sumP] = boundaryPR(pb,segs,nthresh);\n\n% precision/recall plot\nr = cntR./(sumR+(sumR==0));\np = cntP./(sumP+(sumP==0));\nf = 2.*r.*p./(r+p+((r+p)==0));\nfigure(4); clf;\nplot(r,p,'-o');\naxis equal; axis([0 1 0 1]);\nxlabel('Recall'); ylabel('Precision');\n\n% find best F-measure (should interpolate)\n[t,idx] = max(f(:));\ntitle(sprintf('F=%.2g at (R,P)=(%.2g,%.2g) t=%.2g',...\n f(idx),r(idx),p(idx),thresh(idx)));\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/external/segbench/Benchmark/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6931505294624207}} {"text": "function f = p42_f ( n, x )\n\n%*****************************************************************************80\n%\n%% P42_F evaluates the objective function for problem 42.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 March 2002\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% MJD Powell,\n% An Efficient Method for Finding the Minimum of a Function of\n% Several Variables Without Calculating Derivatives,\n% Computer Journal,\n% Volume 7, Number 2, pages 155-162, 1964.\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the argument of the objective function.\n%\n% Output, real F, the value of the objective function.\n%\n if ( x(2) == 0.0 )\n term = 0.0;\n else\n arg = ( x(1) + 2.0 * x(2) + x(3) ) / x(2);\n term = exp ( - arg^2 );\n end\n\n f = 3.0 ...\n - 1.0 / ( 1.0 + ( x(1) - x(2) )^2 ) ...\n - sin ( 0.5 * pi * x(2) * x(3) ) ...\n - term;\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_opt/p42_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6931505247372862}} {"text": "function x=ifmt(mellin,beta,M);\n%IFMT\tInverse fast Mellin transform.\n%\tX=IFMT(MELLIN,BETA,M) computes the inverse fast Mellin\n%\ttransform of MELLIN.\n%\tWARNING : the inverse of the Mellin transform is correct only \n%\tif the Mellin transform has been computed from FMIN to 0.5 Hz, \n%\tand if the original signal is analytic.\n%\t\n%\tMELLIN : Mellin transform to be inverted. Mellin must have been\n%\t obtained from FMT with frequency running from FMIN to 0.5 Hz.\n%\tBETA : Mellin variable issued from FMT.\n%\tM : number of points of the inverse Mellin transform. \n%\t\t\t\t\t(default : length(MELLIN)).\n%\tX : inverse Mellin transform with M points in time.\n%\n%\tExample : \n%\t sig=atoms(128,[64,0.25,32,1]); \n%\t [MELLIN,BETA]=fmt(sig,0.05,0.5,256); clf;\n%\t X=ifmt(MELLIN,BETA,128); plot(real(X)); hold; \n%\t plot(real(sig),'g'); hold; \n%\n%\tSee also : fmt, fft, ifft.\n%\n\n%\tP. Goncalves 9-95 - O. Lemoine, June 1996. \n%\tCopyright (c) 1995 Rice University - CNRS (France).\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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nN=length(mellin);\n\nif nargin<2,\n error('At least 2 input parameters required');\nelseif nargin==2,\n M=N;\nend\n\nNo2 = (N+rem(N,2))/2;\nq = exp(1/(N*(beta(2)-beta(1))));\nfmin = 0.5/(q^(No2-1));\n\n\n% Inverse Mellin transform computation \np = 0:(N-1);\nL = log(fmin)/log(q);\nS = fft(fftshift(mellin.*exp(-j*2*pi*L*(p/N-1/2))/(N*log(q))));\nS = S(1:No2);\n\n\n% Inverse Fourier transform\nk = (1:No2);\nx = zeros(M,1); \nt = (1:M)-(M+rem(M,2))/2-1;\ngeo_f = fmin*(exp((k-1).*log(q))) ;\nitfmatx = zeros(M,No2);\nitfmatx = exp(2*i*t'*geo_f*pi);\nfor k=1:M,\n x(k) = real(integ(itfmatx(k,:).*S,geo_f));\nend;\n\nx = hilbert(x);\n\n% Normalization\nSP = fft(x); fmax=0.5;\nindmin = 1+round(fmin*(M-2));\nindmax = 1+round(fmax*(M-2));\nSPana = SP(indmin:indmax);\nnu = (indmin:indmax)'/M; \nSPp = SPana./nu;\nEsm = SPp'*SPana;\nx = x*norm(mellin)/sqrt(Esm);\n\n\n\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/ifmt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.6931505200121516}} {"text": "function x=v_rsfft(y,n)\n%V_RSFFT fft of a real symmetric spectrum X=(Y,N)\n% Y is the \"first half\" of a symmetric real input signal and X is the\n% \"first half\" of the symmetric real fourier transform.\n% If the length, N, of the full signal is even, then the \"first half\"\n% contains 1+N/2 elements (the first and last are excluded from the reflection).\n% If N is odd, the \"first half\" conatins 0.5+N/2 elements and only the first\n% is excluded from the reflection.\n% If N is specified explicitly, then Y will be truncated of zero-padded accordingly.\n% If N is omitted it will be taken to be 2*(length(Y)-1) and is always even.\n%\n% If Y is a matrix, the transform is performed along each column\n%\n% The inverse function is y=v_rsfft(x,n)/n\n\n% Could be made faster for even n by using symmetry\n\n% Copyright (C) Mike Brookes 1998\n% Version: $Id: v_rsfft.m 10865 2018-09-21 17:22:45Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\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 can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif ~isreal(y) error('RSFFT: Input must be real'); end\nfl=size(y,1)==1;\nif fl y=y(:); end\n[m,k]=size(y);\nif nargin<2 n=2*m-2;\nelse\n mm=1+fix(n/2);\n if mm>m y=[y; zeros(mm-m,k)];\n elseif mm.\n%\n% $Id$\n\nif numel(q)==6\n % this is used a lot by the Neuromag/Elekta software, where the first element is left out and a rigid body transformation wothout scaling is used.\n % see also https://github.com/mne-tools/mne-python/blob/maint/0.15/mne/transforms.py#L1137\n q0 = sqrt(1 - q(1)^2 - q(2)^2 - q(3)^2);\n q = [q0 q];\nend\n\nif numel(q)~=7\n ft_error('incorrect input vector');\nend\n\n% all of these quaternions are zero-offset in the original equation, but one-offset in the MATLAB vector\nq0 = q(0+1);\nq1 = q(1+1);\nq2 = q(2+1);\nq3 = q(3+1);\nq4 = q(4+1);\nq5 = q(5+1);\nq6 = q(6+1);\n\nR = [\n q0^2+q1^2-q2^2-q3^2 2*(q1*q2-q0*q3) 2*(q1*q3+q0*q2)\n 2*(q1*q2+q0*q3) q0^2+q2^2-q1^2-q3^2 2*(q2*q3-q0*q1)\n 2*(q1*q3-q0*q2) 2*(q2*q3+q0*q1) q0^2+q3^2-q1^2-q2^2\n ];\n\nT = [q4 q5 q6]';\n\nH = eye(4,4);\nH(1:3,1:3) = R;\nH(1:3,4) = T;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/inverse/private/quaternion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6930894387321439}} {"text": "%this examples fits a simple neural network to the function \n%z= 0.5*sin(pi*y(1,:).^2).*sin(2*pi*y(2,:));\n\nN_neurons=15;%number of neurons\nN_in=2;%number of inputs\n\nN_params=N_neurons*(N_in+2)+1;%number of parameters\n\nN_pop_min=N_params+1;%minimum population\n\nN_pop=round(N_pop_min*1.5);%population used\n\nfcn_name='fitness_function';%name of function to maximize\n\nbounds=[-20*ones(1,N_params); 20*ones(1,N_params)];\n\ngen_max=100000;%number of times to evaluate fcn_name;\n\nx_start=[];%let the complex function initialize the population randomly\n\nfit_start=[];%let the complex funciton initialize the fitness;\n\nfcn_opts.N_neurons=N_neurons;%this parameter is passed to the fitness function\n\n%%%%%%%%%%%%crunch numbers!%%%%%%%%%%\ntic;\n[x_best, fit_best, x_pop, fit_pop stats]=complexmethod(fcn_name,bounds,gen_max,x_start,fit_start,fcn_opts);\ntimtoc=toc;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfprintf('Total time=%f s. Time per generation=%f s\\n',timtoc,timtoc/gen_max);\nfprintf('Final RMSE=%f\\n',-fit_best)\n\n%%%%the rest is plotting results%%%%%%\nfigure(1)\nloglog(-stats.trace_fitness,'.')\nxlabel('Generation')\nylabel('RMSE')\n\nN_p=10;%number of points in each dimension\ny=[reshape(linspace(0,1,N_p)'*ones(1,N_p),1,[]);reshape((linspace(0,1,N_p)'*ones(1,N_p))',1,[])];%make mesh\n\nN_in=size(y,1);\nz= 0.5*sin(pi*y(1,:).^2).*sin(2*pi*y(2,:));\n\nW1=reshape(x_best(1:N_neurons*N_in),N_neurons,N_in);%extract weights for first layer\nB1=reshape(x_best((N_neurons*N_in+1):N_neurons*(N_in+1)),N_neurons,1);\nW2=reshape(x_best((N_neurons*(N_in+1)+1):N_neurons*(N_in+2)),1,N_neurons);\nB2=x_best(N_neurons*(N_in+2)+1);\nz_hat=W2*(tanh(W1*y+B1*ones(1,size(y,2))))+B2; %neural calculation\n\nfigure(2);\nclf\nsurf(linspace(0,1,N_p),linspace(0,1,N_p),reshape(z_hat,N_p,N_p));\nshading interp;\nhold on\nplot3(y(2,:),y(1,:),z,'kx')\nhold off\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/25428-complex-method-of-optimization/complex_for_file_ex_4/example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6930894380175149}} {"text": "% Given a reference multidimensional signal y and a series of penalty terms P(x,lambda,d,p), solves the generalized Total Variation\n% proximity operator\n% \n% min_x 0.5 ||x-y||^2 + sum_i P(x,lambda_i,d_i,p_i) .\n% \n% where P(x,lambda_i,d_i,p_i) = lambda_i * sum_j TV(x(d_i)_j,p_i) with x(d)_j every possible 1-dimensional slice of x\n% following the dimension d_i, TV(x,p) the TV-Lp prox operator for x.\n%\n% Inputs:\n% - y: input signal.\n% - lambdas: vector of lambda penalties of each penalty term.\n% - ds: vector of dimensions of application of each penalty term.\n% - norms: vector of norms of each penalty term (1, 2 or inf are accepted).\n% - [threads]: number of threads to use (default: 1)\n%\n% Outputs:\n% - x: solution of the proximity problem.\n% - info: statistical info of the run algorithm:\n% info.iters: number of major iterations run.\n% info.stop: value of the stopping criterion.\n%\n% Examples:\n%\n% - Filter 2D signal using TV-L1 norm:\n% prox_TVgen(X,[lambda lambda],[1 2],[1 1])\n%\n% - Filter 2D signal using TV-L2 norm:\n% prox_TVgen(X,[lambda lambda],[1 2],[2 2])\n%\n% - Filter 2D signal using TV-L1 norm for the rows, TV-L2 for the columns, and different penalties:\n% prox_TVgen(X,[lambdaRows lambdaCols],[1 2],[1 2])\n%\n% - Filter 1D signal using both TV-L1 and TV-L2 norms:\n% prox_TVgen(X,[lambda1 lambda2],[1 1],[1 2])\n%\n% - Filter 3D signal using TV-L1 norm:\n% prox_TVgen(X,[lambda lambda lambda],[1 2 3],[1 1 1])\n%\n% - Filter 3D signal using TV-L2 norm, not penalizing over the second dimension:\n% prox_TVgen(X,[lambda lambda],[1 3],[2 2])\n%\n% - Filter 2D signal using both TV-L1 and TV-L2 norms:\n% prox_TVgen(X,[lambda1 lambda1 lambda2 lambda2],[1 2 1 2],[1 1 2 2])\n%\n% - ... and so on, any combination of norms and dimensions is possible.\nfunction [x,info] = prox_TVgen(y,lambdas,ds,norms,threads)\n % Check inputs\n if nargin < 5, threads = 1; end;\n if length(lambdas) ~= length(ds) || length(ds) ~= length(norms)\n fprintf(1,'ERROR (prox_TVgen): arguments defining penalties differ in length.\\n');\n x = y;\n return;\n end;\n if sum(norms == 1 | norms == 2) ~= length(norms)\n fprintf(1,'ERROR (prox_TVgen): unacceptable norms requested. Available norms: 1, 2.\\n');\n x = y;\n return;\n end;\n \n % Invoke C solver\n [x,in] = solveTVgen_PDykstrac(y,lambdas,ds,norms,threads);\n info.iters = in(1);\n info.stop = in(2);\nend\n", "meta": {"author": "beckel", "repo": "nilm-eval", "sha": "83a2cd5fb911299cc267bd9998636934af781915", "save_path": "github-repos/MATLAB/beckel-nilm-eval", "path": "github-repos/MATLAB/beckel-nilm-eval/nilm-eval-83a2cd5fb911299cc267bd9998636934af781915/Matlab/lib/proxTV-1.0/src/prox_TVgen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.911179705187943, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6930894325135857}} {"text": "function [bandwidth pm] = pll_simulation(cap, res, ipump, vco_sensitivity, fout, fcomp )\n\n% Simulates 2nd, 3rd and 4th order PLL loops for the topologies shown\n% below using basic control systems theory. This is useful for design\n% verification. \n%\n% Input \n% - cap is the capacitors of the loop in Farads [C1, C2, C3, C4]. If\n% these components are not present in the loop, set their value\n% to zero.\n% - res is the resistors of the loop in Ohms [ R2, R3, R4]. If\n% these components are not present in the loop, set their value to zero. \n% - order of the loop, either 2,3, or 4.\n% - ipump is the charge pump current in Amperes\n% - vco_sensitivity is the VCO sensitivity in Hertz/Volt\n% - fout is the output frequency in Hertz\n% - fcomp is the comparison frequency in Hertz\n% \n% Output \n% - bandwidth is the open loop bandwidth in Hertz\n% - pm is the phase margin in degrees\n%\n% The methods used here are derived from those presented in Dean Banerjee's\n% Book \"PLL Performance, Simulation, and Design\" 4th Ed available at\n% National Semiconductors site www.national.com. Most of the work is\n% derived from Chapter 8 pp.43-47 and Chapter 9 pp. 48-53.\n%\n% \n% Loop Topologies\n% 2nd Order\n% + _____ ______\n% fcomp -->|Phase|----------------------------------| VCO |---->fout\n% |Det. | | | | | |\n% ----- | | ----- |\n% ^ - C1 R2 |\n% | | | |\n% | GND C2 |\n% | | |\n% | GND _______ |\n% ----------------------------| 1/N |--------------\n% ------- \n%\n% 3rd Order \n% + _____ ______\n% fcomp -->|Phase|-----------------R3---------------| VCO |---->fout\n% |Det. | | | | | | |\n% ----- | | | ----- |\n% ^ - C1 R2 C3 |\n% | | | | |\n% | GND C2 GND |\n% | | |\n% | GND _______ |\n% ----------------------------| 1/N |--------------\n% ------- \n%\n%\n% 4th Order\n% + _____ ______\n% fcomp -->|Phase|-----------------R3------R4-------| VCO |---->fout\n% |Det. | | | | | | | |\n% ----- | | | | ----- |\n% ^ - C1 R2 C3 C4 |\n% | | | | | |\n% | GND C2 GND GND |\n% | | |\n% | GND _______ |\n% ----------------------------| 1/N |--------------\n% ------- \n%\n% \n% Author: Ben Gilbert \n% Homepage: http://nicta.com.au/people/gilbertb\n% Email: ben.gilbert (wibble) nicta.com.au\n% (c) 2009 by National ICT Australia (NICTA)\n% \n\n%% Setup Parameters\nC1 = cap(1);\nC2 = cap(2);\nC3 = cap(3);\nC4 = cap(4);\n\nR2 = res(1);\nR3 = res(2);\nR4 = res(3);\n\n% Conversion of parameters to more convenient units\nKpd = ipump/2/pi; % phase detector gain\nKvco = vco_sensitivity*2*pi; % vco gain\n\n%% Plot Setup\n% Generates logarithmic spaced points for the calculations\nfplotstart = 10; % Hz\nfplotstop = 10E6; % Hz\nplotpoints = 100;\npltfreqs = [];\nfor ppts=0:plotpoints\n pltfreqs = [ pltfreqs fplotstart * 10 ^ (ppts/plotpoints* log10(fplotstop/fplotstart)) ]; \nend\n\n%% Loop Poll's Polynomial Coefficients\n\nA0 = C1 + C2 + C3 + C4;\nA1 = C2*R2*(C1+C3+C4) + R3*(C1+C2)*(C3+C4) + C4*R4*(C1+C2+C3);\nA2 = C1*C2*R2*R3*(C3+C4) + C4*R4*(C2*C3*R3+C1*C3*R3+C1*C2*R2+C2*C3*R2);\nA3 = C1*C2*C3*C4*R2*R3*R4;\n\nT2 = R2*C2;\n\n%% Filter Transfer Function\nZfilt = @(s) (1 + s.*T2)./s./(A3.*s.^3 + A2.*s.^2 + A1.*s + A0); % filter transfer function\nzfilt = @(f) Zfilt(2*pi*1i*f); % filter transfer function as a function of frequency\n\n%% VCO Transfer Function\nGvco = @(s) Kvco./s; % vco transfer function\ngvco = @(f) Gvco(2*pi*1i*f); % vco transfer function expressed as a function of frequency\n\n%% Forward Path Transfer Function\nG = @(s) Kpd * Gvco(s) .* Zfilt(s); % forward path transfer function\n%% Reverse (Feedback) Transfer Function\nH = fcomp/fout; % feedback path transfer function\n%% Open Loop Transfer Function\nGH = @(s) G(s)*H; % open loop transfer function\ngh = @(f) GH(2*pi*1i*f); % open loop transfer function expressed as a function of frequency\n\n%% Gain Plots\n% Plots of transfer function magnitudes\n% figure; \n% loglog( ...\n% pltfreqs, (abs(gh(pltfreqs))), ...\n% pltfreqs, (abs(zfilt(pltfreqs))), ...\n% pltfreqs, (abs(gvco(pltfreqs))) ... \n% ); \n% grid on; title('Open Loop Gain and Contributing Factors'); \n% xlabel('Frequency [Hz]');\n% legend('Open Loop Gain','Loop Filter','VCO', 'Location', 'SouthWest'); \n\n%% Bode Plot\nfigure; \n subplot(2,1,1); \n semilogx(pltfreqs, 20*log10(abs(gh(pltfreqs)))); \n grid on; \n title('Open Loop Magnitude'); \n subplot(2,1,2); \n semilogx(pltfreqs, angle(gh(pltfreqs)).*180/pi); \n grid on; \n title('Open Loop Phase'); \n ylim([-180 180]);\n\n%% Find open loop bandwidth and phase margin\nghdB = @(f) 20*log10(abs(gh(f)));\nbandwidth = fzero(ghdB, [fplotstart fplotstop]); % find bandwidth numerically\npm = 180 + angle(gh(bandwidth)).*180/pi;\n\n%% Closed Loop Transfer Function\nGcl = @(s) GH(s)./(1 + GH(s)); % closed loop transfer function\ngcl = @(f) Gcl(2*pi*1i*f); \n%% Closed Loop Plot (Magnitude)\n% figure; \n% subplot(2,1,1); \n% semilogx(pltfreqs, 20*log10(abs(gcl(pltfreqs)))); \n% grid on; \n% title('Closed Loop Magnitude'); \n% subplot(2,1,2); \n% semilogx(pltfreqs, angle(gcl(pltfreqs)).*180/pi); \n% grid on; \n% title('Closed Loop Phase'); \n% ylim([-180 180]);\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/23588-phase-locked-loop-synthesis-and-simulation/pll_simulation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640645, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6930894288442994}} {"text": "%% test modulate for all oasis functions. \ncol = {[0 114 178],[0 158 115], [213 94 0],[230 159 0],...\n [86 180 233], [204 121 167], [64 224 208], [240 228 66]}; % colors\nplot_cvx = false; \n\n\n%% threshold foopsi, convolution kernel \ng = [1.7, -0.712]; % AR coefficient \nnoise = 1; \nT = 3000; \nframerate = 30; \nfirerate = 0.5; \nb = 0; % baseline \nN = 20; % number of trials \nseed = 3; % seed for genrating random variables \n[Y, trueC, trueS] = gen_data(g, noise, T, framerate, firerate, b, N, seed); \ny = Y(1,:); \ntrue_c = trueC(1,:); %#ok<*NASGU>\ntrue_s = trueS(1,:); \ntemp = roots([1, -g(1), -g(2)]);\nd = max(temp); \nr = min(temp);\nw = 200;\nht = (exp(log(d)*(1:w)) - exp(log(r)*(1:w))) / (d-r); % convolution kernel\n \n% case 1: all parameters are known, the kernel is the sum of two\n% exponential functions\nsmin = 0.5; \npars = [d, r]; \n[c_oasis, s_oasis] = deconvolveCa(y, 'exp2', pars, 'thresholded', 'smin', smin); %#ok<*ASGLU>\nfigure('name', 'threshold, exp2, known: taur, taud, smin', 'papersize', [15, 4]); \nshow_results; \n\n% case 1: all parameters are known \nsmin = 0.5; \n[c_oasis, s_oasis] = deconvolveCa(y, 'kernel', ht, 'thresholded', 'smin', smin); %#ok<*ASGLU>\nfigure('name', 'threshold, kernel, known: kernel, smin', 'papersize', [15, 4]); \nshow_results; \n%%%%%%%%%%%%%% END %%%%%%%%%%%%%%%%%%\n", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/deconvolution/examples/kernel_thresholded_foopsi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6930890509053815}} {"text": "function jed = ymdf_to_jed_saka ( y, m, d, f )\n\n%*****************************************************************************80\n%\n%% YMDF_TO_JED_SAKA converts a Saka YMDF date to a JED.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 March 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Edward Richards,\n% Algorithm E,\n% Mapping Time, The Calendar and Its History,\n% Oxford, 1999, pages 323-324.\n%\n% Parameters:\n%\n% Input, integer Y, M, D, real F, the YMDF date.\n%\n% Output, real JED, the corresponding JED.\n%\n\n%\n% Convert the calendar date to a computational date.\n%\n y_prime = y + 4794 - floor ( ( 13 - m ) / 12 );\n m_prime = mod ( m + 10, 12 );\n d_prime = d - 1;\n%\n% Convert the computational date to a JED.\n%\n j1 = floor ( ( 1461 * y_prime ) / 4 );\n\n z = floor ( m_prime / 6 );\n\n j2 = ( 31 - z ) * m_prime + 5 * z;\n\n g = floor ( ( y_prime + 184 ) / 100 );\n g = floor ( ( 3 * g ) / 4 ) - 36;\n\n jed = j1 + j2 + d_prime - 1348 - g - 0.5 + f;\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/calpak/ymdf_to_jed_saka.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6930890502858957}} {"text": "\n\nmeas_model = LinearGaussianX('NumMeasDims',2,'NumStateDims',2,'Mapping', [1,2], 'MeasurementErrVariance', 1);\nH = meas_model.matrix();\nR = meas_model.covar();\nmeasurements = [10 15;10 15];\n\ndist = GaussianDistributionX([1;1], 10*eye(2));\n\nnumParticles = 1000;\nparticles = dist.random(numParticles);\nweights = repmat(1/numParticles,1,numParticles);\n\nxPred = dist.Mean; \nPPred=dist.Covar; \n[yPred, S, K] = KalmanFilterX.predictMeasurement_(xPred,PPred,H,R);\n\nlik = meas_model.pdf(measurements,particles);\nl = meas_model.pdf(measurements,xPred,PPred);\n\n\n% Data assoc\nlambda = 1/10000;\nPd = 0.9;\nhypothesiser = EfficientHypothesisManagementX();\n\nW = hypothesiser.hypothesise([lambda*(1-Pd); sum(Pd*lik,2)]');\n% W = lambda*(1-Pd);\n% W = [W Pd*sum(l)];\n% W = W./sum(W);\n% \n% Wp = lambda*(1-Pd);\n% Wp = [Wp Pd*sum(lik)];\n% Wp = Wp./sum(Wp);\n%W = [0.009 1-0.009];\n\n%[xPost, PPost] = KalmanFilterX.update_(xPred,dist.Covar,measurements,yPred, S, K);\n[xPost, PPost] = KalmanFilterX.updatePDA_(xPred,PPred,measurements,W,yPred, S, K);\n\n\n[newWeights] = ParticleFilterX_UpdatePDA(@(y,x)meas_model.pdf(y,x),measurements,particles,weights,W,lik);\nXPost = particles*newWeights';\nresampler = SystematicResamplerX();\nnew_weights = weights.*lik;\n%new_weights = W(1)*dist.Weights + sum(W(2:end).*lik.*dist.Weights,1);\nnew_weights = new_weights./sum(new_weights);\n[new_particles, new_weights] = resampler.resample(particles,new_weights);\n\nnew_dist = ParticleDistributionX(new_particles, new_weights);\n\n% [X,Y] = meshgrid(-3:0.1:5,0:0.1:8);\n% Z = dist.pdf([X;Y]);\n% for i=1:size(X,1)\n% Z(i,:) = dist.pdf([X;Y]);\n% end\n\nfigure;\nhold on;\n[bandwidth,Z,X,Y]=kde2d([particles, measurements+meas_model.random(numParticles)]');\n%contour3(X,Y,density,50);\nh = surf(X,Y,Z); \nshading interp\ncolormap(jet(3000))\n[bandwidth,Z,X,Y]=kde2d([new_dist.Particles, measurements+meas_model.random(numParticles)]');\n%contour3(X,Y,density,50);\nh = surf(X,Y,Z); \nshading interp\ncolormap(jet(3000))\nplot(measurements(1,:),measurements(2,:),'r*');\nplot_gaussian_ellipsoid(dist.Particles*dist.Weights',weightedcov(dist.Particles,dist.Weights));\nplot_gaussian_ellipsoid(new_dist.Particles*new_dist.Weights',weightedcov(new_dist.Particles,new_dist.Weights));\n\n", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/Workspace/Generic/test_expected_lik.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6930779279544472}} {"text": "function asa047_test01 ( )\n\n%*****************************************************************************80\n%\n%% ASA047_TEST01 demonstrates the use of NELMIN on ROSENBROCK.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 February 2008\n%\n% Author:\n%\n% John Burkardt\n%\n n = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ASA047_TEST01\\n' );\n fprintf ( 1, ' Apply NELMIN to ROSENBROCK function.\\n' );\n\n start(1:n) = [ -1.2; 1.0 ];\n reqmin = 1.0E-08;\n step(1:n) = 1.0;\n konvge = 10;\n kcount = 500;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Starting point X:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %f\\n', start(i) );\n end\n\n ynewlo = rosenbrock ( start );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X) = %f\\n', ynewlo );\n\n [ xmin, ynewlo, icount, numres, ifault ] = nelmin ( @rosenbrock, n, start, ...\n reqmin, step, konvge, kcount );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Return code IFAULT = %d\\n', ifault );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Estimate of minimizing value X*:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %f\\n', xmin(i) );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X*) = %f\\n', ynewlo );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of iterations = %d\\n', icount );\n fprintf ( 1, ' Number of restarts = %d\\n', numres );\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/asa047/asa047_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.6929241280238081}} {"text": "function linplus_test0195 ( )\n\n%*****************************************************************************80\n%\n%% TEST0195 tests R8VEC_TO_R8GB, R8GB_TO_R8VEC.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n m = 5;\n n = 8;\n ml = 2;\n mu = 1;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST0195\\n' );\n fprintf ( 1, ' For a general banded matrix,\\n' );\n fprintf ( 1, ' R8VEC_TO_R8GB converts a real vector to a R8GB matrix.\\n' );\n fprintf ( 1, ' R8GB_TO_R8VEC converts a R8GB matrix to a real vector.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix rows M = %d\\n', m );\n fprintf ( 1, ' Matrix columns N = %d\\n', n );\n fprintf ( 1, ' Lower bandwidth ML = %d\\n', ml );\n fprintf ( 1, ' Upper bandwidth MU = %d\\n', mu );\n\n a = r8gb_indicator ( m, n, ml, mu );\n\n r8gb_print ( m, n, ml, mu, a, ' The R8GB indicator matrix:' );\n\n x = r8gb_to_r8vec ( m, n, ml, mu, a );\n\n k = 0;\n for j = 1 : n\n for i = 1 : 2*ml+mu+1\n k = k + 1;\n fprintf ( 1, '%4d %4d %4d %14f\\n', i, j, k, x(k) );\n end\n end\n\n a = r8vec_to_r8gb ( m, n, ml, mu, x );\n\n r8gb_print ( m, n, ml, mu, a, ' The recovered R8GB indicator matrix:' );\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/linplus_test0195.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.6929241128758035}} {"text": "function varargout=sde_decorrelate(d,r2)\n%SDE_DECORRELATE Decorrelate correlated values.\n% R1 = SDE_DECORRELATE(D, R2) returns the matrix R1 of M decorrelated values\n% given the N-by-N diffusion matrix D and the M-by-N matrix of (correlated)\n% values R2. The first column of R1 is always SQRT(D(1,1)) divided by the\n% first column of R2.\n%\n% [R1, C] = SDE_DECORRELATE(D, R2) also returns the N-by-N correlation matrix,\n% C, decorrelated from the diffusion matrix, D.\n%\n% C = SDE_DECORRELATE(D) without a second input argument returns the N-by-N\n% correlation matrix, C, decorrelated from the diffusion matrix, D.\n%\n% Note:\n% R1 = SDE_DECORRELATE(D, SDE_CORRELATE(C, R1)) is only accurate to within\n% the floating point machine precision, EPS.\n%\n% Example:\n% % Correlate and then decorrelate normally-distributed samples\n% r1 = randn(5,3)\n% c = [1 0.8 0.2;0.8 1 0.5;0.2 0.5 1];\n% [r2, d] = sde_correlate(c,r1)\n% r3 = sde_decorrelate(d,r2)\n%\n% See also: SDE_CORRELATE, RAND, RANDN, RANDSTREAM, RANDSTREAM/RANDN, EPS\n\n% Andrew D. Horchler, horchler @ gmail . com, Created 5-20-13\n% Revision: 1.2, 7-12-13\n\n\nif nargout > min(nargin,2)\n error('SDETools:sde_decorrelate:TooManyOutputs',...\n 'Too many output arguments for number of supplied inputs.');\nend\n\nif isempty(d) || isempty(r2)\n if nargin == 1\n varargout{1} = [];\n else\n varargout{2} = [];\n end\nelse\n [m,n] = size(d);\n if ndims(d) ~= 2 || m ~= n %#ok\n error('SDETools:sde_decorrelate:NonSquareMatrix',...\n 'The diffusion matrix must be square.');\n end\n \n if isscalar(d)\n c = d^2;\n isDiag = false;\n\telseif sde_isdiag(d)\n d = diag(d);\n c = diag(d.^2);\n isDiag = true;\n else\n c = d^2;\n isDiag = false;\n end\n \n if nargin == 1\n varargout{1} = c;\n else\n if ndims(r2) ~= 2 || size(r2,2) ~= m\t%#ok\n error('SDETools:sde_decorrelate:DimensionMismatch',...\n ['The number of columns in the matrix of normally '...\n 'distributed values must equal the dimension of the '...\n 'correlation matrix.']);\n end\n \n if isDiag\n varargout{1} = bsxfun(@mrdivide,r2,d);\n else\n varargout{1} = r2/d;\n end\n if nargout == 2\n varargout{2} = c;\n end\n end\nend", "meta": {"author": "horchler", "repo": "SDETools", "sha": "b5da17fc1c7b900ef4dc6d2fa0c6ad19e31b0fcf", "save_path": "github-repos/MATLAB/horchler-SDETools", "path": "github-repos/MATLAB/horchler-SDETools/SDETools-b5da17fc1c7b900ef4dc6d2fa0c6ad19e31b0fcf/SDETools/sde_decorrelate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.692924097384766}} {"text": "function value = p23_exact ( dim_num )\n\n%*****************************************************************************80\n%\n%% P23_EXACT returns the exact integral for problem 23.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 January 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Output, real VALUE, the exact value of the integral.\n%\n c = 0.0;\n c = p23_r8 ( 'G', 'C', c );\n\n e = [];\n e = p23_i4vec ( 'G', 'E', dim_num, e );\n\n value = c;\n for i = 1: dim_num\n value = value * gamma ( e(i) + 1 );\n end\n\n value = value / gamma ( sum ( e(1:dim_num) ) + 1 );\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/p23_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.692778002333034}} {"text": "close all;\nclear all;\nclc;\nrng('default');\n\npng_export = true;\npdf_export = false;\n\nmf = spx.graphics.Figures();\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nmf.new_figure('Recovery probability with S for different MMV recovery algorithms');\n\nload ('bin/success_with_s_comparison.mat');\n\nhold all;\nlegends = cell(1, 4);\n\nplot(Ss, success_with_s.ra_ormp, '-+');\nlegends{1} = 'RA-ORMP';\n% plot(Ss, success_with_s.ra_omp, '-o');\n% legends{2} = 'RA-OMP';\nplot(Ss, success_with_s.somp, '-s');\nlegends{2} = 'SOMP';\nplot(Ss, success_with_s.gomp_2_mmv, '-d');\nlegends{3} = 'GOMP-MMV (L=2)';\nplot(Ss, success_with_s.gomp_4_mmv, '-x');\nlegends{4} = 'GOMP-MMV (L=4)';\n\ngrid on;\nxlabel('Number of signals');\nylabel('Recovery Probability');\nlegend(legends, 'Location', 'southeast');\ntitle('Comparison of recovery performance for MMV algorithms');\n\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/experiments/gomp_mmv/print_comparison_with_s.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.6927780002755383}} {"text": "function [E]=gramSchmidtOrtho(E)\n\nk=size(E,1);\nfor i=1:1:k\n E(i,:)=E(i,:)./norm(E(i,:));\n for j=i+1:1:k\n Ei=E(i,:);\n Ej=E(j,:);\n proj_ei_ej=dot(Ei,Ej).*Ei./norm(Ei);\n E(j,:)=E(j,:)-proj_ei_ej;\n end\nend\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/gramSchmidtOrtho.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.692777996767761}} {"text": "function f = oka1( x )\n\n\tx1p = cos(pi./12.0).*x(:,1) - sin(pi./12.0).*x(:,2);\n\tx2p = sin(pi./12.0).*x(:,1) + cos(pi./12.0).*x(:,2);\n\n\tf(:,1) = x1p;\n\tf(:,2) = sqrt(2*pi) - sqrt(abs(x1p)) + 2 .* (abs(x2p-3.*cos(x1p)-3).^0.33333333);\nend", "meta": {"author": "Eric-Bradford", "repo": "TS-EMO", "sha": "9ec2aa2f54d1232f80d37494ac067f2ebc112688", "save_path": "github-repos/MATLAB/Eric-Bradford-TS-EMO", "path": "github-repos/MATLAB/Eric-Bradford-TS-EMO/TS-EMO-9ec2aa2f54d1232f80d37494ac067f2ebc112688/Test_functions/oka1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088084787997, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6927220187201416}} {"text": "function [centered_data,centroid] = CenterRowData(input)\n% each row is a data point\n\ncentroid = mean(input);\n\ncentered_data = input-(ones(size(input, 1), 1)*centroid);\n", "meta": {"author": "zzstefan", "repo": "BrainNetClass", "sha": "556cda9516429a964100e1ac0bace4258194b4a1", "save_path": "github-repos/MATLAB/zzstefan-BrainNetClass", "path": "github-repos/MATLAB/zzstefan-BrainNetClass/BrainNetClass-556cda9516429a964100e1ac0bace4258194b4a1/Toolbox/SLEP_package_4.1/Examples/traceNorm/CenterRowData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6927220150931488}} {"text": "function [spec,freqs,A]=parafrep(Rx,N,method,q);\n% [spec,freqs]=parafrep(Rx,N,method,q) parametric frequency representation\n% of a signal.\n%\n% Rx : correlation matrix of size (p+1)x(p+1)\n% N : number of frequency bins between 0 and 0.5\n% method : can be either 'ar', 'periodogram', 'capon', 'capnorm', 'lagunas',\n% or 'genlag'.\n% q : parameter for the generalized Lagunas method.\n%\n% noise=rand(1000,1); signal=filter([1 0 0],[1 1 1],noise);\n% figure(1);parafrep(correlmx(signal,2,'hermitian'),128,'AR');title('AR (2)');\n% figure(2);parafrep(correlmx(signal,4,'hermitian'),128,'Capon');title('Capon (4)');\n% figure(3);parafrep(correlmx(signal,2,'hermitian'),128,'lagunas');title('Lagunas (2)');\n% figure(4);parafrep(correlmx(signal,40,'hermitian'),128,'periodogram');title('periodogram (40)');\n\n% F. Auger, july 1998, april 99.\n\nif nargin<1,\n error('At least one parameter required');\nelseif nargin==1,\n N=128; method='capon';\nelseif nargin==2,\n method='capon';\nend;\n\n[Rxrow,Rxcol]=size(Rx);\nif (Rxrow ~= Rxcol),\n error('Rx must be a square matrix');\nend;\n\np=Rxrow-1;\nfreqs=linspace(0,0.5,N);\nspec=zeros(N,1);\n\nmethod=upper(method);\nif strcmp(method,'AR'),\n Un=ones(Rxrow,1); Rxm1Un= (Rx\\Un); \n P1=real(Un'*Rxm1Un); A=Rxm1Un/P1; \n for ifreq=1:N, \n Z=exp(2j*pi*freqs(ifreq)*(0:Rxrow-1)'); \n spec(ifreq)=P1 ./ abs(Z' * A)^2 ;\n end;\nelseif strcmp(method,'PERIODOGRAM'),\n for ifreq=1:N, \n Z=exp(2j*pi*freqs(ifreq)*(0:Rxrow-1)'); \n spec(ifreq)=real(Z' * Rx *Z)/(p+1)^2;\n end; \nelseif strcmp(method,'CAPON'),\n for ifreq=1:N, \n Z=exp(2j*pi*freqs(ifreq)*(0:Rxrow-1)'); \n spec(ifreq)=1.0 / real(Z' * (Rx\\Z));\n end; \nelseif strcmp(method,'CAPNORM'),\n for ifreq=1:N, \n Z=exp(2j*pi*freqs(ifreq)*(0:Rxrow-1)'); \n spec(ifreq)=(p+1) / real(Z' * (Rx\\Z));\n end; \nelseif strcmp(method,'LAGUNAS'),\n for ifreq=1:N, \n Z=exp(2j*pi*freqs(ifreq)*(0:Rxrow-1)'); \n Rxm1Z=Rx\\Z; spec(ifreq)=real(Z' * Rxm1Z)/real(Z' * (Rx\\Rxm1Z));\n end; \nelseif strcmp(method,'GENLAG'),\n for ifreq=1:N, \n Z=exp(2j*pi*freqs(ifreq)*(0:Rxrow-1)'); \n Rxqm1Z=(Rx)^q \\Z; spec(ifreq)=real(Z' * Rx * Rxqm1Z)/real(Z' * (Rx\\Rxqm1Z));\n end; \nelse\n error('unknown frequency representation');\nend;\n\nif (nargout==0),\n figure(gcf); plot(freqs,10.0*log10(spec)); grid;\n xlabel('normalized frequency');\n ylabel('DSP (dB)');\nend;\n\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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/parafrep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6927181522544407}} {"text": "%function [pval, t_orig, crit_t, est_alpha, seed_state]=mult_comp_perm_t1(data,n_perm,tail,alpha_level,mu,reports,seed_state)\n%\n% mult_comp_perm_t1-One sample/paired sample permutation test based on a \n% t-statistic. This function can perform the test on one variable or \n% simultaneously on multiple variables. When applying the test to multiple\n% variables, the \"tmax\" method is used for adjusting the p-values of each\n% variable for multiple comparisons (Blair & Karnisky, 1993). Like \n% Bonferroni correction, this method adjusts p-values in a way that controls \n% the family-wise error rate. However, the permutation method will be more \n% powerful than Bonferroni correction when different variables in the test \n% are correlated.\n%\n% Required Input:\n% data - 2D matrix of data (Observation x Variable)\n%\n% Optional Inputs:\n% n_perm - Number of permutations used to estimate the distribution of\n% the null hypothesis. If the number of observations is less\n% than or equal to 12, all possible permutations are used and\n% this optional input has no effect. If the number of \n% observations is greater than 12, n_perm specifies the \n% number of random permutations computed. Manly (1997) \n% suggests using at least 1000 permutations for an alpha level \n% of 0.05 and at least 5000 permutations for an alpha level of\n% 0.01. {default=5000}\n% alpha_level - Desired family-wise alpha level. Note, because of the finite\n% number of possible permutations, the exact desired family-wise\n% alpha may not be possible. Thus, the closest approximation \n% is used and output as est_alpha. {default=.05}\n% tail - [1, 0, or -1] If tail=1, the alternative hypothesis is that the\n% mean of the data is greater than 0 (upper tailed test). If tail=0,\n% the alternative hypothesis is that the mean of the data is different\n% than 0 (two tailed test). If tail=-1, the alternative hypothesis\n% is that the mean of the data is less than 0 (lower tailed test).\n% {default: 0}\n% mu - The mean of the null hypothesis. Must be a scalar or\n% 1 x n vector (where n=the number of variables). {default: 0}\n% reports - [0 or 1] If 0, function proceeds with no command line\n% reports. Otherwise, function reports what it is doing to\n% the command line. {default: 1}\n% seed_state - The initial state of the random number generating stream\n% (see MATLAB documentation for \"randstream\"). If you pass\n% a value from a previous run of this function, it should\n% reproduce the exact same values. Note, this input only has\n% an effect if you have more than 12 observations.\n%\n% Outputs:\n% pval - p-value (adjusted for multiple comparisons) of each\n% variable\n% t_orig - t-score for each variable\n% crit_t - Lower and upper critical t-scores for given alpha level. \n% t-scores that exceed these values significantly deviate from \n% the null hypothesis. For upper tailed tests, the lower\n% critical t-score is NaN. The opposite is true of lower\n% tailed tests.\n% est_alpha - The estimated family-wise alpha level of the test. With \n% permutation tests, a finite number of p-values are possible.\n% This function tries to use an alpha level that is as close \n% as possible to the desired alpha level. However, if the \n% sample size is small, a very limited number of p-values are \n% possible and the desired family-wise alpha level may be \n% impossible to approximately achieve.\n% seed_state - The initial state of the random number generating stream\n% (see MATLAB documentation for \"randstream\") used to \n% generate the permutations. You can use this to reproduce\n% the output of this function. If the number of observations\n% is less than or equal to 12, seed_state='exact' since\n% all possible permutations are used in lieu of random\n% permutations.\n%\n% Note:\n% -Unlike a parametric test (e.g., an ANOVA), a discrete set of p-values\n% are possible (at most the number of possible permutations). Since the\n% number of possible permutations grows exponentially with the number of\n% participants, this is only an issue for small sample sizes (e.g., 6\n% participants). When you have such a small sample size, the\n% limited number of p-values may make the test overly conservative (e.g., \n% you might be forced to use an alpha level of .0286 since it is the biggest\n% possible alpha level less than .05).\n%\n% -The null hypothesis of the permutation test is that the data come from a\n% distribution that is symmetric around the mean of the null hypothesis.\n% This is probably a generally reasonable assumption for\n% paired-sample/repeated measures tests, but it might not be appropriate for\n% one-sample tests.\n%\n%\n% One Sample Example:\n% >> data=randn(16,5); %5 variables, 16 observations\n% >> data(:,1:2)=data(:,1:2)+1; %mean of first two variables is 1\n% >> [pval, t_orig, crit_t, est_alpha, seed_state]=mult_comp_perm_t1(data,50000);\n% >> disp(pval); %adjusted p-values\n%\n% Paired-Sample/Repated Measures Example:\n% >> dataA=randn(16,5); %data from Condition A (5 variables, 16 observations)\n% >> dataA(:,1:2)=dataA(:,1:2)+1; %mean of first two variables is 1\n% >> dataB=randn(16,5); %data from Condition B (all variables have mean of 0)\n% >> dif=dataA-dataB; %difference between conditions\n% >> [pval, t_orig, crit_t, est_alpha, seed_state]=mult_comp_perm_t1(dif,50000);\n% >> disp(pval); %adjusted p-values\n%\n% References:\n% Blair, R.C. & Karniski, W. (1993) An alternative method for significance\n% testing of waveform difference potentials. Psychophysiology.\n%\n% Manly, B.F.J. (1997) Randomization, Bootstrap, and Monte Carlo Methods in\n% Biology. 2nd ed. Chapman and Hall, London.\n%\n%\n%\n% For a review on permutation tests and other contemporary techniques for \n% correcting for multiple comparisons see:\n%\n% Groppe, D.M., Urbach, T.P., & Kutas, M. (2011) Mass univariate analysis \n% of event-related brain potentials/fields I: A critical tutorial review. \n% Psychophysiology, 48(12) pp. 1711-1725, DOI: 10.1111/j.1469-8986.2011.01273.x \n% http://www.cogsci.ucsd.edu/~dgroppe/PUBLICATIONS/mass_uni_preprint1.pdf\n%\n%\n% Author:\n% David Groppe\n% Dec, 2010\n% Kutaslab, San Diego\n%\n\n\nfunction [pval, t_orig, crit_t, est_alpha, seed_state]=mult_comp_perm_t1(data,n_perm,tail,alpha_level,mu,reports,seed_state)\n\nif nargin<1,\n error('You need to provide data.');\nend\n\nif nargin<2,\n n_perm=5000;\nend\n\nif nargin<3,\n tail=0;\nelseif (tail~=0) && (tail~=1) && (tail~=-1),\n error('Argument ''tail'' needs to be 0,1, or -1.');\nend\n\nif nargin<4,\n alpha_level=0.05;\nelseif (alpha_level>=1) || (alpha_level<=0),\n error('Argument ''alpha_level'' needs to be a number between 0 and 1.'); \nend\n\nif nargin<5,\n mu=0;\nend\n\nif nargin<6,\n reports=1;\nend\n\ndefaultStream=RandStream.getDefaultStream; %random # generator state\nif (nargin<7) || isempty(seed_state),\n %Store state of random number generator\n seed_state=defaultStream.State;\nelse\n defaultStream.State=seed_state; %reset random number generator to saved state\nend\n\n[n_obs n_var]=size(data);\nif n_obs<2,\n error('You need data from at least two observations to perform a hypothesis test.')\nend\n\nif n_obs<7,\n n_psbl_prms=2^n_obs;\n if reports,\n watchit(sprintf(['Due to the very limited number of observations,' ...\n ' the total number of possible permutations is small.\\nThus only a limited number of p-values (at most %d) are possible and the test might be overly conservative.'], ...\n n_psbl_prms));\n end\nend\n\n%% Remove null hypothesis mean from data\nif isscalar(mu),\n data=data-mu;\nelseif isvector(mu)\n s_mu=size(mu);\n if s_mu(1)>1,\n mu=mu';\n s_mu=size(mu);\n end\n if s_mu(2)~=n_var,\n error('mu needs to be a scalar or a 1 x %d vector (%d is the number of variables).',n_var,n_var);\n end\n data=data-repmat(mu,n_obs,1);\nelse\n error('mu needs to be a scalar or a 1 x %d vector (%d is the number of variables).',n_var,n_var);\nend\n\nif reports,\n fprintf('mult_comp_perm_t1: Number of variables: %d\\n',n_var);\n fprintf('mult_comp_perm_t1: Number of observations: %d\\n',n_obs);\n fprintf('t-score degrees of freedom: %d\\n',n_obs-1);\nend\n\n\n%% Set up permutation test\nif n_obs<=12,\n n_perm=2^n_obs; %total number of possible permutations\n exact=1;\n seed_state='exact';\n if reports,\n fprintf('Due to the limited number of observations, all possible permutations of the data will be computed instead of random permutations.\\n');\n end\nelse\n exact=0;\nend\n\nif reports,\n fprintf('Executing permutation test with %d permutations...\\n',n_perm);\n fprintf('Permutations completed: ');\nend\n\n\n%% Compute permutations\n\n%Constant factor for computing t, speeds up computing t to precalculate\n%now\nsqrt_nXnM1=sqrt(n_obs*(n_obs-1));\nif exact,\n %Use all possible permutations\n mxt=zeros(1,n_perm);\n for perm=1:n_perm\n if ~rem(perm,100)\n if reports,\n if ~rem(perm-100,1000)\n fprintf('%d',perm);\n else\n fprintf(', %d',perm);\n end\n if ~rem(perm,1000)\n fprintf('\\n');\n end\n end\n end\n %set sign of each participant's data\n if exist('de2bi.m','file') %% ?? check\n temp=de2bi(perm-1);\n else %% check ??\n temp=perm-1; %% check ??\n end %% check ??\n n_temp=length(temp);\n sn=-ones(n_obs,1);\n sn(1:n_temp,1)=2*temp-1;\n sn_mtrx=repmat(sn,1,n_var); \n d_perm=data.*sn_mtrx;\n \n %computes t-score of permuted data across all channels and time points\n sm=sum(d_perm,1);\n mn=sm/n_obs;\n sm_sqrs=sum(d_perm.^2,1)-(sm.^2)/n_obs;\n stder=sqrt(sm_sqrs)/sqrt_nXnM1;\n t=mn./stder;\n \n %get most extreme t-score\n [dummy mxt_id]=max(abs(t));\n mxt(perm)=t(mxt_id); %get the most extreme t-value with its sign (+ or -)\n end\nelse\n %Use random permutations\n mxt=zeros(1,n_perm*2);\n for perm=1:n_perm\n if ~rem(perm,100)\n if reports,\n if ~rem(perm-100,1000)\n fprintf('%d',perm);\n else\n fprintf(', %d',perm);\n end\n if ~rem(perm,1000)\n fprintf('\\n');\n end\n end\n end\n %randomly set sign of each participant's data\n sn=(rand(n_obs,1)>.5)*2-1; \n sn_mtrx=repmat(sn,1,n_var);\n \n d_perm=data.*sn_mtrx;\n \n %computes t-score of permuted data across all channels and time points\n sm=sum(d_perm,1);\n mn=sm/n_obs;\n sm_sqrs=sum(d_perm.^2,1)-(sm.^2)/n_obs;\n stder=sqrt(sm_sqrs)/sqrt_nXnM1;\n t=mn./stder;\n \n %get most extreme t-score (sign isn't immportant since we asumme\n %symmetric distribution of null hypothesis for one sample test)\n mxt(perm)=max(abs(t));\n end\n mxt(n_perm+1:2*n_perm)=-mxt(1:n_perm); %add the negative of all values since we assumme\n %null hypothesis distribution is symmetric\nend\n\n%End permutations completed line\nif reports && rem(perm,1000)\n fprintf('\\n');\nend\n\n\n%% Computes t-scores of observations at all variables and time points\nsm=sum(data,1);\nmn=sm/n_obs;\nsm_sqrs=sum(data.^2,1)-(sm.^2)/n_obs;\nstder=sqrt(sm_sqrs)/sqrt_nXnM1;\nt_orig=mn./stder;\n\n\n%% Compute p-values\npval=zeros(1,n_var);\nfor t=1:n_var,\n if tail==0,\n pval(t)=mean(mxt>=abs(t_orig(t)))*2;\n elseif tail==1,\n pval(t)=mean(mxt>=t_orig(t));\n elseif tail==-1,\n pval(t)=mean(mxt<=t_orig(t));\n end\nend\n\n%% Compute critical t-scores for specified alpha level,\nif tail==0,\n %two-tailed\n crit_t(1)=prctile(mxt,100*alpha_level/2);\n crit_t(2)=-crit_t(1);\n est_alpha=mean(mxt>=crit_t(2))*2;\nelseif tail==1,\n %upper tailed\n crit_t(1)=NaN;\n crit_t(2)=prctile(mxt,100-100*alpha_level);\n est_alpha=mean(mxt>=crit_t(2));\nelse\n %tail=-1, lower tailed\n crit_t(1)=prctile(mxt,alpha_level*100);\n est_alpha=mean(mxt<=crit_t(1));\n crit_t(2)=NaN;\nend\nif reports,\n fprintf('Desired family-wise alpha level: %f\\n',alpha_level);\n fprintf('Estimated actual family-wise alpha level for returned values of crit_t: %f\\n',est_alpha);\nend\n\n\nfunction watchit(msg)\n%function watchit(msg)\n%\n% Displays a warning message on the Matlab command line. Used by \n% several Mass Univariate ERP Toolbox functions.\n%\n\ndisp(' ');\ndisp('****************** Warning ******************');\ndisp(msg);\ndisp(' ');\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/29782-one-samplepaired-samples-permutation-t-test-with-correction-for-multiple-comparisons/mult_comp_perm_t1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6927181513967174}} {"text": "function x = r8ci_sl ( n, a, b, job )\n\n%*****************************************************************************80\n%\n%% R8CI_SL solves a R8CI system.\n%\n% Discussion:\n%\n% The R8CI storage format is used for an N by N circulant matrix.\n% An N by N circulant matrix A has the property that the entries on\n% row I appear again on row I+1, shifted one position to the right,\n% with the final entry of row I appearing as the first of row I+1.\n% The R8CI format simply records the first row of the matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 February 2004\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real A(N), the R8CI matrix.\n%\n% Input, real B(N), the right hand side.\n%\n% Input, integer JOB, specifies the system to solve.\n% 0, solve A * x = b.\n% nonzero, solve A' * x = b.\n%\n% Output, real X(N), the solution of the linear system.\n%\n if ( job == 0 )\n%\n% Solve the system with the principal minor of order 1.\n%\n r1 = a(1);\n x(1) = b(1) / r1;\n\n r2 = 0.0;\n%\n% Recurrent process for solving the system.\n%\n for nsub = 2 : n\n%\n% Compute multiples of the first and last columns of\n% the inverse of the principal minor of order N.\n%\n r5 = a(n+2-nsub);\n r6 = a(nsub);\n\n if ( 2 < nsub )\n\n work(nsub-1) = r2;\n\n for i = 1 : nsub-2\n r5 = r5 + a(n+1-i) * work(nsub-i);\n r6 = r6 + a(i+1) * work(n-1+i);\n end\n\n end\n\n r2 = -r5 / r1;\n r3 = -r6 / r1;\n r1 = r1 + r5 * r3;\n\n if ( 2 < nsub )\n\n r6 = work(n);\n work(n-1+nsub-1) = 0.0;\n for i = 2 : nsub-1\n r5 = work(n-1+i);\n work(n-1+i) = work(i) * r3 + r6;\n work(i) = work(i) + r6 * r2;\n r6 = r5;\n end\n\n end\n\n work(n) = r3;\n%\n% Compute the solution of the system with the principal minor of order NSUB.\n%\n r5 = 0.0;\n for i = 1 : nsub-1\n r5 = r5 + a(n+1-i) * x(nsub-i);\n end\n\n r6 = ( b(nsub) - r5 ) / r1;\n x(1:nsub-1) = x(1:nsub-1) + work(n:n+nsub-2) * r6;\n x(nsub) = r6;\n\n end\n\n else\n%\n% Solve the system with the principal minor of order 1.\n%\n r1 = a(1);\n x(1) = b(1) / r1;\n\n r2 = 0.0;\n%\n% Recurrent process for solving the system.\n%\n for nsub = 2 : n\n%\n% Compute multiples of the first and last columns of\n% the inverse of the principal minor of order N.\n%\n r5 = a(nsub);\n r6 = a(n+2-nsub);\n\n if ( 2 < nsub )\n\n work(nsub-1) = r2;\n\n for i = 1 : nsub-2\n r5 = r5 + a(i+1) * work(nsub-i);\n r6 = r6 + a(n+1-i) * work(n-1+i);\n end\n\n end\n\n r2 = -r5 / r1;\n r3 = -r6 / r1;\n r1 = r1 + r5 * r3;\n\n if ( 2 < nsub )\n\n r6 = work(n);\n work(n-1+nsub-1) = 0.0;\n for i = 2 : nsub-1\n r5 = work(n-1+i);\n work(n-1+i) = work(i) * r3 + r6;\n work(i) = work(i) + r6 * r2;\n r6 = r5;\n end\n\n end\n\n work(n) = r3;\n%\n% Compute the solution of the system with the principal minor of order NSUB.\n%\n r5 = 0.0E+00;\n for i = 1 : nsub-1\n r5 = r5 + a(i+1) * x(nsub-i);\n end\n\n r6 = ( b(nsub) - r5 ) / r1;\n for i = 1 : nsub-1\n x(i) = x(i) + work(n-1+i) * r6;\n end\n\n x(nsub) = r6;\n\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/linplus/r8ci_sl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6927071680473775}} {"text": "function NsVals=reduceStdRefrac2Spher(NMeas,height,expConst,multConst,varargin)\n%%REDUCESTDREFRAC2SPHER Given a measurement of the atmospheric refractivity\n% at a particular height above sea level, determine\n% the equivalent refractivity at sea level using a\n% standard exponential atmospheric model. The\n% algorithm can handle sea surface refractivities\n% from 200 to 450. \n%\n%INPUTS: NMeas The measured atmospheric refractivity. Note that the\n% refractivity is (n-1)*1e6, where n is the index of\n% refraction.\n% height The height in meters at which the measurement of NMeas was\n% taken. One would expect this to be an orthometic height\n% (with respect to mean sea level). However, the model is low\n% fidelity, so using a height with respect to the Earth's\n% reference ellipsoid would presumably not introduce a\n% significant amount of error.\n% expConst, multConst The two optional, positive parameters\n% parameterizing the decay constant in the model. Assume that\n% at a point, the refractivity is N. Increasing the height by\n% 1km, the model is that the refractivity changes by\n% deltaN=-multConst*exp(expConst*N). deltaN cannot be\n% negative. If these parameters are omitted or empty matrices\n% are passed, then the values fitting the data in [1] are\n% used: expConst=0.005577 and multConst=7.32. Note that the\n% value ce=log(Ns/(Ns+DeltaN))/1000 is the decay constant in\n% inverse meters.\n% varargin Parameters to pass to the fminbnd function. These are\n% standard comma-separated keys and values, such as\n% 'TolX',1e-8.\n%\n%OUTPUTS: Ns The indices of refraction reduced to sea level under a\n% standard exponential atmospheric model. There can be 1-2\n% solutions.\n%\n%The standard exponential atmospheric model is derived in [1]. This\n%function determines the refractivity at the given altitudes for sea\n%surface refractivities from 200 to 450 and subtracts the observed\n%refractivity. Any zero crossings indicate potential solutions. The\n%function fminbnd is then used to find each of the zeros given bounded\n%regions for the zero crossings.\n%\n%The use of this type of very basic refraction model is discussed in [2].\n%\n%REFERENCES:\n%[1] B. R. Bean and G. D. Thayer, CRPL Exponential Reference Atmosphere.\n% Washington, D.C.: U. S. Department of Commerce, National Bureau of\n% Standards, Oct. 1959. [Online]. Available:\n% http://digicoll.manoa.hawaii.edu/techreports/PDF/NBS4.pdf\n%[2] D. F. Crouse, \"Basic tracking using 3D monostatic and bistatic\n% measurements in refractive environments,\" IEEE Aerospace and\n% Electronic Systems Magazine, vol. 29, no. 8, Part II, pp. 54-75, Aug.\n% 2014.\n%\n%June 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(expConst))\n expConst=0.005577; \nend\n\nif(nargin<4||isempty(multConst))\n\tmultConst=7.32; \nend\n\n%Evaluate the refractivity on a grid.\nnumPoints=100;\nNs=linspace(200,450,numPoints);\ntheVals=Ns.*(Ns./(Ns-multConst*exp(expConst*Ns))).^(-height/1000)-NMeas;\n\n%Find where the zero crossings are\ndiffIdx=find(diff(theVals>0));\n\n%Each crossing gives a region to search to find the zero. Because it is\n%bounded, we will use fminbnd to find the minimum of the squared value in\n%the bounded region.\nnumNs=length(diffIdx);\nNsVals=zeros(numNs,1);\n\ncostFun=@(Ns)(Ns.*(Ns./(Ns-multConst*exp(expConst*Ns))).^(-height/1000)-NMeas)^2;\nfor curNs=1:numNs\n NsCur=fminbnd(costFun,Ns(diffIdx(curNs)),Ns(diffIdx(curNs)+1),varargin{:});\n NsVals(curNs)=NsCur;\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/Atmosphere_and_Refraction/Standard_Exponential_Model/reduceStdRefrac2Spher.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.6927071642812175}} {"text": "%DEMEV3\tDemonstrate Bayesian regression for the RBF.\n%\n%\tDescription\n%\tThe problem consists an input variable X which sampled from a\n%\tGaussian distribution, and a target variable T generated by computing\n%\tSIN(2*PI*X) and adding Gaussian noise. An RBF network with linear\n%\toutputs is trained by minimizing a sum-of-squares error function with\n%\tisotropic Gaussian regularizer, using the scaled conjugate gradient\n%\toptimizer. The hyperparameters ALPHA and BETA are re-estimated using\n%\tthe function EVIDENCE. A graph is plotted of the original function,\n%\tthe training data, the trained network function, and the error bars.\n%\n%\tSee also\n%\tDEMEV1, EVIDENCE, RBF, SCG, NETEVFWD\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\nclc;\ndisp('This demonstration illustrates the application of Bayesian')\ndisp('re-estimation to determine the hyperparameters in a simple regression')\ndisp('problem using an RBF netowk. It is based on a the fact that the')\ndisp('posterior distribution for the output weights of an RBF is Gaussian')\ndisp('and uses the evidence maximization framework of MacKay.')\ndisp(' ')\ndisp('First, we generate a synthetic data set consisting of a single input')\ndisp('variable x sampled from a Gaussian distribution, and a target variable')\ndisp('t obtained by evaluating sin(2*pi*x) and adding Gaussian noise.')\ndisp(' ')\ndisp('Press any key to see a plot of the data together with the sine function.')\npause;\n\n% Generate the matrix of inputs x and targets t.\n\nndata = 16;\t\t\t% Number of data points.\nnoise = 0.1;\t\t\t% Standard deviation of noise distribution.\nrandn('state', 0);\nrand('state', 0);\nx = 0.25 + 0.07*randn(ndata, 1);\nt = sin(2*pi*x) + noise*randn(size(x));\n\n% Plot the data and the original sine function.\nh = figure;\nnplot = 200;\nplotvals = linspace(0, 1, nplot)';\nplot(x, t, 'ok')\nxlabel('Input')\nylabel('Target')\nhold on\naxis([0 1 -1.5 1.5])\nfplot('sin(2*pi*x)', [0 1], '-g')\nlegend('data', 'function');\n\ndisp(' ')\ndisp('Press any key to continue')\npause; clc;\n\ndisp('Next we create a two-layer MLP network having 3 hidden units and one')\ndisp('linear output. The model assumes Gaussian target noise governed by an')\ndisp('inverse variance hyperparmeter beta, and uses a simple Gaussian prior')\ndisp('distribution governed by an inverse variance hyperparameter alpha.')\ndisp(' ');\ndisp('The network weights and the hyperparameters are initialised and then')\ndisp('the output layer weights are optimized with the scaled conjugate gradient')\ndisp('algorithm using the SCG function, with the hyperparameters kept')\ndisp('fixed. After a maximum of 50 iterations, the hyperparameters are')\ndisp('re-estimated using the EVIDENCE function. The process of optimizing')\ndisp('the weights with fixed hyperparameters and then re-estimating the')\ndisp('hyperparameters is repeated for a total of 3 cycles.')\ndisp(' ')\ndisp('Press any key to train the network and determine the hyperparameters.')\npause;\n\n% Set up network parameters.\nnin = 1;\t\t% Number of inputs.\nnhidden = 3;\t\t% Number of hidden units.\nnout = 1;\t\t% Number of outputs.\nalpha = 0.01;\t\t% Initial prior hyperparameter. \nbeta_init = 50.0;\t% Initial noise hyperparameter.\n\n% Create and initialize network weight vector.\nnet = rbf(nin, nhidden, nout, 'tps', 'linear', alpha, beta_init);\n[net.mask, prior] = rbfprior('tps', nin, nhidden, nout, alpha, alpha);\nnet = netinit(net, prior);\n\noptions = foptions;\noptions(14) = 5; % At most 5 EM iterations for basis functions\noptions(1) = -1; % Turn off all messages\nnet = rbfsetbf(net, options, x); % Initialise the basis functions\n\n% Now train the network\nnouter = 5;\nninner = 2;\noptions = foptions;\noptions(1) = 1;\noptions(2) = 1.0e-5;\t\t% Absolute precision for weights.\noptions(3) = 1.0e-5;\t\t% Precision for objective function.\noptions(14) = 50;\t\t% Number of training cycles in inner loop. \n\n% Train using scaled conjugate gradients, re-estimating alpha and beta.\nfor k = 1:nouter\n net = netopt(net, options, x, t, 'scg');\n [net, gamma] = evidence(net, x, t, ninner);\n fprintf(1, '\\nRe-estimation cycle %d:\\n', k);\n fprintf(1, ' alpha = %8.5f\\n', net.alpha);\n fprintf(1, ' beta = %8.5f\\n', net.beta);\n fprintf(1, ' gamma = %8.5f\\n\\n', gamma);\n disp(' ')\n disp('Press any key to continue.')\n pause;\nend\n\nfprintf(1, 'true beta: %f\\n', 1/(noise*noise));\n\ndisp(' ')\ndisp('Network training and hyperparameter re-estimation are now complete.') \ndisp('Compare the final value for the hyperparameter beta with the true') \ndisp('value.')\ndisp(' ')\ndisp('Notice that the final error value is close to the number of data')\ndisp(['points (', num2str(ndata),') divided by two.'])\ndisp(' ')\ndisp('Press any key to continue.')\npause; clc;\ndisp('We can now plot the function represented by the trained network. This')\ndisp('corresponds to the mean of the predictive distribution. We can also')\ndisp('plot ''error bars'' representing one standard deviation of the')\ndisp('predictive distribution around the mean.')\ndisp(' ')\ndisp('Press any key to add the network function and error bars to the plot.')\npause;\n\n% Evaluate error bars.\n[y, sig2] = netevfwd(netpak(net), net, x, t, plotvals);\nsig = sqrt(sig2);\n\n% Plot the data, the original function, and the trained network function.\n[y, z] = rbffwd(net, plotvals);\nfigure(h); hold on;\nplot(plotvals, y, '-r')\nxlabel('Input')\nylabel('Target')\nplot(plotvals, y + sig, '-b');\nplot(plotvals, y - sig, '-b');\nlegend('data', 'function', 'network', 'error bars');\n\ndisp(' ')\ndisp('Notice how the confidence interval spanned by the ''error bars'' is')\ndisp('smaller in the region of input space where the data density is high,')\ndisp('and becomes larger in regions away from the data.')\ndisp(' ')\ndisp('Press any key to end.')\npause; clc; close(h); \n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/netlab3.3/demev3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.692707158985437}} {"text": "function [ R ] = V2R( V )\n%V2R converts a 1x3 angle-axis vector into a 3x3 rotation matrix \n% Inputs -\n% V - 1x3 vector of form [rx,ry,rz] where rx,ry,rz is an angle-axis \n% representation of the angle where the unit vector representing the axis\n% has been multipled by the angle of rotation about it\n%\n% Outputs -\n% R - a standard 3x3 transformation matrix\n\nvalidateattributes(V, {'numeric'},{'size',[1,3]});\n\nV = double(V(:));\n\ns = norm(V);\nif(s == 0)\n R = eye(3);\n return;\nend\n\nV = [V/s; s];\nR = vrrotvec2mat(V);\n\nend\n\n", "meta": {"author": "ZacharyTaylor", "repo": "Camera-to-Arm-Calibration", "sha": "d3f0d2e00e2eeaba451e4a8edd226ce0bdb24d08", "save_path": "github-repos/MATLAB/ZacharyTaylor-Camera-to-Arm-Calibration", "path": "github-repos/MATLAB/ZacharyTaylor-Camera-to-Arm-Calibration/Camera-to-Arm-Calibration-d3f0d2e00e2eeaba451e4a8edd226ce0bdb24d08/private/V2R.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6926977738447487}} {"text": "function [] = draw_funciton(f, x_range_min, x_range_max, y_range_min, y_range_max, unit_len)\n\n \n xCoarse = x_range_min:unit_len:x_range_max;\n yCoarse = y_range_min:unit_len:y_range_max;\n [XX,YY] = meshgrid(xCoarse,yCoarse); \n row_size = size(XX,1); \n col_size = size(XX,2);\n for j=1:col_size\n for i=1:row_size\n w = [XX(i,j); YY(i,j)];\n ZZ(i,j) = f(w);\n end\n end \n \n figure\n \n % draw contour\n contour(XX,YY,ZZ,50) \n \n % draw x-axis\n x = [x_range_min x_range_max];\n y = [0 0];\n line(x,y,'Color','black','LineStyle','-')\n \n % draw y-axis \n x = [0 0];\n y = [y_range_min y_range_max];\n line(x,y,'Color','black','LineStyle','-') \n\n \nend\n\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/plotter/draw_funciton.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.6926977557071894}} {"text": "function [h, array] = display_samples(A, opt_normalize, opt_graycolor, cols, opt_colmajor)\n% This function visualizes filters in matrix A. Each column of A is a\n% filter. We will reshape each column into a square image and visualizes\n% on each cell of the visualization panel. \n% All other parameters are optional, usually you do not need to worry\n% about it.\n% opt_normalize: whether we need to normalize the filter so that all of\n% them can have similar contrast. Default value is true.\n% opt_graycolor: whether we use gray as the heat map. Default is true.\n% cols: how many columns are there in the display. Default value is the\n% squareroot of the number of columns in A.\n% opt_colmajor: you can switch convention to row major for A. In that\n% case, each row of A is a filter. Default value is false.\nwarning off all\n\nif ~exist('opt_normalize', 'var') || isempty(opt_normalize)\n opt_normalize= true;\nend\n\nif ~exist('opt_graycolor', 'var') || isempty(opt_graycolor)\n opt_graycolor= true;\nend\n\nif ~exist('opt_colmajor', 'var') || isempty(opt_colmajor)\n opt_colmajor = false;\nend\n\n% rescale\nA = A - mean(A(:));\n\nif opt_graycolor, colormap(gray); end\n\n% compute rows, cols\n[L M]=size(A);\nsz=sqrt(L);\nbuf=1;\nif ~exist('cols', 'var')\n if floor(sqrt(M))^2 ~= M\n n=ceil(sqrt(M));\n while mod(M, n)~=0 && n<1.2*sqrt(M), n=n+1; end\n m=ceil(M/n);\n else\n n=sqrt(M);\n m=n;\n end\nelse\n n = cols;\n m = ceil(M/n);\nend\n\narray=-ones(buf+m*(sz+buf),buf+n*(sz+buf));\n\nif ~opt_graycolor\n array = 0.1.* array;\nend\n\n\nif ~opt_colmajor\n k=1;\n for i=1:m\n for j=1:n\n if k>M, \n continue; \n end\n clim=max(abs(A(:,k)));\n if opt_normalize\n array(buf+(i-1)*(sz+buf)+(1:sz),buf+(j-1)*(sz+buf)+(1:sz))=reshape(A(:,k),sz,sz)/clim;\n else\n array(buf+(i-1)*(sz+buf)+(1:sz),buf+(j-1)*(sz+buf)+(1:sz))=reshape(A(:,k),sz,sz)/max(abs(A(:)));\n end\n k=k+1;\n end\n end\nelse\n k=1;\n for j=1:n\n for i=1:m\n if k>M, \n continue; \n end\n clim=max(abs(A(:,k)));\n if opt_normalize\n array(buf+(i-1)*(sz+buf)+(1:sz),buf+(j-1)*(sz+buf)+(1:sz))=reshape(A(:,k),sz,sz)/clim;\n else\n array(buf+(i-1)*(sz+buf)+(1:sz),buf+(j-1)*(sz+buf)+(1:sz))=reshape(A(:,k),sz,sz);\n end\n k=k+1;\n end\n end\nend\n\nif opt_graycolor\n h=imagesc(array,'EraseMode','none',[-1 1]);\nelse\n h=imagesc(array,'EraseMode','none',[-1 1]);\nend\naxis image off\n\ndrawnow;\n\nwarning on all\n", "meta": {"author": "jimmy-ren", "repo": "vcnn_double-bladed", "sha": "a4de90e845875f6e30632f2e879d3afb81c0ebc1", "save_path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed", "path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed/vcnn_double-bladed-a4de90e845875f6e30632f2e879d3afb81c0ebc1/utils/display_samples.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.6926119561344678}} {"text": "function value = r4_csevl ( x, cs, n )\n\n%*****************************************************************************80\n%\n%% R4_CSEVL evaluates a Chebyshev series.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2011\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Roger Broucke,\n% Algorithm 446:\n% Ten Subroutines for the Manipulation of Chebyshev Series,\n% Communications of the ACM,\n% Volume 16, Number 4, April 1973, pages 254-256.\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Input, real CS(N), the Chebyshev coefficients.\n%\n% Input, integer N, the number of Chebyshev coefficients.\n%\n% Output, real VALUE, the Chebyshev series evaluated at X.\n%\n if ( n < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_CSEVL - Fatal error!\\n' );\n fprintf ( 1, ' Number of terms <= 0.\\n' );\n error ( 'R4_CSEVL - Fatal error!' )\n end\n\n if ( 1000 < n )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_CSEVL - Fatal error!\\n' );\n fprintf ( 1, ' Number of terms > 1000.\\n' );\n error ( 'R4_CSEVL - Fatal error!' )\n end\n\n if ( x < -1.1 || 1.0 < x )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_CSEVL - Fatal error!\\n' );\n fprintf ( 1, ' X outside (-1,+1).\\n' );\n fprintf ( 1, ' X = %f\\n', x );\n error ( 'R4_CSEVL - Fatal error!' )\n end\n\n b1 = 0.0;\n b0 = 0.0;\n twox = 2.0 * x;\n\n for i = n : -1 : 1\n b2 = b1;\n b1 = b0;\n b0 = twox * b1 - b2 + cs(i);\n end\n\n value = 0.5 * ( b0 - b2 );\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/fn/r4_csevl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.833324587033253, "lm_q1q2_score": 0.6926119510638961}} {"text": "function differ_test01 ( )\n\n%*****************************************************************************80\n%\n%% DIFFER_TEST01 tests DIFFER_MATRIX.\n%\n% Discussion:\n%\n% DIFFER_MATRIX computes a modified Vandermonde matrix A1.\n%\n% The solution of a system A1 * X1 = B is related to the solution\n% of the system A2 * X2 = B, where A2 is the standard Vandermonde\n% matrix, simply by X2(I) = X1(I) * A(I,1).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 03 November 2013\n%\n% Author:\n%\n% John Burkardt\n%\n n = 4;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'DIFFER_TEST01\\n' );\n fprintf ( 1, ' Demonstrate that the DIFFER matrix is \"really\"\\n' );\n fprintf ( 1, ' a Vandermonde matrix.\\n' );\n\n stencil(1:n,1) = [ 2.5; 3.3; -1.3; 0.5 ];\n x1(1:n,1) = [ 1.0; 2.0; 3.0; 4.0 ];\n a = differ_matrix ( n, stencil );\n r8mat_print ( n, n, a, ' Stencil matrix:' );\n b(1:n,1) = a(1:n,1:n) * x1(1:n,1);\n%\n% Set up and solve the DIFFER system.\n%\n x1 = a \\ b;\n\n r8vec_print ( n, x1, ' Solution of DIFFER system:' );\n%\n% R8VM_SL solves the related Vandermonde system.\n% A simple transformation gives us the solution to the DIFFER system.\n%\n job = 0;\n [ x2, info ] = r8vm_sl ( n, stencil, b, job );\n\n if ( info ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST01 - Warning!\\n' );\n fprintf ( 1, ' VANDERMONDE system is singular.\\n' );\n error ( 'TEST01 - Vandermonde system is singular.' );\n return\n end\n\n r8vec_print ( n, x2, ' Solution of VANDERMONDE system:' );\n\n x2(1:n,1) = x2(1:n,1) ./ stencil(1:n,1);\n r8vec_print ( n, x2, ' Transformed solution of VANDERMONDE system:' );\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/differ/differ_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.6926119492536256}} {"text": "function parent = tree_rb_to_parent ( n, a )\n\n%*****************************************************************************80\n%\n%% TREE_RB_TO_PARENT converts rooted binary tree to parent node representation.\n%\n% Discussion:\n%\n% Parent node representation of a tree assigns to each node a \"parent\" node,\n% which represents the first link of the path between the node and the \n% root node. The root node itself is assigned a parent of 0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 28 June 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of nodes in the tree.\n%\n% Input, integer A(N), the preorder traversal form for the\n% rooted binary tree.\n%\n% Output, integer PARENT(N), the parent node representation \n% of the tree.\n%\n node = 0;\n node_num = 0;\n\n for k = 1 : n\n\n dad = node;\n node_num = node_num + 1;\n node = node_num;\n parent(node) = dad;\n\n if ( a(k) == 1 )\n\n use(node) = 0;\n\n else\n\n use(node) = 2;\n\n while ( use(node) == 2 )\n node = dad;\n if ( node == 0 )\n break\n end\n use(node) = use(node) + 1;\n dad = parent(node);\n end\n\n end\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/treepack/tree_rb_to_parent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.6926119491635652}} {"text": "function mckinnon_test ( )\n\n%*****************************************************************************80\n%\n%% MCKINNON_TEST works with the McKinnon function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 January 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Michael McKinnon,\n% An Iterative Method for Finding Stationary Values of a Function\n% of Several Variables,\n% Computer Journal,\n% Volume 5, 1962, pages 147-151.\n%\n global phi\n global tau\n global theta\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MCKINNON_TEST:\\n' );\n fprintf ( 1, ' Test COORDINATE_SEARCH with the McKinnon function.\\n' );\n n = 2;\n%\n% Test 1\n%\n a = ( 1.0 + sqrt ( 33.0 ) ) / 8.0;\n b = ( 1.0 - sqrt ( 33.0 ) ) / 8.0;\n\n phi = 10.0;\n tau = 1.0;\n theta = 15.0;\n\n x = [ a, b ];\n r8vec_print ( n, x, ' Initial point X0:' );\n fprintf ( 1, ' PHI = %f, TAU = %f, THETA = %f\\n', phi, tau, theta );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X0) = %g\\n', mckinnon ( x ) );\n\n flag = 0;\n x = coordinate_search ( x, @mckinnon, flag );\n r8vec_print ( n, x, ' Estimated minimizer X1:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X1) = %g\\n', mckinnon ( x ) );\n\n x = [ 0.0, -0.5 ];\n r8vec_print ( n, x, ' Correct minimizer X*:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X*) = %g\\n', mckinnon ( x ) );\n%\n% Test 2\n%\n a = ( 1.0 + sqrt ( 33.0 ) ) / 8.0;\n b = ( 1.0 - sqrt ( 33.0 ) ) / 8.0;\n\n phi = 60.0;\n tau = 2.0;\n theta = 6.0;\n\n x = [ a, b ];\n r8vec_print ( n, x, ' Initial point X0:' );\n fprintf ( 1, ' PHI = %f, TAU = %f, THETA = %f\\n', phi, tau, theta );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X0) = %g\\n', mckinnon ( x ) );\n\n flag = 0;\n x = coordinate_search ( x, @mckinnon, flag );\n r8vec_print ( n, x, ' Estimated minimizer X1:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X1) = %g\\n', mckinnon ( x ) );\n\n x = [ 0.0, -0.5 ];\n r8vec_print ( n, x, ' Correct minimizer X*:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X*) = %g\\n', mckinnon ( x ) );\n%\n% Test 3\n%\n a = ( 1.0 + sqrt ( 33.0 ) ) / 8.0;\n b = ( 1.0 - sqrt ( 33.0 ) ) / 8.0;\n\n phi = 4000.0;\n tau = 3.0;\n theta = 6.0;\n\n x = [ a, b ];\n r8vec_print ( n, x, ' Initial point X0:' );\n fprintf ( 1, ' PHI = %f, TAU = %f, THETA = %f\\n', phi, tau, theta );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X0) = %g\\n', mckinnon ( x ) );\n\n flag = 0;\n x = coordinate_search ( x, @mckinnon, flag );\n r8vec_print ( n, x, ' Estimated minimizer X1:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X1) = %g\\n', mckinnon ( x ) );\n\n x = [ 0.0, -0.5 ];\n r8vec_print ( n, x, ' Correct minimizer X*:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' F(X*) = %g\\n', mckinnon ( x ) );\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/coordinate_search/mckinnon_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.6926119421926622}} {"text": "function bessel_jx_values_test ( )\n\n%*****************************************************************************80\n%\n%% BESSEL_JX_VALUES_TEST demonstrates the use of BESSEL_JX_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 April 2007\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BESSEL_JX_VALUES_TEST:\\n' );\n fprintf ( 1, ' BESSEL_JX_VALUES stores values of \\n' );\n fprintf ( 1, ' the Bessel Jn function for NONINTEGER order.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N X JN(X)\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, n, x, fx ] = bessel_jx_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %12f %12f %24.16e\\n', n, x, fx );\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/test_values/bessel_jx_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.6926119388648169}} {"text": "function yval = r8poly2_val2 ( dim_num, ndata, tdata, ydata, left, tval )\n\n%*****************************************************************************80\n%\n%% R8POLY2_VAL2 evaluates a parabolic interpolant through tabular data.\n%\n% Discussion:\n%\n% This routine is a utility routine used by OVERHAUSER_SPLINE_VAL.\n% It constructs the parabolic interpolant through the data in\n% 3 consecutive entries of a table and evaluates this interpolant\n% at a given abscissa value.\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, integer DIM_NUM, the dimension of a single data point.\n% DIM_NUM must be at least 1.\n%\n% Input, integer NDATA, the number of data points.\n% NDATA must be at least 3.\n%\n% Input, real TDATA(NDATA), the abscissas of the data points.\n% The values in TDATA must be in strictly ascending order.\n%\n% Input, real YDATA(DIM_NUM,NDATA), the data points \n% corresponding to the abscissas.\n%\n% Input, integer LEFT, the location of the first of the three\n% consecutive data points through which the parabolic interpolant\n% must pass. 1 <= LEFT <= NDATA - 2.\n%\n% Input, real TVAL, the value of T at which the parabolic\n% interpolant is to be evaluated. Normally, TDATA(1) <= TVAL <= T(NDATA),\n% and the data will be interpolated. For TVAL outside this range,\n% extrapolation will be used.\n%\n% Output, real YVAL(DIM_NUM), the value of the parabolic\n% interpolant at TVAL.\n%\n\n%\n% Check.\n%\n if ( left < 1 || ndata-2 < left )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8POLY2_VAL2 - Fatal error!\\n' );\n fprintf ( 1, ' LEFT < 1 or NDATA-2 < LEFT.\\n' );\n fprintf ( 1, ' LEFT = %d\\n', left );\n error ( 'R8POLY2_VAL2 - Fatal error!' );\n end\n\n if ( dim_num < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8POLY2_VAL2 - Fatal error!\\n' );\n fprintf ( 1, ' DIM_NUM < 1.\\n' );\n fprintf ( 1, ' DIM_NUM = %d\\n', dim_num );\n error ( 'R8POLY2_VAL2 - Fatal error!' );\n end\n%\n% Copy out the three abscissas.\n%\n t1 = tdata(left);\n t2 = tdata(left+1);\n t3 = tdata(left+2);\n\n if ( t2 <= t1 || t3 <= t2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8POLY2_VAL2 - Fatal error!\\n' );\n fprintf ( 1, ' T2 <= T1 or T3 <= T2.\\n' );\n fprintf ( 1, ' T1 = %f\\n', t1 );\n fprintf ( 1, ' T2 = %f\\n', t2 );\n fprintf ( 1, ' T3 = %f\\n', t3 );\n error ( 'R8POLY2_VAL2 - Fatal error!' );\n end\n%\n% Construct and evaluate a parabolic interpolant for the data\n% in each dimension.\n%\n for i = 1 : dim_num\n\n y1 = ydata(i,left);\n y2 = ydata(i,left+1);\n y3 = ydata(i,left+2);\n\n dif1 = ( y2 - y1 ) / ( t2 - t1 );\n dif2 = ( ( y3 - y1 ) / ( t3 - t1 ) ...\n - ( y2 - y1 ) / ( t2 - t1 ) ) / ( t3 - t2 );\n\n yval(i) = y1 + ( tval - t1 ) * ( dif1 + ( tval - t2 ) * dif2 );\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/r8lib/r8poly2_val2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.6925727850993345}} {"text": "function [ xy, elem ] = triangulate_rectangle ( xl, xr, xn, yb, yt, yn, base )\n\n%*****************************************************************************80\n%\n%% TRIANGULATE_RECTANGLE makes a triangular grid of a rectangle.\n%\n% Discussion:\n%\n% The rectangle is presumed to lie between (XL,YB) and (XR,YT).\n%\n% We subdivide the rectangle into XN regions in the X direction,\n% and YN regions in the Y direction, and then split each quadrilateral,\n% creating 2 * XN * YN triangular elements.\n%\n% The locations of the NN=(XN+1)*(YN+1) nodes are stored in the 2 by NN\n% real array XY.\n%\n% The triples of node indices that make up each triangle are stored int\n% the 3 by NE integer array ELEM. Here, NE = 2 * XN * YN, and the\n% nodes are stored in counterclockwise order. The node indices will\n% begin at 0 if the input quantity BASE is set to 0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 March 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real XL, XR, the left and right X limits.\n%\n% Input, integer XN, the number of elements along the X direction.\n%\n% Input, real YB, YT, the bottom and top Y limits.\n%\n% Input, integer YN, the number of elements along the Y direction.\n%\n% Input, integer BASE, the indexing base:\n% 0, the first node has index 0.\n% 1, the first node has index 1.\n%\n if ( nargin < 7 )\n base = 1;\n end\n%\n% Generate 1D data.\n%\n x1d = linspace ( xl, xr, xn + 1 );\n y1d = linspace ( yb, yt, yn + 1 );\n%\n% Create (X,Y) table.\n% This can be done faster, using meshgrid, but then you lose control\n% of ordering and arranging.\n%\n xyn = ( xn + 1 ) * ( yn + 1 );\n xy = zeros ( 2, xyn );\n\n k = 0;\n for j = 1 : yn + 1\n for i = 1 : xn + 1\n k = k + 1;\n xy(1,k) = x1d(i);\n xy(2,k) = y1d(j);\n end\n end\n%\n% Create connectivity.\n%\n en = 2 * xn * yn;\n elem = zeros ( 3, en );\n e = 0;\n\n for j = 1 : yn\n for i = 1 : xn\n sw = ( j - 1 ) * ( xn + 1 ) + i;\n se = ( j - 1 ) * ( xn + 1 ) + i + 1;\n ne = ( j ) * ( xn + 1 ) + i + 1;\n nw = ( j ) * ( xn + 1 ) + i;\n e = e + 1;\n elem(1,e) = sw;\n elem(2,e) = se;\n elem(3,e) = nw;\n e = e + 1;\n elem(1,e) = ne;\n elem(2,e) = nw;\n elem(3,e) = se;\n end\n end\n%\n% Shift base if requested.\n%\n if ( base == 0 )\n elem = elem - 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/triangulate_rectangle/triangulate_rectangle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.8596637451167995, "lm_q1q2_score": 0.6925727847662712}} {"text": "function [ grid_order, grid_point ] = cc_grids_minmax ( dim_num, q_min, ...\n q_max, grid_num, point_num )\n\n%*****************************************************************************80\n%\n%% CC_GRIDS_MINMAX computes CC orders and grids with Q_MIN <= Q <= Q_MAX.\n%\n% Discussion:\n%\n% The necessary dimensions of GRID_ORDER and GRID_POINT can be\n% determined by calling CC_GRIDS_MINMAX first.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 October 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer Q_MIN, Q_MAX, the minimum and maximum values of\n% Q, the sum of the orders in each spatial coordinate.\n%\n% Input, integer GRID_NUM, the number of Clenshaw Curtis\n% grids whose Q value is between Q_MIN and Q_MAX.\n%\n% Input, integer POINT_NUM, the total number of points in the grids.\n%\n% Output, integer GRID_ORDER(DIM_NUM,GRID_NUM), contains, for each\n% grid, the order of the Clenshaw-Curtis rule in each dimension.\n%\n% Output, real GRID_POINT(DIM_NUM,POINT_NUM), contains\n% a list of all the abscissas of all the rules, listed one grid at\n% a time. If a point occurs in several grids, it will be listed\n% several times.\n%\n\n%\n% Outer loop generates Q's from Q_MIN to Q_MAX.\n%\n point_num = 0;\n grid_num = 0;\n\n for q = q_min : q_max\n%\n% Middle loop generates next partition that adds up to Q.\n%\n more = 0;\n order_1d = [];\n\n while ( 1 )\n\n [ order_1d, more ] = compnz_next ( q, dim_num, order_1d, more );\n%\n% Inner (hidden) loop generates all CC points corresponding to given grid.\n%\n order_nd = prod ( order_1d(1:dim_num) );\n\n grid_point(1:dim_num,point_num+1:point_num+order_nd) = cc_grid ( ...\n dim_num, order_1d, order_nd );\n\n point_num = point_num + order_nd;\n\n grid_num = grid_num + 1;\n grid_order(1:dim_num,grid_num) = order_1d(1:dim_num);\n\n if ( ~more )\n break\n end\n\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/cc_display/cc_grids_minmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835534888481, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.6925647464972515}} {"text": "function xy = padua_points ( l )\n\n%*****************************************************************************80\n%\n%% PADUA_POINTS returns the Padua points of level L.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Marco Caliari, Stefano de Marchi, Marco Vianello,\n% Bivariate interpolation on the square at new nodal sets,\n% Applied Mathematics and Computation,\n% Volume 165, Number 2, 2005, pages 261-274.\n%\n% Parameters:\n%\n% Input, integer L, the level of the set.\n% 0 <= L\n%\n% Output, real XY(2,N), the Padua points of level L.\n%\n n = ( ( l + 1 ) * ( l + 2 ) ) / 2;\n\n xy = zeros ( 2, n );\n\n if ( l == 0 )\n xy(1,1) = 0.0;\n xy(2,1) = 0.0;\n return\n end\n\n k = 0;\n\n for i = 0 : l\n\n j_hi = floor ( l / 2 ) + 1;\n if ( mod ( l, 2 ) == 1 && mod ( i, 2 ) == 1 )\n j_hi = j_hi + 1;\n end;\n\n for j = 1 : j_hi\n\n k = k + 1;\n\n if ( i * 2 == l )\n xy(1,k) = 0.0;\n else\n angle1 = i * pi / l;\n xy(1,k) = cos ( angle1 );\n end\n\n if ( mod ( i, 2 ) == 0 )\n if ( 2 * ( 2 * j - 1 ) == l + 1 ) \n xy(2,k) = 0.0;\n else\n angle2 = ( 2 * j - 1 ) * pi / ( l + 1 );\n xy(2,k) = cos ( angle2 );\n end\n else\n if ( 2 * ( 2 * j - 2 ) == l + 1 ) \n xy(2,k) = 0.0;\n else\n angle2 = ( 2 * j - 2 ) * pi / ( l + 1 );\n xy(2,k) = cos ( angle2 );\n end\n end\n\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/padua/padua_points.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.6925647308792264}} {"text": "function linplus_test44 ( )\n\n%*****************************************************************************80\n%\n%% TEST44 tests R8LT_DET, R8LT_INVERSE, R8LT_MXM, R8LT_RANDOM.\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 n = 5;\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST44\\n' );\n fprintf ( 1, ' For a matrix in lower triangular storage,\\n' );\n fprintf ( 1, ' R8LT_DET computes the determinant.\\n' );\n fprintf ( 1, ' R8LT_INVERSE computes the inverse.\\n' );\n fprintf ( 1, ' R8LT_MXM computes matrix products.\\n' );\n fprintf ( 1, ' R8LT_RANDOM sets a random value.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix order N = %d\\n', n );\n\n [ a, seed ] = r8lt_random ( n, n, seed );\n\n r8lt_print ( n, n, a, ' Matrix A:' );\n%\n% Compute the determinant.\n%\n det = r8lt_det ( n, a );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Determinant is %f\\n', det );\n%\n% Compute the inverse matrix.\n%\n a_inverse = r8lt_inverse ( n, a );\n\n r8lt_print ( n, n, a_inverse, ' Inverse matrix B:' );\n%\n% Check\n%\n c = r8lt_mxm ( n, a, a_inverse );\n\n r8lt_print ( n, n, c, ' Product A * B:' );\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/linplus_test44.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.6925647193322438}} {"text": "function truncated_normal_ab_pdf_test ( )\n\n%*****************************************************************************80\n%\n%% TRUNCATED_NORMAL_AB_PDF_TEST tests TRUNCATED_NORMAL_AB_PDF;\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 September 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRUNCATED_NORMAL_AB_PDF_TEST\\n' );\n fprintf ( 1, ' TRUNCATED_NORMAL_AB_PDF evaluates the Truncated Normal PDF.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The \"parent\" normal distribution has\\n' );\n fprintf ( 1, ' mean = mu\\n' );\n fprintf ( 1, ' standard deviation = sigma\\n' );\n fprintf ( 1, ' The parent distribution is truncated to\\n' );\n fprintf ( 1, ' the interval [a,b]\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Stored Computed\\n' );\n fprintf ( 1, ' X Mu S A B PDF PDF\\n' );\n fprintf ( 1, '\\n');\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, mu, sigma, a, b, x, pdf1 ] ...\n = truncated_normal_ab_pdf_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n pdf2 = truncated_normal_ab_pdf ( x, mu, sigma, a, b );\n\n fprintf( 1, ' %8.1f %8.1f %8.1f %8.1f %8.1f %14g %14g\\n', x, mu, sigma, a, b, pdf1, pdf2 );\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/truncated_normal/truncated_normal_ab_pdf_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.6925647190620774}} {"text": "function [xlat, alt] = geodet2(decl, rmag)\n\n% geocentric to geodetic coordinates\n% exact solution (Borkowski, 1989)\n\n% input\n\n% decl = geocentric declination (radians)\n% rmag = geocentric distance (kilometers)\n\n% output\n\n% xlat = geodetic latitude (radians)\n% alt = geodetic altitude (kilometers)\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nglobal req flat\n\nfr = 1 / flat;\n\n% determine x and z components of the geocentric distance\n\nrx = rmag * cos(decl);\n\nrz = rmag * sin(decl);\n\n% compute geodetic latitude and altitude\n\nif (rz == 0)\n % special case - equatorial\n\n xlat = 0;\n alt = rmag - req;\n\nelseif (abs(decl) == 0.5 * pi)\n % special case - polar\n\n xlat = decl;\n alt = rmag - (req - req/fr);\n\nelse\n % general case\n\n b = sign(rz) * (req - req/fr);\n\n e = ((rz + b) * b/req - req)/rx;\n\n f = ((rz - b) * b/req + req)/rx;\n\n p = (e * f + 1) * 4/3;\n\n q = (e * e - f * f) * 2;\n\n d = p * p * p + q * q;\n\n if (d >= 0.0)\n s = sqrt(d) + q;\n s = sign(s) * (exp(log(abs(s))/3));\n v = p/s - s;\n v = -(q + q + v * v * v)/(3 * p);\n else\n v = 2 * sqrt(-p) * cos(acos(q/p/sqrt(-p))/3);\n end\n\n g = 0.5 * (e + sqrt(e * e + v));\n\n t = sqrt(g * g + (f - v * g)/(g + g - e)) - g;\n\n xlat = atan((1 - t * t) * req/(2 * b * t));\n\n alt = (rx - req * t) * cos(xlat) + (rz - b) * sin(xlat);\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/39494-geodetic-and-geocentric-coordinates/geodet2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138559, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6925298662400906}} {"text": "function H = histcImWin( I, edges, wtMask, shape )\n% Calculates local histograms at every point in an image I.\n%\n% H(i,j,...,k,:) will contain the histogram at location (i,j,...,k), as\n% calculated by weighing values in I by placing wtMask at that\n% location. For example, if wtMask is ones(windowSize) then the\n% histogram at every location will simply be a histogram of the pixels\n% within that window. See histc2 for more information about histgorams.\n% See convnFast for information on shape flags.\n%\n% USAGE\n% H = histcImWin( I, edges, wtMask, [shape] )\n%\n% INPUTS\n% I - image (possibly multidimensional) [see above]\n% edges - quantization bounds, see histc2\n% wtMask - numeric array of weights, or cell array of sep kernels\n% shape - ['full'], 'valid', 'same', or 'smooth'\n%\n% OUTPUTS\n% H - [size(I)xnBins] array of size(I) histograms\n%\n% EXAMPLE\n% load trees; L=conv2(X,filterDog2d(10,4,1,0),'valid'); figure(1); im(L);\n% f1=filterGauss(25,[],25); f2=ones(1,15);\n% H1 = histcImWin(L, 15, {f1,f1'}, 'same'); figure(2); montage2(H1);\n% H2 = histcImWin(L, 15, {f2,f2'}, 'same'); figure(3); montage2(H2);\n%\n% See also ASSIGNTOBINS, HISTC2, CONVNFAST, HISTCIMLOC\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( nargin<4 || isempty(shape) ); shape = 'full'; end;\nif( ~iscell(wtMask) ); wtMask={wtMask}; end;\n\n% split I into channels\nI = assignToBins( I, edges );\nnBins=length(edges)-1; if(nBins==0); nBins=edges; end;\nnd = ndims(I); siz=size(I); maxI = max(I(:));\nif( nd==2 && siz(2)==1); nd=1; siz=siz(1); end;\nQI = false( [siz maxI] );\ninds = {':'}; inds = inds(:,ones(1,nd));\nfor i=1:nBins; QI(inds{:},i)=(I==i); end;\nH = double( QI );\n\n% convolve with wtMask to get histograms, scale appropriately\nfor i=1:length(wtMask)\n wtMaski = wtMask{i};\n for d=1:ndims(wtMaski); wtMaski = flipdim(wtMaski,d); end;\n wtMaski = wtMaski / sum(wtMaski(:));\n H = convnFast( H, wtMaski, shape );\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/images/histcImWin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.6925245848802415}} {"text": "function value = index_to_level_open ( dim_num, t, order, level_max )\n\n%*****************************************************************************80\n%\n%% INDEX_TO_LEVEL_OPEN determines the level of a point given its index.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 April 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer T(DIM_NUM), the grid index of a point.\n%\n% Input, integer ORDER, the order of the rule.\n%\n% Input, integer LEVEL_MAX, the level with respect to which the\n% index applies.\n%\n% Output, integer VALUE, the first level on which\n% the point associated with the given index will appear.\n%\n value = 0;\n\n for dim = 1 : dim_num\n\n s = round ( t(dim) );\n\n s = i4_modp ( t, order );\n\n if ( s == 0 )\n\n level = 0;\n\n else\n\n level = level_max;\n\n while ( mod ( s, 2 ) == 0 )\n s = floor ( s / 2 );\n level = level - 1;\n end\n\n end\n\n if ( level == 0 )\n level = 1;\n elseif ( level == 1 )\n level = 0;\n end\n\n value = value + level;\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_open/index_to_level_open.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504226, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.6925245829491405}} {"text": "function [X,D,e] = sparse_solver_irls(p, A, Y, beta, terminationValue, maxIterations)\n%SPARSE_SOLVER_IRLS Steered-response power map using a MVDR beamformer\n% \n% This routine performs sparse recovery using the iterative reweighted\n% least squares (IRLS) algorithm, with an L_{p,2} norm, assuming\n% spatiotemporal signals Y, of M channels/sensors/microphones and T\n% temporal frames (snapshots), and a linear mixing model of the form \n% Y = A*X, where A is a MxK overcomplete basis dictionary, with K>>M. \n% The original algorithm is described in:\n% \n% Chartrand, R., & Yin, W. (2008). Iteratively reweighted algorithms for \n% compressive sensing. In 2008 IEEE International Conference on Acoustics, \n% Speech and Signal Processing (ICASSP), pp. 3869-3872.\n%\n% and further inspired by the microphone array processing work of\n%\n% Wabnitz, A., Epain, N., McEwan, A., & Jin, C. (2011). Upscaling ambisonic \n% sound scenes using compressed sensing techniques. In 2011 IEEE Workshop \n% on Applications of Signal Processing to Audio and Acoustics (WASPAA).\n%\n% Inputs:\n% p: sparsity exponent p<=1, of the L_{p,2} norm\n% A: overcomplete dictionary (in CS jargon) of steering vectors for\n% a dense grid of K directions, with A of size MxK.\n% Y: measurement vectors (in CS jargon), multichannel microphone signals \n% in audio/acoustics, of size MxT\n% beta: regularization parameter\n% terminationValue: error threshold to stop iterations in the\n% solver\n% maxIterations: maximum number of iterations before stopping the\n% solver, if terminationValue is not reached\n%\n% Outputs:\n% X: KxT sparse signal solution\n% D: demixing matrix of size KxM\n% e: Kx1 sparse signal powers\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% SPARSE_SOLVER_IRLS.M - 13/5/2019\n% Archontis Politis, archontis.politis@tuni.fi\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin<6\n maxIterations = 0;\nend\n\nnChan = size(A,1); % number of channels/sensors\nnDict = size(A,2); % size of steering vector dictionary\nnSnap = size(Y,2); % size of temporal snapshots (e.g. STFT frames, or time-domain samples)\n% initial values for amplitudes and weights\nW = eye(nDict);\nminEpsilon = terminationValue;\nepsilon = 1;\nn = 0;\n\nif nSnap>nChan\n % dimensionality reduction using SVD\n [U, L, ~] = svd(Y);\n L_trunc = L(:,1:nChan);\n Y2 = U*L_trunc;\nelse\n Y2 = Y;\nend\nX_prev = A\\Y2; % initial LS solution\nwhile epsilon>minEpsilon\n % regularization\n gamma = beta/(1-beta) * trace(A*W*A')/nChan;\n % gamma = beta^0.15/(1-beta^0.15) * trace(A*W*A')/nChan; % Epain & Jin\n % reconstruction matrix\n D = (W*A')/(A*W*A' + gamma*eye(nChan));\n % amplitude estimates\n X_current = D * Y2; \n % norm of difference between previous and current solution\n er_k = sqrt(sum((X_current - X_prev).^2,2));\n er = sqrt(sum(er_k.^2));\n % sparse solution signal energies\n e = sum(X_current.^2,2);\n e_max = max(e);\n epsilon = e_max/nDict; % Epain & Jin\n% if er < epsilon^(1/2)/100 % Chartrand & Yin\n% epsilon = epsilon /10;\n% end\n w = (e + epsilon).^(1-p/2);\n W = diag(w);\n \n n = n+1;\n disp(['Iteration ' num2str(n) ': ' num2str(epsilon)])\n if maxIterations\n if n>maxIterations, break; end\n end\nend\nif nSnap>nChan\n D = X_current*inv(U*L_trunc);\n X = D*Y;\nelse\n X = X_current;\nend\n", "meta": {"author": "polarch", "repo": "Spherical-Array-Processing", "sha": "f08bed9b80ce580f9056fd6573ab0c08588ebc11", "save_path": "github-repos/MATLAB/polarch-Spherical-Array-Processing", "path": "github-repos/MATLAB/polarch-Spherical-Array-Processing/Spherical-Array-Processing-f08bed9b80ce580f9056fd6573ab0c08588ebc11/sparse_solver_irls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6924855166813891}} {"text": "function [ point_num, edge_num, face_num, face_order_max ] = ...\n soccer_size_3d ( )\n\n%*****************************************************************************80\n%\n%% SOCCER_SIZE_3D gives \"sizes\" for a truncated icosahedron in 3D.\n%\n% Discussion:\n%\n% The shape is a truncated icosahedron, which is the design used\n% on a soccer ball. There are 12 pentagons and 20 hexagons.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 July 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% http://polyhedra.wolfram.com/uniform/u25.html\n%\n% Parameters:\n%\n% Output, integer POINT_NUM, the number of points.\n%\n% Output, integer EDGE_NUM, the number of edges.\n%\n% Output, integer FACE_NUM, the number of faces.\n%\n% Output, integer FACE_ORDER_MAX, the maximum order of any face.\n%\n point_num = 60;\n edge_num = 90;\n face_num = 32;\n face_order_max = 6;\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/soccer_size_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.6924703114645864}} {"text": "function [all_theta] = oneVsAll(X, y, num_labels, lambda)\n%ONEVSALL trains multiple logistic regression classifiers and returns all\n%the classifiers in a matrix all_theta, where the i-th row of all_theta \n%corresponds to the classifier for label i\n% [all_theta] = ONEVSALL(X, y, num_labels, lambda) trains num_labels\n% logisitc regression classifiers and returns each of these classifiers\n% in a matrix all_theta, where the i-th row of all_theta corresponds \n% to the classifier for label i\n\n% Some useful variables\nm = size(X, 1);\nn = size(X, 2);\n\n% You need to return the following variables correctly \nall_theta = zeros(n + 1 , num_labels);\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: You should complete the following code to train num_labels\n% logistic regression classifiers with regularization\n% parameter lambda. \n%\n% Hint: theta(:) will return a column vector.\n%\n% Hint: You can use y == c to obtain a vector of 1's and 0's that tell use \n% whether the ground truth is true/false for this class.\n%\n% Note: For this assignment, we recommend using fmincg to optimize the cost\n% function. It is okay to use a for-loop (for c = 1:num_labels) to\n% loop over the different classes.\n%\n% fmincg works similarly to fminunc, but is more efficient when we\n% are dealing with large number of parameters.\n%\n% Example Code for fmincg:\n%\n% % Set Initial theta\n% initial_theta = zeros(n + 1, 1);\n% \n% % Set options for fminunc\n% options = optimset('GradObj', 'on', 'MaxIter', 50);\n% \n% % Run fmincg to obtain the optimal theta\n% % This function will return theta and the cost \n% [theta] = ...\n% fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...\n% initial_theta, options);\n%\n\nclasses = zeros(m, num_labels);\nfor i=1:num_labels\n classes(:,i) = y==i;\nend\n\ninitial_theta = zeros(n + 1, 1);\n\n% Set options for fminunc\noptions = optimset('GradObj', 'on', 'MaxIter', 50);\n\n% Run fmincg to obtain the optimal theta\n% This function will return theta and the cost \nfor i = 1:num_labels\n [all_theta(:,i)] = fmincg (@(t)(lrCostFunction(t, X, classes(:,i), lambda)), ...\n initial_theta, options);\nend\n\n\nall_theta = all_theta';\n\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "lawlite19", "repo": "MachineLearningEx", "sha": "44be60fe4d639d18af5ea5011f069eed348e97b8", "save_path": "github-repos/MATLAB/lawlite19-MachineLearningEx", "path": "github-repos/MATLAB/lawlite19-MachineLearningEx/MachineLearningEx-44be60fe4d639d18af5ea5011f069eed348e97b8/machine-learning-ex3/ex3/oneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.6924702941464352}} {"text": "% Fig. 6.23 Feedback Control of Dynamic Systems, 5e \n% Franklin, Powell, Emami\n%\n\nclear all;\nclose all;\n\nnum=1;\nden=[1 2 1];\nw=logspace(-2,3,100);\n[re,im]=nyquist(num,den,w);\n\nplot(re,im,re,-im);\ngrid;\naxis equal\nxlabel('Re(G(s))');\nylabel('Im(G(s))');\ntitle('Fig. 6.23 Nyquist plot');\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/9907-feedback-control-of-dynamic-systems-fifth-ed/fig6_23.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6923789316064988}} {"text": "function [panel, Vol] = DeterminePanelGeometry(inputgeo, figs)\n% find coordinates for horseshoe vortices and control points and plot\n% Aircraft-Fixed coordinate system:\n% x: forward along fuselage axis\n% y: out starboard wing\n% z: down\n% Local Profile coordinate system:\n% x: along chord from leading edge toward trailing edge\n% z: up\n\nplot_on = 1;\n\n%% constants\nhalfSpan=inputgeo.b/2; % half wingspan\nsweep=inputgeo.sweep; % wing sweep angle in radians\ndihedral=inputgeo.dih; %dihedral angle in radians\nnc=inputgeo.nc; %number of panels on camber line, upper and lower surfaces\nns = inputgeo.ns; % number of span segments per side\nM = inputgeo.M; %Freestream mach number\nbeta = sqrt(1-M^2); %Prandtl-Glauert correction\n\n\n%% Root Airfoil data\ny=0; % span station\nchord=inputgeo.c_r; % chord length\nalphaRoot=inputgeo.i_r; % geometric angle of incidence at root in radians\n\n% call function\n[Croot,Troot,Aroot]=NacaCoord(inputgeo.root,y,nc); % Croot = nondimensional camber line, Troot = nondimensional surface;\n%Croot coordinates = [x location in fraction chord, y location in fraction\n% chord, z location in fraction chord]\n%Troot coordinates = [x location in fraction chord, y location in fraction\n% chord, z location in fraction chord]\n\n%% Scale to chord length\nCroot(:,1)=chord*Croot(:,1);Croot(:,3)=chord*Croot(:,3);\nTroot(:,1)=chord*Troot(:,1);Troot(:,3)=chord*Troot(:,3);\nAroot=Aroot*chord^2;\n\n%Calculate slope of camber line for each panel at the root\n%Calculate the chord along each elemental panel\ndzdxRoot = zeros(1,nc);\nccRoot = zeros(1,nc);\nif nc == 1 %If there is only one chordwise element\n i=1;\n dzdxRoot(i)=-(Croot(i+1,3)-Croot(i,3))/(Croot(i+1,1)-Croot(i,1));\n ccRoot(i)=0.75*(Croot(i+1,1)-Croot(i,1));\nelse %if there are more than one chordwise elements\n for i=1:nc\n dzdxRoot(i)=(Croot(i+1,3)-Croot(i,3))/(Croot(i+1,1)-Croot(i,1));\n if i==nc\n ccRoot(i)=0.75*(Croot(i+1,1)-Croot(i,1));\n else\n ccRoot(i)=0.75*(Croot(i+1,1)-Croot(i,1))+0.25*(Croot(i+2,1)-Croot(i+1,1));\n end\n end\nend\n\nif plot_on\n axes(figs.root); cla;\n plot(Croot(:,1)*-3.2808,Croot(:,3)*-3.2808,'r') %Convert to feet; plot with z-axis positive up and x-axis to the left\n hold on\n plot(Troot(:,1)*-3.2808,Troot(:,3)*-3.2808,'b') %Convert to feet; plot with z-axis positive up and x-axis to the left\n axis equal\n title('Root airfoil')\nend\n\n%% Tip Airfoil data\ny=-halfSpan; % span station; left wing\nchord=inputgeo.taper*inputgeo.c_r; % chord length\nalphaTip=inputgeo.i_r+inputgeo.twist; % geometric angle of incidence at tip in radians\n\n%call function\n[Ctip,Ttip,Atip]=NacaCoord(inputgeo.tip,y,nc);\n\n%% scale to chord length\nCtip(:,1)=chord*Ctip(:,1);Ctip(:,3)=chord*Ctip(:,3);\nTtip(:,1)=chord*Ttip(:,1);Ttip(:,3)=chord*Ttip(:,3);\nAtip=Atip*chord^2;\n\n%Calculate slope of camber line for each panel at the tip\n%Calculate the chord along each elemental panel\ndzdxTip = zeros(1,nc);\nccTip = zeros(1,nc);\nif nc == 1 %If there is only one chordwise element\n dzdxTip(i)=-(Ctip(i+1,3)-Ctip(i,3))/(Ctip(i+1,1)-Ctip(i,1));\n ccTip(i)=0.75*(Ctip(i+1,1)-Ctip(i,1));\nelse %if there are more than one chordwise elements\n for i=1:nc\n dzdxTip(i)=(Ctip(i+1,3)-Ctip(i,3))/(Ctip(i+1,1)-Ctip(i,1));\n if i==nc\n ccTip(i)=0.75*(Ctip(i+1,1)-Ctip(i,1));\n else\n ccTip(i)=0.75*(Ctip(i+1,1)-Ctip(i,1))+0.25*(Ctip(i+2,1)-Ctip(i+1,1));\n end\n end\nend\n\nif plot_on\n axes(figs.tip); cla;\n plot(Ctip(:,1)*-3.2808,Ctip(:,3)*-3.2808,'r') %Convert to feet; plot with z-axis positive up and x-axis to the left\n hold on\n plot(Ttip(:,1)*-3.2808,Ttip(:,3)*-3.2808,'b') %Convert to feet; plot with z-axis positive up and x-axis to the left\n axis equal\n title('Tip airfoil')\nend\n\n%% Root: Transform to Aircraft-Fixed Coordinate System:\n% skin:\n%Skin(number of spanwise sections, number of chordwise sections, coordinates in 3 dimensions (x,y,z))\nSkin(1,1:2*nc+1,1:3) = Troot*[cos(alphaRoot) 0 sin(alphaRoot); 0 1 0; -sin(alphaRoot) 0 cos(alphaRoot)];\n\n% Mean camber line:\nCamber(1,1:nc+1,1:3) = Croot*[cos(alphaRoot) 0 sin(alphaRoot); 0 1 0; -sin(alphaRoot) 0 cos(alphaRoot)];\n\n%% Tip: Transform to Aircraft-Fixed Coordinate System:\n% sweep and dihedral\n% Negative sign occurs because local axes are opposite to global\nxLETip = -halfSpan*(tan(sweep));% x coordinate of Leading Edge at Tip\nzLETip = -halfSpan*(tan(dihedral));% z coordinate of Leading Edge at Tip\n% Skin:\nLETip=ones(2*nc+1,1)*[xLETip 0 zLETip];\nSkin(ns+1,1:2*nc+1,1:3) = Ttip*[cos(alphaTip) 0 sin(alphaTip); 0 1 0; -sin(alphaTip) 0 cos(alphaTip)]+LETip;\n\n% Mean camber line\nLETip=ones(nc+1,1)*[xLETip 0 zLETip];\nCamber(ns+1,1:nc+1,1:3) = Ctip*[cos(alphaTip) 0 sin(alphaTip); 0 1 0; -sin(alphaTip) 0 cos(alphaTip)]+LETip;\n\n%% Intermediate stations\nfor k=1:ns-1 % k = 0 corresponds to root, k = ns corresponds to tip\n eta=k/ns;\n for i=1:nc+1 % along camber\n Camber(k+1,i,:) = Camber(1,i,:)+eta*(Camber(ns+1,i,:)-Camber(1,i,:));\n end\n for i=1:2*nc+1 %along surface\n Skin(k+1,i,:) = Skin(1,i,:)+eta*(Skin(ns+1,i,:)-Skin(1,i,:));\n end\nend\n\nif plot_on\n %Plot wing surface\n axes(figs.fig); cla; hold on; axis equal; \n for k=1:ns+1\n plot3(Skin(k,:,1)*-3.2808,Skin(k,:,2)*3.2808,Skin(k,:,3)*-3.2808); %Convert to feet; plot with z-axis positive up and x-axis to the left\n plot3(Skin(k,:,1)*-3.2808,-Skin(k,:,2)*3.2808,Skin(k,:,3)*-3.2808); %Convert to feet; plot with z-axis positive up and x-axis to the left\n plot3(Camber(k,:,1)*-3.2808,Camber(k,:,2)*3.2808,Camber(k,:,3)*-3.2808,'r') %Convert to feet; plot with z-axis positive up and x-axis to the left\n end\n for i=1:size(Skin,2)\n plot3(Skin(:,i,1)*-3.2808,Skin(:,i,2)*3.2808,Skin(:,i,3)*-3.2808);\n plot3(Skin(:,i,1)*-3.2808,-Skin(:,i,2)*3.2808,Skin(:,i,3)*-3.2808);\n end\nend\n\n\n%Determine panel properties\ntwist = zeros(1,ns);\ndzdx = zeros(ns,nc);\ncc = zeros(ns,nc);\nCP = zeros(ns,nc,3);\nBV = zeros(ns,nc,3);\nBV1 = zeros(ns,nc,3);\nBV2 = zeros(ns,nc,3);\nBVhalfspan = zeros(ns,nc);\nsweep_c4 = zeros(ns,nc);\n\nfor k = 1:ns\n %Determine local twist at each panel, dz/dx at control points, and\n %chord along left trailing leg of elemental panel\n eta=k/(ns+1);\n twist(k)=alphaRoot+eta*(alphaTip-alphaRoot);\n dzdx(k,:)=dzdxRoot+eta*(dzdxTip-dzdxRoot);\n cc(k,:)=ccRoot+eta*(ccTip-ccRoot); %Validated\n %Determine control point coordinates, coordinates to center of bound\n %vortex, half span of bound vortex, and quarter-chord sweep angle\n for i = 1:nc\n CP(k,i,:)=0.5*(Camber(k,i,:)+Camber(k+1,i,:))+0.75*(0.5*(Camber(k,i+1,:)+Camber(k+1,i+1,:))-0.5*(Camber(k,i,:)+Camber(k+1,i,:)));\n BV(k,i,:)=0.5*(Camber(k,i,:)+Camber(k+1,i,:))+0.25*(0.5*(Camber(k,i+1,:)+Camber(k+1,i+1,:))-0.5*(Camber(k,i,:)+Camber(k+1,i,:)));\n BV1(k,i,:)=0.75*Camber(k+1,i,:)+0.25*Camber(k+1,i+1,:); %Left bound vortex coordinate\n BV2(k,i,:)=0.75*Camber(k,i,:)+0.25*Camber(k,i+1,:); %Right bound vortex coordinate\n BVhalfspan(k,i)= 0.5*(0.75*norm(shiftdim(Camber(k,i,2:3)-Camber(k+1,i,2:3)))+0.25*norm(shiftdim(Camber(k,i+1,2:3)-Camber(k+1,i+1,2:3))));\n %Only consider [Y,Z] distances due to definition of halfspan in\n %NASA paper; considering X distance as well makes halfspan increase\n %greatly as you increase sweep and invalidates calculations\n %Validated BVhalfspan calculation through (1:ns-1,1:nc)\n sweep_c4(k,i)=atan((Camber(k,i,1)-Camber(k+1,i,1))/(Camber(k,i,2)-Camber(k+1,i,2))); %Validated\n end\nend\n\n%Prandtl-Glauert corrections\nCPprime = CP(:,:,1)/beta;\nBVprime = BV(:,:,1)/beta;\nBV1prime = BV1(:,:,1)/beta;\nBV2prime = BV2(:,:,1)/beta;\nsweep_c4_prime = atan(tan(sweep_c4)/beta);\n\nfor k = 1:ns\n for i = 1:nc\n panel(k,i).CP=shiftdim(CP(k,i,:)); %Removing singleton dimensions\n panel(k,i).BV=shiftdim(BV(k,i,:)); %Removing singleton dimensions\n panel(k,i).BV1=shiftdim(BV1(k,i,:)); %Removing singleton dimensions\n panel(k,i).BV2=shiftdim(BV2(k,i,:)); %Removing singleton dimensions\n panel(k,i).dzdx=dzdx(k,i);\n panel(k,i).twist=twist(k);\n panel(k,i).s=BVhalfspan(k,i);\n panel(k,i).sweep=sweep_c4(k,i);\n panel(k,i).sweepprime=sweep_c4_prime(k,i);\n panel(k,i).CPprime=CPprime(k,i);\n panel(k,i).BVprime=BVprime(k,i);\n panel(k,i).BV1prime=BV1prime(k,i);\n panel(k,i).BV2prime=BV2prime(k,i);\n panel(k,i).cc=cc(k,i);\n end\nend\n\n%Determine wing volume\nVol = 1/3*(Aroot +sqrt(Aroot*Atip) + Atip)*inputgeo.b;\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/15442-wing-designer/DeterminePanelGeometry.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7577943767446201, "lm_q1q2_score": 0.6923789316064987}} {"text": "% convert mel frequency to linear frequency\n\nfunction [linear_freq] = mel2linear(mel_freq)\n\n% slow implementation\n% for i=1:length(mel_freq)\n% linear_freq(i) = 700*( 10^(mel_freq(i)/2595)-1 );\n% end\n\n% fast implementation\nlinear_freq = 700*( 10.^(mel_freq/2595)-1 );", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/signal/feature/mel2linear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765163620468, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6923789262627731}} {"text": "function [V,dV] = dss_sphere(X, dim, symmetric, params)\n% [V,dV] = dss_sphere(X)\n% [V,dV] = dss_sphere(X, dim)\n% [V,dV] = dss_sphere(X, dim, symmetric)\n% X Data to be sphered\n% dim Requested result data dimension, 0 for no reduction\n% symmetric Boolean, perform symmetric sphering\n% V Sphering matrix\n% dV De-sphering matrix\n\n% Copyright (C) 2004, 2005 DSS MATLAB package team (dss@cis.hut.fi).\n% Distributed by Laboratory of Computer and Information Science,\n% Helsinki University of Technology. http://www.cis.hut.fi/projects/dss/.\n% $Id: dss_sphere.m,v 1.2 2005/11/30 08:29:40 jaakkos Exp $\n\nif nargin<4\n params = [];\nend\nif nargin<3 || isempty(symmetric)\n symmetric = false;\nend\nif ~isfield(params, 'absthreshold')\n params.absthreshold=true;\nend\nif params.absthreshold && ~isfield(params, 'thresholdEig')\n % Treshold for eigenvalues that are treated zero\n params.thresholdEig=1e-12;\nelseif ~params.absthreshold && ~isfield(params, 'thresholdEig')\n params.thresholdEig=0.99; % keep the components that explain up to 99% of variance\nend\nif ~isfield(params, 'thresholdSphered')\n % Treshold for maximum covariance for treating data already sphered\n params.tresholdSphered=1e-12;\nend\n\nif nargin>=2 && dim~=0\n if iscell(X)\n dim = min(dim, size(X{1}, 1));\n else\n dim = min(dim, size(X, 1));\n end \nelseif iscell(X)\n dim = size(X{1}, 1);\nelse\n dim = size(X, 1);\nend\n\nfprintf('Sphering the data\\n');\n% data covariance\nif iscell(X)\n C = cellcov(X, 2, 1);\n I = diag(ones(size(X{1},1),1));\nelse\n C = cov(X', 1);\n I = diag(ones(size(X,1),1));\nend\n\n% check if data is already sphered\nmaxCov = max(max(C-I));\nif maxCov=params.thresholdEig);\n if values %d.\\n', size(X{1},1), dim);\n end\n if ~iscell(X) && dim < size(X,1)\n fprintf('SPHERING: Reducing data dimension: %d -> %d.\\n', size(X,1), dim);\n end\n E = E(:,1:dim);\n D = D(1:dim);\n\n % calculate sphering matrices\n D = sqrt(D);\n V = diag(1./D) * E' ;\n dV = E * diag(D);\n if symmetric\n % symmetric sphering\n V = E * V;\n dV = dV *E';\n end\n\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/dss/dss_sphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676514011486, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6923789194837393}} {"text": "function C = IPTColorfullness(imgIPT)\n%\n% C = IPTColorfullness(imgIPT)\n%\n% This computes the colorfullness in the IPT color space\n%\n% input:\n% - imgIPT: an image in the IPT color space\n%\n% output:\n% - C: colorfullness\n%\n% Copyright (C) 2015 Francesco Banterle\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%\n\ncheck3Color(imgIPT);\n\nC = sqrt(imgIPT(:,:,2).^2 + imgIPT(:,:,3).^2);\n\nend", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/ColorSpace/IPTColorfullness.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6923789194837392}} {"text": "function Mz = ir_equations(params, seqFlag, approxFlag)\n%IR_EQUATIONS Analytical equations for the longitudinal magnetization of \n%steady-state inversion recovery experiments with either a gradient echo \n%(GRE-IR) or spin-echo (SE-IR) readouts. \n% Reference: Barral, J. K., Gudmundson, E. , Stikov, N. , Etezadi?Amoli, \n% M. , Stoica, P. and Nishimura, D. G. (2010), A robust methodology for \n% in vivo T1 mapping. Magn. Reson. Med., 64: 1057-1067. \n% doi:10.1002/mrm.22497\n%\n% params: struct with the required parameters for the sequence and\n% approximation. See below for list.\n%\n% seqFlag: String. Either 'GRE-IR' or 'SE-IR'\n% approxFlag: Integer between 1 and 4.\n% 1: General equation (no approximation).\n% 2: Ideal 180 degree pulse approximation of case 1.\n% 3: Ideal 90 degree pulse approximation of case 2, and readout term\n% absorbed into constant.\n% 4: Long TR (TR >> T1) approximation of case 3.\n%\n% **PARAMS PROPERTIES**\n% All times in seconds, all angles in degrees.\n% 'GRE-IR'\n% case 1: T1, TR, TI, EXC_FA, INV_FA, constant (optional)\n% case 2: T1, TR, TI, EXC_FA, constant (optional)\n% case 3: T1, TR, TI, constant (optional)\n% case 4: T1, TI, constant (optional)\n%\n% 'SE-IR'\n% case 1: Same as 'GRE-IR' case + SE_FA, TE\n% case 2: Same as 'GRE-IR' case + TE\n% case 3: Same as 'GRE-IR' case + TE\n% case 4: Same as 'GRE-IR' case\n%\n\nswitch seqFlag\n case 'GRE-IR'\n switch approxFlag\n case 1 % General\n try\n T1 = params.T1;\n TR = params.TR;\n TI = params.TI;\n \n EXC_FA = params.EXC_FA; % Excitation pulse in deg\n INV_FA = params.INV_FA; % Inversion pulse in deg\n \n try\n constant = params.constant;\n catch\n constant = 1;\n end\n \n Mz= constant .* ( (1-cosd(INV_FA).*exp(-TR/T1) - (1-cosd(INV_FA)).*exp(-TI./T1)) ./ (1-cosd(INV_FA).*cosd(EXC_FA).*exp(-TR./T1)) );\n catch\n error('ir_equations.GRE-IR.case1: Incorrect parameters for given flag. Run `help ir_equations` for more info.')\n end\n case 2 % Ideal 180 pulse\n try\n T1 = params.T1;\n TR = params.TR;\n TI = params.TI;\n \n EXC_FA = params.EXC_FA; % in deg\n \n try\n constant = params.constant;\n catch\n constant = 1;\n end\n \n Mz= constant .* (1 - 2*exp(-TI./T1) + exp(-TR./T1));\n catch\n error('ir_equations.GRE-IR.case2: Incorrect parameters for given flag. Run `help ir_equations` for more info.')\n end\n case 3 % Ideal 90 pulse.\n try\n T1 = params.T1;\n TR = params.TR;\n TI = params.TI;\n \n try\n constant = params.constant;\n catch\n constant = 1;\n end\n \n Mz= constant .* (1 - 2*exp(-TI./T1) + exp(-TR./T1));\n catch\n error('ir_equations.GRE-IR.case3: Incorrect parameters for given flag. Run `help ir_equations` for more info.')\n end\n \n case 4 % Long TR (TR >> T1)\n try\n T1 = params.T1;\n TI = params.TI;\n \n try\n constant = params.constant;\n catch\n constant = 1;\n end\n \n Mz= constant .* (1 - 2*exp(-TI./T1));\n catch\n error('ir_equations.GRE-IR.case4: Incorrect parameters for given flag. Run `help ir_equations` for more info.')\n end\n \n otherwise\n error('ir_equations: Unknown flag. Run `help ir_equations` for more info.')\n end\n case 'SE-IR'\n switch approxFlag\n case 1 % General equation\n try\n T1 = params.T1;\n TR = params.TR;\n TI = params.TI;\n \n TE = params.TE;\n \n EXC_FA = params.EXC_FA; % Excitation pulse in deg\n INV_FA = params.INV_FA; % Inversion pulse in deg\n SE_FA = params.SE_FA; % Inversion pulse in deg\n \n try\n constant = params.constant;\n catch\n constant = 1;\n end\n \n Mz= constant .* ( (1-cosd(INV_FA).*cosd(SE_FA).*exp(-TR/T1) - cosd(INV_FA).*(1-cosd(SE_FA)).*exp(-(TR-(TE/2))./T1) - (1-cosd(INV_FA)).*exp(-TI./T1)) ./ (1-cosd(INV_FA).*cosd(EXC_FA).*cosd(SE_FA).*exp(-TR./T1)) );\n catch\n error('ir_equations.SE-IR.case1: Incorrect parameters for given flag. Run `help ir_equations` for more info.')\n end\n case 2 % Ideal 180 pulses\n try\n T1 = params.T1;\n TR = params.TR;\n TI = params.TI;\n \n TE = params.TE;\n \n EXC_FA = params.EXC_FA; % Excitation pulse in deg\n \n try\n constant = params.constant;\n catch\n constant = 1;\n end\n \n Mz= constant .* ( (1-exp(-TR/T1) + 2.*exp(-(TR-(TE/2))./T1) - 2.*exp(-TI./T1)) ./ (1-cosd(EXC_FA).*exp(-TR./T1)) );\n catch\n error('ir_equations.SE-IR.case2: Incorrect parameters for given flag. Run `help ir_equations` for more info.')\n end\n case 3 % Ideal 90 pulse\n try\n T1 = params.T1;\n TR = params.TR;\n TI = params.TI;\n \n TE = params.TE;\n \n try\n constant = params.constant;\n catch\n constant = 1;\n end\n \n Mz= constant .* (1-exp(-TR/T1) + 2.*exp(-(TR-(TE/2))./T1) - 2.*exp(-TI./T1));\n catch\n error('ir_equations.SE-IR.case3: Incorrect parameters for given flag. Run `help ir_equations` for more info.')\n end\n case 4 % Long TR\n try\n T1 = params.T1;\n TI = params.TI;\n \n try\n constant = params.constant;\n catch\n constant = 1;\n end\n \n Mz= constant .* (1 - 2.*exp(-TI./T1));\n catch\n error('ir_equations.SE-IR.case4: Incorrect parameters for given flag. Run `help ir_equations` for more info.')\n end\n end\n otherwise\n error('ir_equations.seqFlag: Incorrect seqFlag arguement. Must be either GRE-IR or SE-IR.')\nend\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Models_Functions/IRfun/ir_equations.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137296, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6923789166131223}} {"text": "function value = r8_tanh ( x )\n\n%*****************************************************************************80\n%\n%% R8_TANH evaluates the hyperbolic tangent of an R8 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the hyperbolic tangent of X.\n%\n persistent nterms\n persistent sqeps\n persistent tanhcs\n persistent xmax\n\n if ( isempty ( nterms ) )\n tanhcs = [ ...\n -0.25828756643634710438338151450605, ...\n -0.11836106330053496535383671940204, ...\n +0.98694426480063988762827307999681E-02, ...\n -0.83579866234458257836163690398638E-03, ...\n +0.70904321198943582626778034363413E-04, ...\n -0.60164243181207040390743479001010E-05, ...\n +0.51052419080064402965136297723411E-06, ...\n -0.43320729077584087216545467387192E-07, ...\n +0.36759990553445306144930076233714E-08, ...\n -0.31192849612492011117215651480953E-09, ...\n +0.26468828199718962579377758445381E-10, ...\n -0.22460239307504140621870997006196E-11, ...\n +0.19058733768288196054319468396139E-12, ...\n -0.16172371446432292391330769279701E-13, ...\n +0.13723136142294289632897761289386E-14, ...\n -0.11644826870554194634439647293781E-15, ...\n +0.98812684971669738285540514338133E-17, ...\n -0.83847933677744865122269229055999E-18, ...\n +0.71149528869124351310723506176000E-19, ...\n -0.60374242229442045413288837119999E-20, ...\n +0.51230825877768084883404663466666E-21, ...\n -0.43472140157782110106047829333333E-22, ...\n +0.36888473639031328479423146666666E-23, ...\n -0.31301874774939399883325439999999E-24, ...\n +0.26561342006551994468488533333333E-25, ...\n -0.22538742304145029883494399999999E-26, ...\n +0.19125347827973995102208000000000E-27, ...\n -0.16228897096543663117653333333333E-28, ...\n +0.13771101229854738786986666666666E-29, ...\n -0.11685527840188950118399999999999E-30, ...\n +0.99158055384640389120000000000000E-32 ]';\n nterms = r8_inits ( tanhcs, 31, 0.1 * r8_mach ( 3 ) );\n sqeps = sqrt ( 3.0 * r8_mach ( 3 ) );\n xmax = - 0.5 * log ( r8_mach ( 3 ) );\n end\n\n y = abs ( x );\n\n if ( y <= sqeps )\n\n value = x;\n\n elseif ( y <= 1.0 )\n\n value = x * ( 1.0 + r8_csevl ( 2.0 * x * x - 1.0, tanhcs, nterms ) );\n\n elseif ( y <= xmax )\n\n y = exp ( y );\n yrec = 1.0 / y;\n value = ( y - yrec ) / ( y + yrec );\n\n if ( x < 0.0 )\n value = - value;\n end\n\n else\n\n if ( x < 0.0 )\n value = - 1.0;\n else\n value = + 1.0;\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/fn/r8_tanh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.6923361679866166}} {"text": "function quadrule_test07 ( )\n\n%*****************************************************************************80\n%\n%% TEST07 tests FEJER1_RULE_COMPUTE and FEJER1_RULE_SET.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 March 2007\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST07\\n' );\n fprintf ( 1, ' FEJER1_RULE_COMPUTE computes\\n' );\n fprintf ( 1, ' a Fejer type 1 quadrature rule.\\n' );\n fprintf ( 1, ' FEJER1_RULE_SET sets\\n' );\n fprintf ( 1, ' a Fejer type 1 quadrature rule.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Compare:\\n' );\n fprintf ( 1, ' (X1,W1) from FEJER1_RULE_SET\\n' );\n fprintf ( 1, ' (X2,W2) from FEJER1_RULE_COMPUTE\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ...\n ' Order W1 W2 X1 X2\\n' );\n fprintf ( 1, '\\n' );\n\n for order = 1 : 3 : 10\n\n [ x1, w1 ] = fejer1_rule_set ( order );\n [ x2, w2 ] = fejer1_rule_compute ( order );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' %8d\\n', order );\n\n for i = 1 : order\n fprintf ( 1, ' %12f %12f %12f %12f\\n', ...\n w1(i), w2(i), x1(i), x2(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/quadrule_fast/quadrule_fast_test07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.6923286951814197}} {"text": "function line_nco_rule_test01 ( )\n\n%*****************************************************************************80\n%\n%% LINE_NCO_RULE_TEST01 computes and prints NCO rules.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 28 July 2014\n%\n% Author:\n%\n% John Burkardt\n%\n a = -1.0;\n b = +1.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LINE_NCO_RULE_TEST01\\n' );\n fprintf ( 1, ' LINE_NCO_RULE computes the Newton-Cotes Open rule\\n' );\n fprintf ( 1, ' using N equally spaced points for an interval [A,B].\\n' );\n\n for n = 1 : 12\n\n [ x, w ] = line_nco_rule ( n, a, b );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Newton-Cotes Open Rule #%d\\n', n );\n fprintf ( 1, ' I X(I) W(I)\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %2d %14.6g %14.6g\\n', i, x(i), w(i) );\n end\n fprintf ( 1, ' Sum(|W)|) = %14.6g\\n', sum ( abs ( w(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/line_nco_rule/line_nco_rule_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.6923286864418342}} {"text": "function dtr = sv_clock_bias(t, toc, a0, a1, a2, e, sqrtA, toe, Delta_n, M0)\n% \u8f93\u5165:\n% a0 a1 a2 toc: \u536b\u661f\u65f6\u949f\u6821\u6b63\u6a21\u578b\u65b9\u7a0b\u4e2d3\u4e2a\u53c2\u6570\uff0c toc: \u7b2c\u4e00\u6570\u636e\u5757\u53c2\u8003\u65f6\u95f4, \u88ab\u7528\u4f5c\u65f6\u949f\u6821\u6b63\u6a21\u578b\u4e2d\u65f6\u95f4\u53c2\u8003\u70b9\n\n% dtr\uff1a \u536b\u661f\u65f6\u949f\u504f\u5dee\n\ndtr = a0+a1*(t-toc)+a2*(t-toc).^2;%t\u4e3a\u672a\u505a\u949f\u5dee\u6539\u6b63\u7684\u89c2\u6d4b\u65f6\u523b\n\n\nF = -4.442807633e-10;\nmu = 3.986005e14;\nA = sqrtA^2;\ncmm = sqrt(mu/A^3); % computed mean motion\ntk = t - toe;\n% account for beginning or end of week crossover\nif (tk > 302400)\n tk = tk-604800;\nend\nif (tk < -302400)\n tk = tk+604800;\nend\n% apply mean motion correction\nn = cmm + Delta_n;\n\n% Mean anomaly\nmk = M0 + n*tk;\n\n% solve for eccentric anomaly\nEk = mk;\nEk = mk + e*sin(Ek);\nEk = mk + e*sin(Ek);\nEk = mk + e*sin(Ek);\n\n% dsv \u65f6\u95f4\u4e3as\ndtr = dtr + F*e*sqrtA*sin(Ek);\n \nend", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/lib/gnss/sv_clock_bias.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6923195061823728}} {"text": "function [yd2] = ft22yd2(ft2)\n% Convert area from square feet to square yards.\n% Chad A. Greene 2012\nyd2 = ft2/9;", "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/35258-unit-converters/unit_converters/ft22yd2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6921886260554417}} {"text": "function x=randvec(n,m,c,w,mode)\n%RANDVEC Generate real or complex GMM/lognormal random vectors X=(N,M,C,W,MODE)\n% generates a random matrix of size (|n|,p) where p is the maximum\n% dimension of M or C (see note below about row versus column vectos)\n% Inputs: N is the number of points to generate\n% M(K,P) is the mean vectors (one row per mixture)\n% C(K,P) are diagonal covariances (one row per mixture)\n% or C(P,P,K) are full covariance matrices (one per mixture)\n% W(K) are the mixture weights (or omit if all mixtures have equal weight)\n% MODE character string specifying options:\n% g = real gaussian [default]\n% c = complex gaussian\n% l = lognormal\n%\n% Outputs: X(N,P) is the output data\n%\n% Note this routine generates row vectors such that E((x-m)'*(x-m)) = C = cov(x). If\n% Alternatively x=(n,m',c,w,mode)' will generate column vectors satisfying E((x-m)*(x-m)') = C = cov(x').\n\n% Bugs/suggestions\n% (1) New mode 'x' to approximate chi squared\n\n% Copyright (C) Mike Brookes 1998\n% Version: $Id: randvec.m 9549 2017-03-08 09:39:50Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\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 can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% first sort out the input arguments\n\nsm=size(m);\nif nargin<3\n c=ones(sm); % default to unit variance\nend\nsc=size(c);\np=max(sm(2),sc(2)); % data dimension\nk=sm(1); % number of mixtures\nfullc=(length(sc)>2) || (sc(1)>k);\nif nargin<4\n mode='g'; % default to gaussian\n w=ones(k,1);\nelse\n if ischar(w)\n mode = w; % w argument has been omitted\n w=ones(k,1);\n elseif nargin<5\n mode='g';\n end\nend\nty=mode(1); % ignore all but first character for type\nx=zeros(n,p); % initialize output array\nif sm(2)~=p\n m=repmat(m,1,p); % if m is given as a scalar\nend\nif sc(2) ~=p\n c=repmat(c,1,p); % if c is given as a scalar\nend\nq=sqrt(0.5);\nif k>1\n kx=randiscr(w,n);\nelse\n kx=ones(n,1);\nend\nfor kk=1:k\n nx=find(kx==kk);\n nn=length(nx);\n if nn % check if we need to generate any from mixture kk\n\n % extract the mean and cov for this mixture\n\n mm=m(kk,:); % mean vector\n if fullc % full covariance matrix\n cc=c(:,:,kk);\n if ty=='l' % lognormal distribution - convert mean and covariance\n cc=log(1+cc./(mm.'*mm));\n mm=log(mm)-0.5*diag(cc).';\n end\n else\n cc=c(kk,:);\n if ty=='l' % lognormal distribution - convert mean and covariance\n cc=log(1+cc(:).'./mm.^2);\n mm=log(mm)-0.5*cc;\n end\n end\n\n % now generate nn complex or real values\n\n if ty=='c' % generate complex values\n xx=q*randn(nn,p)+1i*q*randn(nn,p); % complex-valued unit variance values\n else\n xx=randn(nn,p); % real-valued unit variance values\n end;\n\n % scale by the square root of the covariance matrix\n\n if fullc % full covariance covariance\n [v,d]=eig((cc+cc')/2); % force covariance matrix to be hermitian\n xx=(xx.*repmat(sqrt(abs(diag(d))).',nn,1))*v'+repmat(mm,nn,1); % and also positive definite\n else\n xx=xx.*repmat(sqrt(abs(cc)),nn,1)+repmat(mm,nn,1); % different mean/cov for each column\n end\n x(nx,:)=xx;\n end\nend\nif ty=='l' % lognormal distribution\n x=exp(x);\nend\nif ~nargout\n if p==1\n if ty=='c'\n plot(real(x), imag(x),'+');\n xlabel('Real');\n ylabel('Imag');\n else\n nbin=max(min(floor(sqrt(n)),50),5);\n hist(x,nbin);\n xlabel('X');\n ylabel('Frequency');\n end\n else\n [vv,iv]=sort(var(x,0,1));\n iv=sort(iv(end-1:end));\n plot(real(x(:,iv(1))), real(x(:,iv(2))),'+');\n if ty=='c'\n xylab='Real[ x(%d) ]';\n else\n xylab='x(%d)';\n end\n xlabel(sprintf(xylab,iv(1)));\n ylabel(sprintf(xylab,iv(2)));\n end\nend\n\n", "meta": {"author": "jtkim-kaist", "repo": "Speech-enhancement", "sha": "84f1a3c1273fb4952522b911dd62cbb4476a534d", "save_path": "github-repos/MATLAB/jtkim-kaist-Speech-enhancement", "path": "github-repos/MATLAB/jtkim-kaist-Speech-enhancement/Speech-enhancement-84f1a3c1273fb4952522b911dd62cbb4476a534d/SE/lib/sub_lib/voicebox/randvec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6921886192394265}} {"text": "function SNR = Convert_SNR(SNR_dB)\n\n% Convert back from dBs to SNR value \n%SNR_dB = 10 * Log10(SNR)\n\nSNR = 10^(SNR_dB/10);", "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/27116-mfsk-modulation-in-awgn-noise-with-reed-solomon-decoding/MFSK/MFSK/Convert_SNR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6921886180757333}} {"text": "clear all;\nclose all;\nclc;\nrng default;\n\n% Ambient space dimension\nM = 50;\n% Number of subspaces\nK = 10;\n% common dimension for each subspace\nD = 20;\n\n% Construct bases for random subspaces\nbases = spx.data.synthetic.subspaces.random_subspaces(M, K, D);\n% samples angles between subspaces\nangles_matrix = spx.la.spaces.smallest_angles_deg(bases)\nangles = spx.matrix.off_diag_upper_tri_elements(angles_matrix)';\nmin(angles)\n\n% Number of points on each subspace\nSk = 4 * D;\n\ncluster_sizes = Sk * ones(1, K);\n% total number of points\nS = sum(cluster_sizes);\n\npoints_result = spx.data.synthetic.subspaces.uniform_points_on_subspaces(bases, cluster_sizes);\nX0 = points_result.X;\n\n% noise level\nsigma = 0.5;\n% Generate noise\nNoise = sigma * spx.data.synthetic.uniform(M, S);\n% Add noise to signal\nX = X0 + Noise;\n% Normalize noisy signals.\nX = spx.norm.normalize_l2(X); \n% labels assigned to the data points\ntrue_labels = spx.cluster.labels_from_cluster_sizes(cluster_sizes);\ncvx_solver sdpt3\ncvx_quiet(true);\n\n% storage for coefficients\nZ = zeros(S, S);\nstart_time = tic;\nfprintf('Processing %d signals\\n', S);\nfor s=1:S\n fprintf('.');\n if (mod(s, 50) == 0)\n fprintf('\\n');\n end\n x = X(:, s);\n cvx_begin\n % storage for l1 solver\n variable z(S, 1);\n minimize norm(z, 1)\n subject to\n x == X*z;\n z(s) == 0;\n cvx_end\n Z(:, s) = z;\nend\nelapsed_time = toc(start_time);\nfprintf('\\n Time spent: %.2f seconds\\n', elapsed_time);\nW = abs(Z) + abs(Z).';\nclustering_result = spx.cluster.spectral.simple.normalized_symmetric(W);\ncluster_labels = clustering_result.labels;\n% Time to compare the clustering\ncomparsion_result = spx.cluster.clustering_error_hungarian_mapping(cluster_labels, true_labels, K);\nclustering_error_perc = comparsion_result.error_perc;\nclustering_acc_perc = 100 - comparsion_result.error_perc;\n\nspr_stats = spx.cluster.subspace.subspace_preservation_stats(Z, cluster_sizes);\nspr_error = spr_stats.spr_error;\nspr_flag = spr_stats.spr_flag;\nspr_perc = spr_stats.spr_perc;\nelapsed_time = toc(start_time);\nfprintf('\\nclustering error: %0.2f %%, clustering accuracy: %0.2f %% \\n'...\n , clustering_error_perc, clustering_acc_perc);\nfprintf('mean spr error: %0.2f, preserving : %0.2f %%\\n', spr_stats.spr_error, spr_stats.spr_perc);\nfprintf('elapsed time: %0.2f sec', elapsed_time);\nfprintf('\\n\\n');\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/docs/book/subspace_clustering/demo_ssc_bp_random_subspaces.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6921886144183382}} {"text": "% Local Regression and Likelihood, Figure 8.3.\n%\n% Discrimination/Classification, iris data for different\n% smooting paramters.\n%\n% Note that the iris.mat file contains the full iris dataset;\n% only Versicolor and Virginica are used in this example.\n%\n% The `Species' variable contains species names. `Specn' has\n% them numerically, Setosa=1, Versicolor=2, Virginica=3.\n%\n% Author: Catherine Loader\n%\n% Need: get contour plot correct.\n% Need: distinguish colors in plot.\n\nload iris;\na = (2:9)/10;\nz = zeros(size(a));\n\nu = find(Specn >= 2);\npw = PetalWid(u);\npl = PetalLen(u);\ny = (Specn(u)==3);\n\nfor i = 1:length(a)\n fit = locfit([pw pl],y,'deg',1,'alpha',a(i),'ev','cros','scale',0,'family','binomial');\n fv = fitted(fit);\n tb = tabulate(10*y+(fv>=0.5))\n z(i) = sum(y == (fv<=0.5));\nend;\n\n[a; z]\n\nfit = locfit([pw pl],y,'deg',1,'scale',0,'family','binomial');\nfigure('Name','fig8_3: iris classification');\nlfplot(fit,'contour');\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/locfit/Book/fig8_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6921886132546451}} {"text": "function euler = quatern2euler(q)\n%QUATERN2EULER Converts a quaternion orientation to ZYX Euler angles\n%\n% q = quatern2euler(q)\n%\n% Converts a quaternion orientation to ZYX Euler angles where phi is a\n% rotation around X, theta around Y and psi around Z.\n%\n% For more information see:\n% http://www.x-io.co.uk/node/8#quaternions\n%\n%\tDate Author Notes\n%\t27/09/2011 SOH Madgwick Initial release\n\n R(1,1,:) = 2.*q(:,1).^2-1+2.*q(:,2).^2;\n R(2,1,:) = 2.*(q(:,2).*q(:,3)-q(:,1).*q(:,4));\n R(3,1,:) = 2.*(q(:,2).*q(:,4)+q(:,1).*q(:,3));\n R(3,2,:) = 2.*(q(:,3).*q(:,4)-q(:,1).*q(:,2));\n R(3,3,:) = 2.*q(:,1).^2-1+2.*q(:,4).^2;\n\n phi = atan2(R(3,2,:), R(3,3,:) );\n theta = -atan(R(3,1,:) ./ sqrt(1-R(3,1,:).^2) );\n psi = atan2(R(2,1,:), R(1,1,:) );\n\n euler = [phi(1,:)' theta(1,:)' psi(1,:)'];\nend\n\n", "meta": {"author": "xioTechnologies", "repo": "Oscillatory-Motion-Tracking-With-x-IMU", "sha": "314208abbb592c9623ad0940138ea597447774a9", "save_path": "github-repos/MATLAB/xioTechnologies-Oscillatory-Motion-Tracking-With-x-IMU", "path": "github-repos/MATLAB/xioTechnologies-Oscillatory-Motion-Tracking-With-x-IMU/Oscillatory-Motion-Tracking-With-x-IMU-314208abbb592c9623ad0940138ea597447774a9/quaternion_library/quatern2euler.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904955, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.692188605274936}} {"text": "function err = getH1error(node,elem,Du,uh,K,quadOrder)\n%% GETH1ERROR H1 norm of the approximation error.\n%\n% err = getH1error(node,elem,@Du,uh,K) computes the H1 norm of the\n% error between the exact solution Du and finite element approximation\n% uh on a mesh described by node and elem. \n%\n% The input parameter Du is a function handle and uh is either a column\n% array with length N representing a piecewise linear function on the mesh\n% or a (NT,2) array representing the gradient of a linear function. The\n% diffusion coefficient K is either a NT by 1 array or a function handle.\n%\n% err = getH1error(node,elem,@Du,uh,d,quadOrder) computes error\n% using the quadrature rule with order quadOrder (up to 9). The default\n% order is 3.\n% \n% Example: compute H1 error of piecewise linear interpolation\n%\n% [node,elem] = squaremesh([0,1,0,1],0.25);\n% for k = 1:4\n% exactu = inline('sin(pi*pxy(:,1)).*sin(pi*pxy(:,2))','pxy');\n% Du = inline('[pi*cos(pi*pxy(:,1)).*sin(pi*pxy(:,2)) pi*sin(pi*pxy(:,1)).*cos(pi*pxy(:,2))]','pxy');\n% uI = exactu(node);\n% N(k) = size(node,1);\n% err(k) = getH1error(node,elem,Du,uI);\n% [node,elem] = uniformrefine(node,elem);\n% end\n% showrate(N,err);\n%\n% See also getH1error3, getL2error, getL2error3, quadpts.\n%\n% The quadratic element is added by Ming Wang. The cubic element is added by Jie Zhou.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nNu = size(uh,1); N = size(node,1); NT = size(elem,1);\n% Euler formula N-NE+NT = c % rough estimateus using Euler formula\nNE = N + NT; NP2 = N + NE; NP3 = N + 2*NE + NT; \nif Nu > N+NT-5 % Euler formula N-NE+NT = c\n elem2dof = dofP2(elem);\n NP2 = max(elem2dof(:));\n NE = NP2 - N;\n NP3 = N+2*NE+NT; \nend\n\n%% Default quadrature orders for different elements\nif ~exist('quadOrder','var')\n switch Nu\n case NT % piecewise constant vector (uh is Duh)\n quadOrder = 3;\n case N % piecewise linear function P1 element\n quadOrder = 3; \n case NE % piecewise linear function CR element\n quadOrder = 3; \n case NP2 % piecewise quadratic function\n quadOrder = 4;\n case NE + NT % WG element\n quadOrder = 3; \n case NP3 % P3 element\n quadOrder = 5; \n end\nend\n\n%% compute gradient of finite element function uh\nif (size(uh,2) == 2) && (Nu == NT) % uh is a piecewise constant vector\n Duh = uh;\n area = abs(simplexvolume(node,elem));\nelseif size(uh,2) == 1 % scalar function uh\n switch Nu\n case N % piecewise linear function P1 element\n [Duh,area] = gradu(node,elem,uh);\n case NE % piecewise linear function CR element\n elem2edge = elem2dof(:,4:6) - N; \n [Duh,area] = graduCR(node,elem,elem2edge,uh); \n case NE + NT % weak Galerkin element\n elem2edge = elem2dof(:,4:6) - N; \n [Duh,area] = graduWG(node,elem,elem2edge,uh); \n case NP2 % piecewise quadratic function\n [Dlambda,area] = gradbasis(node,elem);\n case NP3\n [Dlambda,area] = gradbasis(node,elem); \n elem2dof = dofP3(elem);\n end\nend\n\n%% compute H1 error element-wise using quadrature rule with order quadOrder\n[lambda,weight] = quadpts(quadOrder);\nnQuad = size(lambda,1);\nerr = zeros(NT,1);\nfor p = 1:nQuad\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ...\n + lambda(p,3)*node(elem(:,3),:);\n if Nu == NP2 % piecewise quadratic function\n Dphip1 = (4*lambda(p,1)-1).*Dlambda(:,:,1);\n Dphip2 = (4*lambda(p,2)-1).*Dlambda(:,:,2);\n Dphip3 = (4*lambda(p,3)-1).*Dlambda(:,:,3);\n Dphip4 = 4*(lambda(p,2)*Dlambda(:,:,3)+lambda(p,3)*Dlambda(:,:,2));\n Dphip5 = 4*(lambda(p,3)*Dlambda(:,:,1)+lambda(p,1)*Dlambda(:,:,3));\n Dphip6 = 4*(lambda(p,1)*Dlambda(:,:,2)+lambda(p,2)*Dlambda(:,:,1));\n Duh = repmat(uh(elem2dof(:,1)),1,2).*Dphip1 + ...\n repmat(uh(elem2dof(:,2)),1,2).*Dphip2 + ...\n repmat(uh(elem2dof(:,3)),1,2).*Dphip3 + ...\n repmat(uh(elem2dof(:,4)),1,2).*Dphip4 + ...\n repmat(uh(elem2dof(:,5)),1,2).*Dphip5 + ...\n repmat(uh(elem2dof(:,6)),1,2).*Dphip6;\n end\n if Nu == NP3 % piecewise cubic function\n Dphip1 = (27/2*lambda(p,1)*lambda(p,1)-9*lambda(p,1)+1).*Dlambda(:,:,1); \n Dphip2 = (27/2*lambda(p,2)*lambda(p,2)-9*lambda(p,2)+1).*Dlambda(:,:,2); \n Dphip3 = (27/2*lambda(p,3)*lambda(p,3)-9*lambda(p,3)+1).*Dlambda(:,:,3);\n Dphip4 = 9/2*((3*lambda(p,2)*lambda(p,2)-lambda(p,2)).*Dlambda(:,:,3)+...\n lambda(p,3)*(6*lambda(p,2)-1).*Dlambda(:,:,2)); \n Dphip5 = 9/2*((3*lambda(p,3)*lambda(p,3)-lambda(p,3)).*Dlambda(:,:,2)+...\n lambda(p,2)*(6*lambda(p,3)-1).*Dlambda(:,:,3)); \n Dphip6 = 9/2*((3*lambda(p,3)*lambda(p,3)-lambda(p,3)).*Dlambda(:,:,1)+...\n lambda(p,1)*(6*lambda(p,3)-1).*Dlambda(:,:,3)); \n Dphip7 = 9/2*((3*lambda(p,1)*lambda(p,1)-lambda(p,1)).*Dlambda(:,:,3)+...\n lambda(p,3)*(6*lambda(p,1)-1).*Dlambda(:,:,1)); \n Dphip8 = 9/2*((3*lambda(p,1)*lambda(p,1)-lambda(p,1)).*Dlambda(:,:,2)+...\n lambda(p,2)*(6*lambda(p,1)-1).*Dlambda(:,:,1)); \n Dphip9 = 9/2*((3*lambda(p,2)*lambda(p,2)-lambda(p,2)).*Dlambda(:,:,1)+...\n lambda(p,1)*(6*lambda(p,2)-1).*Dlambda(:,:,2)); \n Dphip10= 27*(lambda(p,1)*lambda(p,2)*Dlambda(:,:,3)+lambda(p,1)*lambda(p,3)*Dlambda(:,:,2)+...\n lambda(p,3)*lambda(p,2)*Dlambda(:,:,1));\n Duh = repmat(uh(elem2dof(:,1)),1,2).*Dphip1 + ...\n repmat(uh(elem2dof(:,2)),1,2).*Dphip2 + ...\n repmat(uh(elem2dof(:,3)),1,2).*Dphip3 + ...\n repmat(uh(elem2dof(:,4)),1,2).*Dphip4 + ...\n repmat(uh(elem2dof(:,5)),1,2).*Dphip5 + ...\n repmat(uh(elem2dof(:,6)),1,2).*Dphip6 + ...\n repmat(uh(elem2dof(:,7)),1,2).*Dphip7 + ...\n repmat(uh(elem2dof(:,8)),1,2).*Dphip8 + ...\n repmat(uh(elem2dof(:,9)),1,2).*Dphip9 + ... \n repmat(uh(elem2dof(:,10)),1,2).*Dphip10;\n end \n if exist('K','var') && ~isempty(K) && ~isnumeric(K) % K is a function\n err = err + weight(p)*K(pxy).*sum((Du(pxy)-Duh).^2,2);\n else\n err = err + weight(p)*sum((Du(pxy)-Duh).^2,2); \n end\nend\nif exist('K','var') && ~isempty(K) && isnumeric(K) && size(K,1) == NT\n err = K.*err; % K is piecewise constant\nend\nerr = area.*err;\nerr(isnan(err)) = 0; % singular values are excluded\nerr = sqrt(sum(err));", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/getH1error.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.69212136667216}} {"text": "function f = flops_det(n)\n% FLOPS_DET Flops for matrix determinant.\n% FLOPS_DET(n) returns the number of flops for det(eye(n)).\n\nif n == 1\n f = 1;\nelse\n % this is from logdet\n f = flops_chol(n) + n;\nend\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/external/lightspeed/flops_det.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6921213592388308}} {"text": "function y = naca4_symmetric ( t, c, x )\n\n%*****************************************************************************80\n%\n%% NACA4_SYMMETRIC evaluates y(x) for a NACA symmetric 4-digit airfoil.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 October 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Eastman Jacobs, Kenneth Ward, Robert Pinkerton,\n% \"The characteristics of 78 related airfoil sections from tests in\n% the variable-density wind tunnel\",\n% NACA Report 460, 1933.\n%\n% Parameters:\n%\n% Input, real T, the maximum relative thickness.\n%\n% Input, real C, the chord length.\n%\n% Input, real X(*), points along the chord length. \n% 0.0 <= X(*) <= C.\n%\n% Output, real Y(*), for each value of X, the corresponding value of Y\n% so that (X,Y) is on the upper wing surface, and (X,-Y) is on the\n% lower wing surface.\n%\n y = 5.0 * t * c * ( ...\n 0.2969 * sqrt ( x / c ) ...\n + (((( ...\n - 0.1015 ) .* ( x / c ) ...\n + 0.2843 ) .* ( x / c ) ...\n - 0.3516 ) .* ( x / c ) ...\n - 0.1260 ) .* ( x / c ) );\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/naca/naca4_symmetric.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6921213592388307}} {"text": "function q = fromTransfMatrixToPosQuat(H)\n\n % FROMTRANSFMATRIXTOQUATERNIONS computes a link pose using position \n % + quaternion rapresentation. The input is \n % the link pose represented by a transformation matrix.\n %\n % FORMAT: q = fromTransfMatrixToPosQuat(H) \n %\n % INPUT: - H = [4 * 4] transf matrix representing link pose\n %\n % OUTPUT: - q = [7 * 1] position + quaternions representing link pose\n %\n % Authors: Daniele Pucci, Marie Charbonneau, Gabriele Nava\n % \n % all authors are with the Italian Istitute of Technology (IIT)\n % email: name.surname@iit.it\n %\n % Genoa, Dec 2017\n %\n\n %% --- Initialization ---\n\n % Separate the rotation matrix\n R = H(1:3,1:3);\n qt_b = zeros(4,1);\n \n % min. value to treat a number as zero\n epsilon = 1e-12; \n \n % Compute the corresponding (unit) quaternion from a given rotation matrix R:\n %\n % The transformation uses the computational efficient algorithm of Stanley.\n % To be numerically robust, the code determines the set with the maximum\n % divisor for the calculation.\n %\n % For further details about the Stanley Algorithm, see:\n % [1] Optimal Spacecraft Rotational Maneuvers, John L. Junkins & James D. Turner, Elsevier, 1986, pp. 28-29, eq. (2.57)-(2.59).\n % [2] Theory of Applied Robotics: Kinematics, Dynamics, and Control, Reza N. Jazar, 2nd Edition, Springer, 2010, p. 110, eq. (3.149)-(3.152).\n % Note: There exist also an optimized version of the Stanley method and is the fastest\n % possible computation method for Matlab, but it does not cover all special cases.\n % Further details about the fast calculation can be found at:\n % [3] Modelling and Control of Robot Manipulators, L. Sciavicco & B. Siciliano, 2nd Edition, Springer, 2008,\n % p. 36, formula (2.30).\n %\n tr = R(1,1) + R(2,2) + R(3,3);\n \n if (tr > epsilon)\n \n % scalar part:\n qt_b(1,1) = 0.5*sqrt(tr + 1);\n s_inv = 1/(qt_b(1,1)*4);\n \n % vector part:\n qt_b(2,1) = (R(3,2) - R(2,3))*s_inv;\n qt_b(3,1) = (R(1,3) - R(3,1))*s_inv;\n qt_b(4,1) = (R(2,1) - R(1,2))*s_inv;\n else\n % if tr <= 0, find the greatest diagonal element for calculating\n % the scale factor s and the vector part of the quaternion\n if ((R(1,1) > R(2,2)) && (R(1,1) > R(3,3)))\n \n qt_b(2,1) = 0.5*sqrt(R(1,1) - R(2,2) - R(3,3) + 1);\n s_inv = 1/(qt_b(2,1)*4);\n\n qt_b(1,1) = (R(3,2) + R(2,3))*s_inv;\n qt_b(3,1) = (R(2,1) + R(1,2))*s_inv;\n qt_b(4,1) = (R(3,1) + R(1,3))*s_inv;\n \n elseif (R(2,2) > R(3,3))\n \n qt_b(3,1) = 0.5*sqrt(R(2,2) - R(3,3) - R(1,1) + 1);\n s_inv = 1/(qt_b(3,1)*4);\n\n qt_b(1,1) = (R(1,3) - R(3,1))*s_inv;\n qt_b(2,1) = (R(2,1) + R(1,2))*s_inv;\n qt_b(4,1) = (R(3,2) + R(2,3))*s_inv;\n else\n qt_b(4,1) = 0.5*sqrt(R(3,3) - R(1,1) - R(2,2) + 1);\n s_inv = 1/(qt_b(4,1)*4);\n \n qt_b(1,1) = (R(2,1) - R(1,2))*s_inv;\n qt_b(2,1) = (R(3,1) + R(1,3))*s_inv;\n qt_b(3,1) = (R(3,2) + R(2,3))*s_inv;\n end\n end\n\n % Final state converted into quaternion rapresentation\n q = [H(1:3,4); qt_b];\nend", "meta": {"author": "robotology", "repo": "whole-body-controllers", "sha": "90ff965a523f0a120e6a8981b71326c1485e7742", "save_path": "github-repos/MATLAB/robotology-whole-body-controllers", "path": "github-repos/MATLAB/robotology-whole-body-controllers/whole-body-controllers-90ff965a523f0a120e6a8981b71326c1485e7742/library/matlab-wbc/+wbc/fromTransfMatrixToPosQuat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6921213580184786}} {"text": "function [beta_gibbs,sigma_gibbs]=ndgibbstotal(It,Bu,X,Y,y,Bhat,n,T,q)\n\n% modified ndgibbs sampler: insensitive to hyperparameters, total diffuse, \"flat\" prior in spirit of Uhlig (2005)\n\n% function [beta_gibbs sigma_gibbs]=bear.ndgibbs(It,Bu,beta0,omega0,X,Y,y,Bhat,n,T,q)\n% performs the Gibbs algorithm 1.5.2 for the normal-diffuse prior, and returns draws from posterior distribution\n% inputs: - integer 'It': total number of iterations of the Gibbs sampler (defined p 28 of technical guide)\n% - integer 'Bu': number of burn-in iterations of the Gibbs sampler (defined p 28 of technical guide)\n% - vector 'beta0': vector of prior values for beta (defined in 1.3.4)\n% - matrix 'omega0': prior covariance matrix for the VAR coefficients (defined in 1.3.8)\n% - matrix 'X': matrix of regressors for the VAR model (defined in 1.1.8)\n% - matrix 'Y': matrix of regressands for the VAR model (defined in 1.1.8)\n% - vector 'y': vectorised regressands for the VAR model (defined in 1.1.12)\n% - matrix 'Bhat': OLS VAR coefficients, in non vectorised form (defined in 1.1.9)\n% - integer 'n': number of endogenous variables in the BVAR model (defined p 7 of technical guide)\n% - integer 'T': number of sample time periods (defined p 7 of technical guide)\n% - integer 'q': total number of coefficients to estimate for the BVAR model (defined p 7 of technical guide)\n% outputs: - matrix 'beta_gibbs': record of the gibbs sampler draws for the beta vector\n% - matrix'sigma_gibbs': record of the gibbs sampler draws for the sigma matrix (vectorised)\n\n\n\n% preliminary tasks\n\n% % invert omega0, as it will be used repeatedly during step 4\n% invomega0=diag(1./diag(omega0));\n\n% set initial values for B (step 2); use OLS estimates\nB=Bhat;\n\n% create the progress bar\nhbar = bear.parfor_progressbar(It,'Progress of the Gibbs sampler.');\n\n% start iterations\nfor ii=1:It\n\n% Step 3: at iteration ii, first draw sigma from IW, conditional on beta from previous iteration\n% obtain first Shat, defined in (1.6.10)\nShat=(Y-X*B)'*(Y-X*B);\n% Correct potential asymmetries due to rounding errors from Matlab\nC=chol(bear.nspd(Shat));\nShat=C'*C;\n\n% next draw from IW(Shat,T)\nsigma=bear.iwdraw(Shat,T);\n\n% step 4: with sigma drawn, continue iteration ii by drawing beta from a multivariate Normal, conditional on sigma obtained in current iteration\n% first invert sigma\nC=chol(bear.nspd(sigma));\ninvC=C\\speye(n);\ninvsigma=invC*invC';\n\n% then obtain the omegabar matrix\ninvomegabar=kron(invsigma,X'*X);\nC=chol(bear.nspd(invomegabar));\ninvC=C\\speye(q);\nomegabar=invC*invC';\n\n% following, obtain betabar\nbetabar=omegabar*(kron(invsigma,X')*y);\n\n% draw from N(betabar,omegabar);\nbeta=betabar+chol(bear.nspd(omegabar),'lower')*mvnrnd(zeros(q,1),eye(q))';\n\n% % update matrix B with each draw\n% B=reshape(beta,size(B));\n\n% record the values if the number of burn-in iterations is exceeded\nif ii>Bu\n% values of vector beta\nbeta_gibbs(:,ii-Bu)=beta;\n% values of sigma (in vectorized form)\nsigma_gibbs(:,ii-Bu)=sigma(:);\n% if current iteration is still a burn iteration, do not record the result\nelse\nend\n\n% update progress by one iteration\nhbar.iterate(1); \n\n% go for next iteration\nend\n% close progress bar\nclose(hbar);\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/ndgibbstotal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.692121354301814}} {"text": "function lambda = carry_eigenvalues ( n, alpha )\n\n%*****************************************************************************80\n%\n%% CARRY_EIGENVALUES returns the eigenvalues of the CARRY matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 September 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, integer ALPHA, the numeric base being used in the addition.\n%\n% Output, real LAMBDA(N,1), the eigenvalues.\n%\n lambda = zeros ( n, 1 );\n\n for i = 1 : n\n lambda(i,1) = 1.0 / alpha^(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/test_mat/carry_eigenvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.6920782854364816}} {"text": "% FIT_CUBIC_BEZIER Fit a cubic bezier spline (G1 continuous) to an ordered list\n% of input points in any dimension, according to \"An algorithm for automatically\n% fitting digitized curves\" [Schneider 1990].\n% \n% Inputs:\n% d #d by dim list of points along a curve to be fit with a cubic bezier\n% spline (should probably be roughly uniformly spaced). If d(0)==d(end),\n% then will treat as a closed curve.\n% error maximum squared distance allowed\n% Output:\n% cubics #cubics list of 4 by dim lists of cubic control points\n%\n% Example:\n% [P,~,C] = remove_duplicate_vertices(cell2mat(fit_cubic_bezier(X,1)),0);\n% C = reshape(C,4,[])';\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mex/fit_cubic_bezier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.6920564799627038}} {"text": "function [n,J] = dyadlength(x)\n% dyadlength -- Find length and dyadic length of array\n% Usage\n% [n,J] = dyadlength(x)\n% Inputs\n% x array of length n = 2^J (hopefully)\n% Outputs\n% n length(x)\n% J least power of two greater than n\n%\n% Side Effects\n% A warning is issued if n is not a power of 2.\n%\n% See Also\n% quadlength, dyad, dyad2ix\n%\n n = length(x) ;\n J = ceil(log(n)/log(2));\n if 2^J ~= n ,\n disp('Warning in dyadlength: n != 2^J')\n end\n \n \n \n \n%\n% Part of Wavelab Version 850\n% Built Tue Jan 3 13:20:40 EST 2006\n% This is Copyrighted Material\n% For Copying permissions see COPYING.m\n% Comments? e-mail wavelab@stat.stanford.edu \n", "meta": {"author": "BUNPC", "repo": "Homer3", "sha": "d0fac4b22d1069eaa5cba268a225eb117ddcdca1", "save_path": "github-repos/MATLAB/BUNPC-Homer3", "path": "github-repos/MATLAB/BUNPC-Homer3/Homer3-d0fac4b22d1069eaa5cba268a225eb117ddcdca1/FuncRegistry/UserFunctions/dyadlength.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.6920564709767676}} {"text": "function [vValues] = bruteforceloglikecgr(time_as)\n % bruteforceloglike Calculates by a constrained grid search\n %\n % [pv, cv, kv] = bruteforceloglike(time_as);\n % vValues = [pvalue, cvalue, kvalue];\n % --------------------------------------------\n % the parameters of the modified Omori formula\n % using the log likelihood function by Ogata\n %\n % Input parameters:\n % time_as Delay time [days]\n %\n % Output parameters:\n % pv p value\n % cv c value\n % kv k value\n %\n % Samuel Neukomme\n % July 31, 2002\n\n options = optimset('Display','none','MaxFunEvals',400,'TolFun',1e-04,'MaxIter',500);\n vStartValues = [1.1 0.5 200];\n\n [vValues, ~] = fmincon(@bruteloglike, vStartValues, [], [], [], [],...\n [0.2 0.01 10], [2.7 3 5000], [], options, time_as);\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/bruteforceloglikecgr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.946596665680527, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6920176184948837}} {"text": "function cross_time=MeanCrossingRate(data)\n%\tAcc feas Computation\n% INPUT:\n% data NO*1\n% OUTPUT:\n% cross_time: 1*1 mean crossing rate\n\nmean_series = data - mean(data);\ncross_time = 0;\nfor i = 2:length(data)\n if mean_series(i-1)*mean_series(i) < 0\n cross_time = cross_time + 1;\n end\nend", "meta": {"author": "jindongwang", "repo": "activityrecognition", "sha": "33687803886d4a184e0b285e3ec7ab73a8f86355", "save_path": "github-repos/MATLAB/jindongwang-activityrecognition", "path": "github-repos/MATLAB/jindongwang-activityrecognition/activityrecognition-33687803886d4a184e0b285e3ec7ab73a8f86355/code/matlab/core/MeanCrossingRate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.6920132978993461}} {"text": "function [ vX, mX ] = SolveLsL1Prox( mA, vB, paramLambda, numIterations )\n% ----------------------------------------------------------------------------------------------- %\n%[ vX, mX ] = SolveLsL1Prox( mA, vB, lambdaFctr, numIterations )\n% Solve L1 Regularized Least Squares Using Proximal Gradient (PGM) Method.\n% Input:\n% - mA - Input Matirx.\n% The model matrix.\n% Structure: Matrix (m X n).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - vB - input Vector.\n% The model known data.\n% Structure: Vector (m X 1).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - paramLambda - Parameter Lambda.\n% The L1 Regularization parameter.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: (0, inf).\n% - numIterations - Number of Iterations.\n% Number of iterations of the algorithm.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range {1, 2, ...}.\n% Output:\n% - vX - Output Vector.\n% Structure: Vector (n X 1).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% References\n% 1. Wikipedia PGM - https://en.wikipedia.org/wiki/Proximal_gradient_method.\n% Remarks:\n% 1. Using vanilla PGM.\n% Known Issues:\n% 1. A\n% TODO:\n% 1. B\n% Release Notes:\n% - 1.0.000 23/08/2017\n% * First realease version.\n% ----------------------------------------------------------------------------------------------- %\n\nmAA = mA.' * mA;\nvAb = mA.' * vB;\nvX = pinv(mA) * vB; %.\nfunction speed_demo_with_movement_sinusoidal\nclose all\n\nrobot = load_robot('OMRON', 'ECOBRA600')\n\n\n% example trajectories (10 seconds)\ndelta_t = 0.01; % s\nt = 0:delta_t:20;\nw1 = 0.5; %rad/s\nw2 = 1.0; %rad/s\nw3 = 1.5; %m/s\n\nqt = [sin(w1*t); cos(w2*t); 0.1*(sin(w3*t)+0.3*cos(w3*t)); 0*t];\n\nqds = [];\nvs = [];\n\nfor i=1:length(t)-1\n % joint position\n q = qt(:, i); \n % joint speed\n qd = (qt(:, i+1) - qt(:, i))/delta_t;\n \n J = manipulator_jacobian(robot, q); \n % end effector's velocity\n v = J*qd; \n qds = [qds qd];\n vs = [vs v];\nend\nqds = [qds qd];\nvs = [vs v];\n\nfigure, plot(t, qt)\ntitle('Posici\u00f3n articular')\nxlabel('tiempo (s)')\nylabel('q (rad)')\nlegend('q1 (rad)', 'q2 (rad)', 'q3 (m)')\n\nfigure, plot(t, qds)\ntitle('Velocidad articular')\nxlabel('tiempo (s)')\nylabel('qd (rad)')\nlegend('qd1 (rad/s)', 'qd2 (rad/s)', 'qd3 (m/s)')\n\nfigure, plot(t, vs)\ntitle('Velocidad en el extremo')\nxlabel('tiempo (s)')\nylabel('v (m/s)')\nlegend('vx m/s', 'vy m/s', 'vz m/s')\n\n% animamos el resultado\n%animate(robot, qt(:, 1:10:end))\n% animamos el resultado con un vector de velocidad en el extremo del robot\nfor i=1:5:length(t)\n q = qt(:,i);\n v = vs(:,i);\n T = directkinematic(robot, q);\n \n %plot speed\n p0 = T(1:3,4);\n drawrobot3d(robot, q)\n draw_vector(v(1:3), p0, ' V', 3)\n pause(0.1)\nend\n\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/robots/OMRON/ECOBRA600/speed_demo_with_movement_sinusoidal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6920132862681072}} {"text": "% sq_dist - a function to compute a matrix of all pairwise squared distances\n% between two sets of vectors, stored in the columns of the two matrices, a\n% (of size D by n) and b (of size D by m). If only a single argument is given\n% or the second matrix is empty, the missing matrix is taken to be identical\n% to the first.\n%\n% Special functionality: If an optional third matrix argument Q is given, it\n% must be of size n by m, and in this case a vector of the traces of the\n% product of Q' and the coordinatewise squared distances is returned.\n%\n% NOTE: The program code is written in the C language for efficiency and is\n% contained in the file sq_dist.c, and should be compiled using matlabs mex\n% facility. However, this file also contains a (less efficient) matlab\n% implementation, supplied only as a help to people unfamiliar with mex. If\n% the C code has been properly compiled and is avaiable, it automatically\n% takes precendence over the matlab code in this file.\n%\n% Usage: C = sq_dist(a, b)\n% or: C = sq_dist(a) or equiv.: C = sq_dist(a, [])\n% or: c = sq_dist(a, b, Q)\n% where the b matrix may be empty.\n%\n% where a is of size D by n, b is of size D by m (or empty), C and Q are of\n% size n by m and c is of size D by 1.\n%\n% Copyright (c) 2003, 2004, 2005 and 2006 Carl Edward Rasmussen. 2006-03-09.\n\nfunction C = kafbox_sq_dist(a, b, Q);\n\nif nargin < 1 | nargin > 3 | nargout > 1\n error('Wrong number of arguments.');\nend\n\nif nargin == 1 | isempty(b) % input arguments are taken to be\n b = a; % identical if b is missing or empty\nend \n\n[D, n] = size(a); \n[d, m] = size(b);\nif d ~= D\n error('Error: column lengths must agree.');\nend\n\nif nargin < 3\n C = zeros(n,m);\n for d = 1:D\n C = C + (repmat(b(d,:), n, 1) - repmat(a(d,:)', 1, m)).^2;\n end\n % C = repmat(sum(a.*a)',1,m)+repmat(sum(b.*b),n,1)-2*a'*b could be used to \n % replace the 3 lines above; it would be faster, but numerically less stable.\nelse\n if [n m] == size(Q)\n C = zeros(D,1);\n for d = 1:D\n C(d) = sum(sum((repmat(b(d,:), n, 1) - repmat(a(d,:)', 1, m)).^2.*Q));\n end\n else\n error('Third argument has wrong size.');\n end\nend\n", "meta": {"author": "steven2358", "repo": "kafbox", "sha": "694cf94df02a9728a90d7bacda1a8520b425f86f", "save_path": "github-repos/MATLAB/steven2358-kafbox", "path": "github-repos/MATLAB/steven2358-kafbox/kafbox-694cf94df02a9728a90d7bacda1a8520b425f86f/lib/util/gpml/kafbox_sq_dist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6920132750974943}} {"text": "% Deterministic error model.\n% Demonstrates how the MSE various as the perturbation level increases.\n% Produces figures similar to Fig. 4, 5.\n\n%% Configure\nclear();\n\nwavelength = 1; % normalized\nd_0 = wavelength / 2;\ndesign_set = 'SameAperture'; % can also be 'SameAperture'\ndesigns = get_design_set(design_set, d_0);\n\nn_designs = length(designs);\nif strcmpi(design_set, 'SameNumSensor')\n n_doas = 11;\nelse\n n_doas = 6;\nend\ndoas = linspace(-pi/3, pi/3, n_doas);\n\nn_snapshots = 1000;\nsource_power = 1;\nnoise_power = 1;\n\nperturb_type = 'gaussian';\nn_params_perturb = 20;\nmax_perturb = 0.08*d_0;\nparams_perturb = linspace(0, max_perturb, n_params_perturb);\nn_repeats = 1000;\n\n%% Run\nmse_em = zeros(n_designs, n_params_perturb, n_repeats);\nmse_an = zeros(n_designs, n_params_perturb);\n\nfprintf('Fixed snapshot count, varying pos err std parameters:\\n');\nfprintf(' DOAs: [%s]\\n', num2str(doas, '%f '));\nfprintf(' Number of snapshots: %d\\n', n_snapshots);\nfprintf(' SNR: %.1f\\n', 10*log10(source_power / noise_power));\nfprintf(' Perturbation range: [0 %f]d_0\\n', max_perturb/d_0);\nfprintf(' Repeat: %d\\n', n_repeats);\n\nfor dd = 1:n_designs\n cur_design = designs{dd};\n fprintf('Running simulations for %s:\\n', cur_design.name);\n progressbar('reset', n_params_perturb);\n for kk = 1:n_params_perturb\n % collect empirical results\n cur_mses = zeros(n_repeats, 1);\n perturb_std = params_perturb(kk);\n for rr = 1:n_repeats\n pos_err = gen_pos_err(perturb_std, cur_design.element_count, perturb_type);\n perturbed_design = cur_design;\n perturbed_design.position_errors = pos_err;\n [~, R] = snapshot_gen_sto(perturbed_design, doas, wavelength, n_snapshots, noise_power, source_power);\n [Rv, ~, ~] = virtual_ula_cov_1d(cur_design, R, 'SS');\n sp = rmusic_1d(Rv, n_doas, 2*pi * cur_design.element_spacing / wavelength);\n mse_em(dd,kk,rr) = sum((sp.x_est - doas).^2) / n_doas;\n end\n % compute analytical results\n [~, perturb_cov] = gen_pos_err(params_perturb(kk), cur_design.element_count, perturb_type);\n error_stat = struct;\n error_stat.PositionErrorCov = perturb_cov;\n mse_an(dd, kk) = sum(ecov_perturbed_coarray_music_1d(cur_design, wavelength, ...\n doas, source_power, noise_power, n_snapshots, error_stat, 'DiagonalsOnly')) / n_doas;\n progressbar('advance');\n end\n progressbar('end');\nend\n\n%% Plot\nmarkers = {'x', 'o', 's', 'd', '*', '^', '>', '<', 'h'};\nfigure;\nfor dd = 1:n_designs\n hp = plot(params_perturb/d_0, rad2deg(sqrt(mean(squeeze(mse_em(dd,:,:)), 2))), ...\n ['' markers{mod(dd, length(markers))+1}], ...\n 'DisplayName', [designs{dd}.name ' empirical']);\n hold on;\n plot(params_perturb/d_0, rad2deg(sqrt(mse_an(dd,:))), '--', 'Color', get(hp, 'Color'), ...\n 'DisplayName', [designs{dd}.name ' analytical']);\nend\nhold off;\nxlabel('\\delta_p/d_0');\nylabel('RMSE/deg');\ngrid on;\nlegend('show');\nlegend('Location', 'northwest');\ntitle('RMSE vs Perturbation Level - Deterministic Error Model');\n", "meta": {"author": "morriswmz", "repo": "doa-tools", "sha": "76c1cb7f365615d719fbb050c7ea52b616a28c33", "save_path": "github-repos/MATLAB/morriswmz-doa-tools", "path": "github-repos/MATLAB/morriswmz-doa-tools/doa-tools-76c1cb7f365615d719fbb050c7ea52b616a28c33/examples/experiments/location_errors/sim_error_analysis_det_perturb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6920132703298424}} {"text": "% ir_mri_partial_fourier_3d_test2.m\n% test 2D partial Fourier MRI method ir_mri_partial_fourier_3d.m\n% to examine behavior of xu:01:pfi\n% 2014-06-? Mai Le\n% 2014-06-22 JF mods\n\n%% --- Parameters that control recon quality\n\npercentage = 0.65; % partial k-space fraction, must be greater than 0.5\n\nwindow_step3 = 12; % controls transition band width for apodization\nwindow_step8 = 6;\n\n\n%% --- Chose test case\n\nnz = 1;\n% uncomment line below to test 3D\n% even number just big enough to pass condition in PF_3D that requires apodization area of 16:\n%nz = 2*ceil((2*max(window_step3,window_step8)+1) / (2*(percentage - 0.5)) / 2);\n\n% Shepp-Logan\n%xtrue = phantom('Modified Shepp-Logan');\nif nz > 1\n\txtrue = ellipse_im(64); % need even dims\n\txtrue = xtrue(5:64,:); % stress test non-square\n\txtrue = repmat(xtrue, [1 1 nz]);\nim(xtrue) % fails in octave - todo try in matlab\nreturn\n\txtrue(:,:,1) = zeros(size(xtrue(:,:,1))); xtrue(10, 50) = 1; % impulse\nelse\n\txtrue = ellipse_im(128);\n\txtrue = xtrue(5:124,:); % stress test non-square\n%\txtrue = zeros(size(xtrue)); xtrue(10, 80) = 1; % impulse\nend\n[nx ny nz] = size(xtrue)\n\n% make it complex\nxtrue = xtrue .* exp(-1i*0.05); % constant phase - simple case\nxtrue = xtrue .* exp(-1i*2*pi*(([1:nx]'*[1:ny])/(nx*ny)).^2); % nonlinear phase\n\n% Tough Case\n%xtrue = 1 + rand(nx, ny, nz) .* exp(1i*0.05); % not quite constant phase :(\n\nkspace = fftshift(fftn(xtrue));\n\nif 0 % Artificial k-space for visualizing effect of algo\n\tkspace = rand(size(xtrue));\n\txtrue = ifftn(ifftshift(k));\nend\n\n\n%% --- Select partial k-space and do PF recon\n\npf_location = [1 0 0]; % stress test\nnx_pf = round(percentage*nx);\nny_pf = round(percentage*ny);\nnz_pf = round(percentage*nz);\nkx = (1:nx_pf) + pf_location(1) * (nx - nx_pf);\nky = (1:ny_pf) + pf_location(2) * (ny - ny_pf);\nkz = (1:nz_pf) + pf_location(3) * (nz - nz_pf);\n\nsampling = false(size(xtrue));\nsampling(kx, ky, kz) = true;\n% partial_kspace = sampling .* k;\npartial_kspace = kspace(kx, ky, kz);\n\n% log scale over 6 digits (single precision)\nim_log = @(i, x, t) ...\n\tim(i, log10(abs(x) / max(abs(kspace(:))) + 1e-20), [-6 0], t);\n\nir_fontsize im_axes 5\nir_fontsize title 10\nir_fontsize label 10\nim plc 3 5\nim(1, abs(xtrue), 'true'), cbar\nim(2, sampling), cbar\ntmp = @(k, n) unique([1 n minmax(k)']);\nxtick(tmp(kx, nx))\nytick(tmp(ky, ny))\nim_log(6, kspace, 'full k-space'), cbar\nim_log(7, embed(partial_kspace(:), sampling), 'partial'), cbar\n\nif nz > 1\n\tfull_dims = [nx ny nz];\nelse\n\tfull_dims = [nx ny];\nend\n\nif ~isvar('img_est')\n\t[img_est, full_kspace] = ir_mri_partial_fourier_3d(...\n\t\tpartial_kspace, full_dims, 'pf_location', pf_location, ...\n\t\t'chat', 1, 'show', 1, 'niter', 10, ...\n\t\t'window_step3', window_step3, 'window_step8', window_step8);\n%\t\t'init', xtrue, ... % of course it works\nend\n\nim(5, abs(img_est)), title '|img_est|', cbar\nim(10, angle(img_est)), title '\\angle < img_est', cbar\n\ndiff_img = img_est - xtrue;\n%im(9, abs(img), '|Recon|'), cbar\nim(11, abs(diff_img), 'Error'), cbar\nxlabelf('max = %.3g', max(abs(diff_img(:))))\nim_log(15, full_kspace, 'kspace est'), cbar\nim_log(12, full_kspace - kspace, 'kspace err'), cbar\n\nif 0\n\tim plc 1 1\n\tim_log(1, full_kspace - kspace, 'kspace err')\nend\n\n%im_log(11, full_kspace, 'estimated')\n\n% conclusions:\n% - perfect recovery not possible\n% - missing corners of k-space filled in by convolution of fft of phase difference between current iterate and low frequency estimate\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/mri/ir_mri_partial_fourier_3d_test2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.6919649176083432}} {"text": "function xList=RungeKSteps(xInit,t0,f,deltaT,numSteps,order,solutionChoice,onlyEnd)\n%%RUNGEKSTEPS Perform multiple steps of Runge-Kutta propagation with a\n% fixed time interval between steps.\n%\n%INPUTS: xInit The xDimX1 initial value of the state (scalar or vector)\n% over which integration is being performed.\n% t0 The scalar time at which xInit is taken.\n% f f(xVal,curT) returns the derivative of xVal taken at time\n% curT.\n% deltaT The scalar size of the steps in the Runge-Kutta integration.\n% numSteps The scalar number of steps over which Runge-Kutta\n% integration is performed.\n% order The order of the Runge-Kutta method. If this parameter is\n% omitted, then the default order of 4 is used. Order can\n% range from 1 to 7.\n% solutionChoice When multiple formulae are implemented, this selects which\n% one to use. Otherwise, this parameter is not used.\n% Currently, only the order=4 method has multiple solutions\n% implemented in which case omitting this parameter or setting\n% it to zero used the Dormand and Prince Algorithm, and\n% setting it to 1 uses the Fehlberg algorithm.\n% onlyEnd If this is true, only the value of x at the final step is\n% returned, not any of the intermediate values. The default if\n% this is omitted or an empty matrix is passed is false.\n%\n%OUTPUTS: xList If onlyEnd is false, then this is the xDimX(numSteps+1 The\n% first column of xList is xInit. The subsequent columns\n% are the state propagated forward at intervals of deltaT.\n% Otherwise, if onlyEnd is true, then only the final\n% propagated value is returned and not any of the\n% intermediate steps.\n%\n%This function calls the RungeKStep function to propagate forward the\n%target state each step of duration deltaT. See the comments in RungeKStep\n%for more information.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n \n if(nargin<8||isempty(onlyEnd))\n onlyEnd=false; \n end\n\n if(nargin<7||isempty(solutionChoice))\n solutionChoice=0;\n end\n \n if(nargin<6||isempty(order))\n order=4;\n end\n\n if(onlyEnd)\n xList=xInit;\n curT=t0;\n for curStep=1:numSteps \n xList=RungeKStep(xList,curT,f,deltaT,[],order,solutionChoice);\n curT=curT+deltaT;\n end\n else%If all of the steps are desired.\n xDim=size(xInit,1);\n xList=zeros(xDim,numSteps+1);\n xList(:,1)=xInit;\n\n curT=t0;\n for curStep=1:numSteps \n xList(:,curStep+1)=RungeKStep(xList(:,curStep),curT,f,deltaT,[],order,solutionChoice);\n curT=curT+deltaT;\n end\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/Differential_Equations/RungeKSteps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.8615382040983516, "lm_q1q2_score": 0.6919649019742165}} {"text": "function R=quat2RotMat(q,handed)\n%%QUAT2ROTMAT Turn a unit quaternion into an equivalent rotation matrix.\n% The multiplication rules for the quaternion algebra can be\n% chosen to support standard right-handed quaternion rotation,\n% or non-standard left-handed rotations that some authors use.\n%\n%INPUTS: q A 4X1 unit quaternion corresponding to the rotation matrix. The\n% quaternion is ordered [cos(theta/2);sin(theta/2)u'] where u is a\n% unit vector for the axis of rotation and theta is the rotation\n% angle about that unit vector according to the specified\n% handedness. The ordering of the elements corresponds to the\n% hypercomplex decomposition q(1)+i*q(2)+j*q(3)+k*q(4), where i,\n% j, and k are all roots of -1.\n% handed The handedness of the quaternion. If omitted, it is assumed that\n% the quaternion is right-handed (the standard). Possible values\n% are:\n% 'right' The default if omitted. The quaternion multiplication is\n% assumed right-handed (standard).\n% 'left' The quaternion multiplication is assumed left-handed.\n% This is used in someplaces, including the reference from\n% Shuster, below.\n%\n%OUTPUTS: R A 3X3 orthonormal rotation matrix.\n%\n%If q does not have unit magnitude, then R will not be a rotation matrix.\n%\n%The formula for turning a quaternion into a left-handed rotation matrix is\n%given in [1]. However, right-handed quaternion algebra, as used in [2] is\n%far more common.\n%\n%A quaternion form q(1)+i*q(2)+j*q(3)+k*q(4) that obeys right-handed\n%multiplication rules supports the following rules for multiplication of i,\n%j, and k, where an item in a row is multiplied by an item in the column to\n%get the result:\n% i, j, k\n%i -1, k,-j\n%j -k,-1, i\n%k j,-i,-1\n%On the other hand, left-handed multiplication rules flip the signs of the\n%off-diagonal terms:\n% i, j, k\n%i -1,-k, j\n%j k,-1,-i\n%k -j, i,-1\n%\n%REFERENCES:\n%[1] M. D. Shuster, \"A survey of attitude representations,\" The Journal of\n% Astronautical Sciences, vol. 41, no. 4, pp. 439-517, Oct. -Dec. 1993.\n%[2] Weisstein, Eric W. \"Quaternion.\" From MathWorld--A Wolfram Web\n% Resource. http://mathworld.wolfram.com/Quaternion.html\n%\n%August 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(handed))\n handed='right';\nend\n\nswitch(handed)\n case 'left'\n %The rotation matrix for a left-handed quaternion algebra, as in\n %[1].\n R=[q(1)^2+q(2)^2-q(3)^2-q(4)^2, 2*(q(2)*q(3)+q(1)*q(4)), 2*(q(2)*q(4)-q(1)*q(3));\n 2*(q(2)*q(3)-q(1)*q(4)), q(1)^2-q(2)^2+q(3)^2-q(4)^2,2*(q(3)*q(4)+q(1)*q(2));\n 2*(q(2)*q(4)+q(1)*q(3)), 2*(q(3)*q(4)-q(1)*q(2)), q(1)^2-q(2)^2-q(3)^2+q(4)^2];\n case 'right'\n %The rotation matrix for a right-handed quaternion algebra is the\n %transpose of the matrix from [1].\n R=[q(1)^2+q(2)^2-q(3)^2-q(4)^2, 2*(q(2)*q(3)-q(1)*q(4)), 2*(q(2)*q(4)+q(1)*q(3));\n 2*(q(2)*q(3)+q(1)*q(4)), q(1)^2-q(2)^2+q(3)^2-q(4)^2,2*(q(3)*q(4)-q(1)*q(2));\n 2*(q(2)*q(4)-q(1)*q(3)), 2*(q(3)*q(4)+q(1)*q(2)), q(1)^2-q(2)^2-q(3)^2+q(4)^2];\n otherwise\n error('Invalid handedness provided.')\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/Coordinate_Systems/Rotations/quat2RotMat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755218, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6919426340967222}} {"text": "function gamblers_ruin_plot ( a_stakes, b_stakes )\n\n%*****************************************************************************80\n%\n%% GAMBLERS_RUIN_PLOT plots a game of gambler's ruin.\n%\n% Discussion:\n%\n% Two players, A and B, repeatedly toss a coin. \n% For heads, A wins one dollar from B;\n% For tails, B wins one dollar from A.\n% Play continues until one player is bankrupt.\n%\n% The program simulates the game, and then produces a plot of the\n% amount of money that A has at each stage of the game. At the end,\n% A must have either nothing or all the money.\n%\n% The program produces a plot of A's money. It also displays the\n% initial stakes, the number of steps, and the number of times the\n% lead changed.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 November 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer A_STAKES, B_STAKES, the number of dollars that A and\n% B have initially.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GAMBLERS_RUIN_PLOT\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n\n step_num = 0;\n leader = '0';\n flip_num = -1;\n a = a_stakes;\n b = b_stakes;\n value(1) = a;\n\n while ( 0 < a & 0 < b )\n\n step_num = step_num + 1;\n\n r = rand ( );\n\n if ( r <= 0.5 )\n a = a + 1;\n b = b - 1;\n else\n a = a - 1;\n b = b + 1;\n end\n\n fprintf ( 1, ' %d %d\\n', a, b );\n value(step_num+1) = a;\n\n if ( a_stakes < a & leader ~= 'A' )\n leader = 'A';\n flip_num = flip_num + 1;\n elseif ( a < a_stakes & leader ~= 'B' )\n leader = 'B';\n flip_num = flip_num + 1;\n end\n\n end\n%\n% Plot the results.\n%\n clf\n hold on\n plot ( [ 0, step_num], [ a_stakes, a_stakes ], 'r-', 'LineWidth', 2 );\n plot ( [ 0, step_num], [ 0, 0 ], 'r-', 'LineWidth', 2 );\n plot ( [ 0, step_num], [ a_stakes + b_stakes, a_stakes + b_stakes ], 'r-', 'LineWidth', 2 );\n\n steps = 0 : step_num;\n plot ( steps, value, 'b-', 'LineWidth', 2 );\n\n title_string = sprintf ( 'Gambler''s Ruin - A = %d, B = %d, Steps = %d, Flips = %d', ...\n a_stakes, b_stakes, step_num, flip_num );\n\n title ( title_string );\n xlabel ( 'Coin Tosses' )\n ylabel ( 'A''s Money' );\n axis tight\n\n hold off\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/gamblers_ruin_simulation/gamblers_ruin_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.8933094131553264, "lm_q1q2_score": 0.6919426283482344}} {"text": "function [xMin,fMin,exitCode]=quasiNetwonBFGS(f,x0,D0,epsilon,deltaTestDist,delta,lineSearchParams,scaleD,maxIter)\n%%QUASINEWTONBFGS Perform unconstrained nonlinear optimization using the\n% Broyden-Fletcher-Goldfarb-Shanno (BFGS) algorithm. The\n% algorithm performs unconstrained minimization of a\n% nonlinear function without one having to provide a\n% Hessian matrix. Note that if a minimization over a\n% least-squares problem is desired, then the\n% Levenberg-Marquardt algorithm in LSEstLMarquardt is\n% often preferable. The limited memory version of thie\n% algorithm, quasiNewtonLBFGS, is more appropriate for use\n% with very large matrices. The L-BFGS algorithm also\n% supports an additional L1 norm term in the objective\n% function. If one wishes to zero a vector (not a scalar),\n% then NewtonsMethod is more appropriate as this function\n% assumes the Hessian matrix is symmetric.\n%\n%INPUTS: f A handle to the function (and its gradient) over which the\n% minimization is to be performed. The function [fVal,gVal]=f(x)\n% takes the NX1 x vector and returns the real scalar function\n% value fVal and gradient gVal at the point x.\n% x0 The NX1-dimensional point from which the minimization starts.\n% D0 An estimate of the inverse Hessian matrix at x0. If omitted or\n% an empty matrix is passed, then the identity matrix is used.\n% epsilon The parameter determining the accuracy of the desired solution\n% in terms of the gradient. The function terminates when\n% norm(g) < epsilon*max([1, norm(x)])\n% where g is the gradient. The default if omitted or an empty\n% matrix is passed is 1e-6.\n% deltaTestDist The number of iterations back to use to compute the\n% decrease of the objective function if a delta-based convergence\n% test is performed. If zero, then no delta-based convergence\n% testing is done. The default if omitted or an empty matrix is\n% passed is zero.\n% delta The delta for the delta convergence test. This determines the\n% minimum rate of decrease of the objective function. Convergence\n% is determined if (f'-f)<=delta*f, where f' is the value of the\n% objective function f deltaTestDist iterations ago,and f is the\n% current objective function value. The default if this parameter\n% is omitted or an empty matrix is passed is 0.\n% lineSearchParams An optional structure whose members specify tolerances\n% for the line search. The parameters are described as in the\n% lineSearch function.\n% scaleD A boolean parameter indicating whether the inverse Hessian\n% estimate should be scaled as in Equation 1.201 of Section 1.7 of\n% [1]. The default if omitted or an empty matrix is passed is\n% false.\n% maxIter The maximum number of iterations to use for the overall BFGS\n% algorithm. The default if this parameter is omitted or an empty\n% matrix is passed is 1000.\n%\n%OUTPUTS: xMin The value of x at the minimum point found. If exitCode is\n% negative, then this might be an empty matrix.\n% fMin The cost function value at the minimum point found. If\n% exitCode is negative, then this might be an empty\n% matrix.\n% exitCode A value indicating the termination condition of the\n% algorithm. Nonnegative values indicate success; negative\n% values indicate some type of failure. Possible values are:\n% 0 The algorithm termiated successfully based on the\n% gradient criterion.\n% 1 The algorithm terminated successfully based on the\n% accuracy criterion.\n% -1 The maximum number of overall iterations was reached.\n% Other negative values correspond to a failure in lineSearch\n% and correspond to the exitCode returned by the lineSearch\n% function. \n%\n%The algorithm is implemented based on the description in Chapter 1.7 of\n%[1] with the function lineSearch used to perform the line search.\n%\n%EXAMPLE 1:\n%The first example is that used in the lineSearch file. \n% f=@(x)deal((x(1)+x(2)-3)*(x(1)+x(2))^3*(x(1)+x(2)-6)^4,... %The function\n% [(-6+x(1)+x(2))^3*(x(1)+x(2))^2*(54+8*x(1)^2+x(2)*(-45+8*x(2))+x(1)*(-45+16*x(2)));\n% (-6+x(1)+x(2))^3*(x(1)+x(2))^2*(54+8*x(1)^2+x(2)*(-45+8*x(2))+x(1)*(-45+16*x(2)))]);%And the gradient as the second return.\n% %Note that the deal function is used to make an anonymous function have\n% %two outputs.\n% x0=[0.5;0.25];\n% [xMin,fMin,exitCode]=quasiNetwonBFGS(f,x0)\n%The optimum point found is such that sum(xMin) is approximately\n%1.73539450 with a minimum function value of approximately -2.1860756.\n%\n%EXAMPLE 2:\n%The second example requires that the cost function be placed in a separate\n%file. The cost function is\n% function [fx,g]=objFun(x)\n% n=length(x);\n% fx=0;\n% \n% g=zeros(n,1);\n% for i=0:(n-1)\n% if(mod(i,2)==1)\n% continue;\n% end\n% t1=1-x(i+1);\n% t2=10*(x(i+1+1)-x(i+1)^2);\n% g(i+1+1)=20*t2;\n% g(i+1)=-2*(x(i+1)*g(i+1+1)+t1);\n% fx =fx+t1^2+t2^2;\n% end\n% end\n%It is used as\n% n=100;\n% x0=zeros(n,1);\n% for i=0:(n-1)\n% if(mod(i,2)==1)\n% continue;\n% end\n%\n% x0(i+1)=-1.2;\n% x0(i+1+1)=1;\n% end\n% f=@(x)objFun(x);\n% [xMin,fMin,exitCode]=quasiNetwonBFGS(f,x0)\n%whereby the optimal solution is all ones with a minimum function value of\n%zero. This second example is the same as that provided with the L-BFGS\n%library in C.\n%\n%REFERENCES:\n%[1] D. P. Bertsekas, Nonlinear Programming, 2nd ed. Belmont, MA: Athena\n% Science, 1999.\n%\n%July 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nxDim=size(x0,1);\nif(nargin<3||isempty(D0))\n D=eye(xDim,xDim);\nelse\n D=D0;\nend\n\nif(nargin<4||isempty(epsilon))\n epsilon=1e-6;\nend\n\nif(nargin<5||isempty(deltaTestDist))\n deltaTestDist=0;\nend\n\nif(nargin<6||isempty(delta))\n delta=0;\nend\n\nif(nargin<7)\n lineSearchParams=[];\nend\n\nif(nargin<8||isempty(scaleD))\n scaleD=false; \nend\n\nif(nargin<9||isempty(maxIter))\n maxIter=1000; \nend\n\nxPrev=x0;\n[fValPrev,gradFPrev]=f(x0);\n\nif(deltaTestDist>0)\n pastFVals=zeros(deltaTestDist,1);\n pastFVals(1)=fValPrev;\nend\nfor curIter=1:maxIter\n %Equation 1.181 for the descent direction.\n d=-D*gradFPrev;\n \n %Perform a line search in the given descent direction.\n [xCur,fValCur,gradFCur,~,~,exitCode]=lineSearch(f,xPrev,d,[],[],lineSearchParams);\n\n if(isempty(xCur))\n xMin=[];\n fMin=[];\n return;\n end\n \n %Check for convergence based on the gradient.\n if(norm(gradFCur)max(realmin,max(eps(p),eps(q))))\n if(scaleD==true)\n %If D should be scaled as in Equation 1.201. As noted, this can improve\n %the condition number of D and is often recommended after the first\n %iteration.\n D=(p'*q/(q'*D*q))*D;\n end\n\n %The BFGS update from Problem 1.7.2 with the correction from the errata\n %for the denominator of the p*p' term. \n D=D+(1+q'*D*q/(p'*q))*(p*p')/(p'*q)-(D*q*p'+p*q'*D)/(p'*q);\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/Continuous_Optimization/quasiNetwonBFGS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6919426274963631}} {"text": "m = find(tm(:,22)<0);\navr = sum(tm(:,22))/size(m,1);\nvar1 = (tm(:,22)-avr).^2;\nvar = sum(var1)/size(m,1);\nstdev = var.^(1/2);\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/fractal/easystat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6919426272481747}} {"text": "function [W, p, t] = build8(im, angles)\nt_s = toc;\n%Pad image\n[im_pad,D] = impad(im,'diag',0);\nsz = size(im);\nm = sz(1); %rows\nn = sz(2); %cols\nn_proj = length(angles);\nN = m*n; %number of unknown variables\nM = D*n_proj; %number of equations\n%Weighting Factor Matrix\ntry\n W = zeros(M,N);\ncatch expr\n fprintf([expr.message '\\nGenerates a sparse.\\r'])\n W = sparse(M,N);\nend\n%proj_info = zeros(M,2); %[theta No.]\np = zeros(M,1); %projection vector\nix = false(M,1);\nrc = [m;n]/2+0.5;\nfprintf('Building Weight Matrix...\\r')\n[x,y] = ind2sub(sz,1:N);\n%xy = [x;y]; %x,y coordinate\n%x,y coordinate with respect to rotation center\nxy_c = [x;y]-repmat(rc,1,N);\nd = 1; %side length of square\nA0 = d^2;\nH = @heaviside;\ntry\n A = zeros(D,N);\ncatch expr\n fprintf(['Building A...\\n' ...\n expr.message '\\nGenerating a sparse...\\r'])\n A = sparse(D,N);\nend\nfor kp = 1:n_proj\n A(:) = 0; %#\n im_rot = imrotate(im_pad,-angles(kp),'bilinear','crop');\n pvec = sum(im_rot,1);\n t = -angles(kp)/180*pi;\n R = [cos(t) -sin(t);sin(t) cos(t)];\n fprintf('\\nAngle No.%d(%d Degree)\\r',kp,angles(kp))\n xy_rot = R*xy_c+D/2+0.5;\n idx = round(xy_rot(2,:));\n ixM = D*(kp-1)+idx; %corresponding indice in W and p matrix\n %Calculate Area\n x1 = d*min(abs([sin(t) cos(t)]))+eps;\n x2 = d*max(abs([sin(t) cos(t)]))-eps;\n l = x1+x2;\n h = d^2/x2;\n %A0 = d^2;\n A1 = x1*h/2;\n G1 = @(x) H(x)-H(x-x1);\n G2 = @(x) H(x-x1)-H(x-x2);\n G3 = @(x) H(x-x2)-H(x-l);\n f_A = @(x) (x/x1).^2*A1.*G1(x)+...\n (A1+h*(x-x1)).*G2(x)+...\n (A0-((l-x)/x1).^2.*A1).*G3(x)+...\n A0*H(x-l);\n x0 = xy_rot(2,:)-l/2;\n S1 = f_A((idx-0.5)-x0)/A0;\n S2 = f_A((idx+0.5)-x0)/A0;\n for kn = 1:N\n if idx(kn)-1 >= 1\n A(idx(kn)-1,kn) = S1(kn);\n end\n A(idx(kn) ,kn) = S2(kn)-S1(kn);\n if idx(kn)+1 <= D\n A(idx(kn)+1,kn) = 1-S2(kn);\n end\n p(ixM(kn)) = pvec(idx(kn));\n ix(ixM(kn)) = true;\n end\n W((D*(kp-1)+(1:D)),:) = A; %#\nend\n% %\n%Delete all-zero rows in W\nfprintf('\\nDelete all-zero rows in W...\\r')\n%ix = sum(W,2)==0;\ntry\n W(~ix,:) = [];\ncatch expr\n fprintf([expr.message '\\nConverting to sparse...\\r'])\n W = sparse(W);\n W(~ix,:) = [];\nend\np(~ix) = [];\nn_eq = size(W,1);\nfprintf('\\nFinish building A. \\n%d equations in total.\\r',n_eq);\nfigure('name','Sparsity pattern of matrix W');\nspy(W)\nt_e = toc;\nt = t_e-t_s;\nfprintf('\\nTotal: %f seconds\\n\\r',t);\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/43008-tomotools/tomotool/build8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6919426269999857}} {"text": "function c = tapas_hgf_categorical_norm_config\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Contains the configuration for the Hierarchical Gaussian Filter (HGF) for categorical inputs\n% restricted to 3 levels, no drift, and no inputs at irregular intervals, in the absence of\n% perceptual uncertainty.\n%\n% This model deals with the situation where an agent has to determine the probability of categorical\n% outcomes. The tendencies of these outcomes are modeled as independent Gaussian random processes at\n% the second level of the HGF. They are transformed into predictive probabilities at the first level\n% by a softmax function (i.e., a logistic sigmoid). This amounts to the assumption that the\n% probabilities are performing a Gaussian random walk in logit space. The volatility of all of\n% these walks is determined by the same higher-level state x_3 in standard HGF fashion.\n%\n% The HGF is the model introduced in \n%\n% Mathys C, Daunizeau J, Friston, KJ, & Stephan KE. (2011). A Bayesian foundation for individual\n% learning under uncertainty. Frontiers in Human Neuroscience, 5:39.\n%\n% and elaborated in\n%\n% Mathys, C, Lomakina, EI, Daunizeau, J, Iglesias, S, Brodersen, KH, Friston, KJ, & Stephan, KE\n% (2014). Uncertainty in perception and the Hierarchical Gaussian Filter. Frontiers in Human\n% Neuroscience, 8:825.\n%\n% This file refers to CATEGORICAL inputs (Eqs 1-3 in Mathys et al., (2011)); for continuous inputs,\n% refer to tapas_hgf_config.m, for binary inputs, refer to tapas_hgf_binary.m\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% The HGF configuration consists of the priors of parameters and initial values. All priors are\n% Gaussian in the space where the quantity they refer to is estimated. They are specified by their\n% sufficient statistics: mean and variance (NOT standard deviation).\n% \n% Quantities are estimated in their native space if they are unbounded (e.g., omega). They are\n% estimated in log-space if they have a natural lower bound at zero (e.g., sigma2).\n% \n% Kappa and theta are estimated in 'logit-space' because bounding them above (in addition to\n% their natural lower bound at zero) is an effective means of preventing the exploration of\n% parameter regions where the assumptions underlying the variational inversion (cf. Mathys et\n% al., 2011) no longer hold.\n% \n% 'Logit-space' is a logistic sigmoid transformation of native space with a variable upper bound\n% a>0:\n% \n% logit(x) = ln(x/(a-x)); x = a/(1+exp(-logit(x)))\n%\n% Parameters can be fixed (i.e., set to a fixed value) by setting the variance of their prior to\n% zero. Aside from being useful for model comparison, the need for this arises whenever the scale\n% and origin of x3 are arbitrary. This is the case if the observation model does not contain the\n% representations mu3 and sigma3 from the third level. A choice of scale and origin is then\n% implied by fixing the initial value mu3_0 of mu3 and either kappa or omega.\n%\n% Kappa and theta can be fixed to an arbitrary value by setting the upper bound to twice that\n% value and the mean as well as the variance of the prior to zero (this follows immediately from\n% the logit transform above).\n% \n% Fitted trajectories can be plotted by using the command\n%\n% >> tapas_hgf_categorical_plotTraj(est)\n% \n% where est is the stucture returned by fitModel. This structure contains the estimated\n% perceptual parameters in est.p_prc and the estimated trajectories of the agent's\n% representations (cf. Mathys et al., 2011). Their meanings are:\n% \n% est.p_prc.mu2_0 initial values of the mu2s\n% est.p_prc.sa2_0 initial values of the sigma2s\n% est.p_prc.mu3_0 initial value of mu3\n% est.p_prc.sa3_0 initial value of sigma3\n% est.p_prc.ka kappa\n% est.p_prc.om omega\n% est.p_prc.th theta\n%\n% est.traj.mu mu\n% est.traj.sa sigma\n% est.traj.muhat prediction mean\n% est.traj.sahat prediction variance\n% est.traj.v inferred variances of random walks\n% est.traj.w weighting factor of informational and environmental uncertainty at the 2nd level\n% est.traj.da prediction errors\n% est.traj.ud updates with respect to prediction\n% est.traj.psi precision weights on prediction errors\n% est.traj.epsi precision-weighted prediction errors\n% est.traj.wt full weights on prediction errors (at the first level,\n% this is the learning rate)\n%\n% Tips:\n% - When analyzing a new dataset, take your inputs u and use\n%\n% >> est = tapas_fitModel([], u, 'tapas_hgf_categorical_config', 'tapas_bayes_optimal_categorical_config');\n%\n% to determine the Bayes optimal perceptual parameters (given your current priors as defined in\n% this file here, so choose them wide and loose to let the inputs influence the result). You can\n% then use the optimal parameters as your new prior means for the perceptual parameters.\n%\n% - If you get an error saying that the prior means are in a region where model assumptions are\n% violated, lower the prior means of the omegas, starting with the highest level and proceeding\n% downwards.\n%\n% - Alternatives are lowering the prior mean of kappa, if they are not fixed, or adjusting\n% the values of the kappas or omegas, if any of them are fixed.\n%\n% - If the log-model evidence cannot be calculated because the Hessian poses problems, look at\n% est.optim.H and fix the parameters that lead to NaNs.\n%\n% - Your guide to all these adjustments is the log-model evidence (LME). Whenever the LME increases\n% by at least 3 across datasets, the adjustment was a good idea and can be justified by just this:\n% the LME increased, so you had a better model.\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2013-2014 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n\n% Config structure\nc = struct;\n\n% Model name\nc.model = 'hgf_categorical';\n\n% Number of states\nc.n_outcomes = 3;\n\n% Upper bound for kappa and theta (lower bound is always zero)\nc.kaub = 2;\nc.thub = 0.1;\n\n% Sufficient statistics of Gaussian parameter priors\n\n% Initial mu2\nc.mu2_0mu = repmat(tapas_logit(1/c.n_outcomes,1),1,c.n_outcomes);\nc.mu2_0sa = zeros(1,c.n_outcomes);\n\n% Initial sigma2\nc.logsa2_0mu = repmat(log(1),1,c.n_outcomes);\nc.logsa2_0sa = zeros(1,c.n_outcomes);\n\n% Initial mu3\n% Usually best kept fixed to 1 (determines origin on x3-scale).\nc.mu3_0mu = 1;\nc.mu3_0sa = 0;\n\n% Initial sigma3\nc.logsa3_0mu = log(0.1);\nc.logsa3_0sa = 1;\n\n% Kappa\n% This should be fixed (preferably to 1) if the observation model\n% does not use mu3 (kappa then determines the scaling of x3).\nc.logitkamu = 0; % If this is 0, and\nc.logitkasa = 0; % this is 0, and c.kaub = 2 above, then kappa is fixed to 1\n\n% Omega\nc.ommu = -4;\nc.omsa = 5^2;\n\n% Theta\nc.logitthmu = 0;\nc.logitthsa = 2;\n\n\n% Gather prior settings in vectors\nc.priormus = [\n c.mu2_0mu,...\n c.logsa2_0mu,...\n c.mu3_0mu,...\n c.logsa3_0mu,...\n c.logitkamu,...\n c.ommu,...\n c.logitthmu,...\n ];\n\nc.priorsas = [\n c.mu2_0sa,...\n c.logsa2_0sa,...\n c.mu3_0sa,...\n c.logsa3_0sa,...\n c.logitkasa,...\n c.omsa,...\n c.logitthsa,...\n ];\n\n% Model function handle\nc.prc_fun = @tapas_hgf_categorical;\n\n% Handle to function that transforms perceptual parameters to their native space\n% from the space they are estimated in\nc.transp_prc_fun = @tapas_hgf_categorical_transp;\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hgf_categorical_norm_config.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6919426157511985}} {"text": "function [val,idx] = of_RMSE(obs,sim,idx)\n% of_RMSE Calculates the Root Mean Squared Error of simulated streamflow.\n% Ignores time steps with negative flow values.\n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% In:\n% obs - time series of observations [nx1]\n% sim - time series of simulations [nx1]\n% idx - optional vector of indices to use for calculation, can be\n% logical vector [nx1] or numeric vector [mx1], with m <= n\n%\n% Out:\n% val - objective function value [1x1]\n% idx - indices used for the calculation\n\n%% Check inputs and select timesteps\nif nargin < 2\n error('Not enugh input arguments') \nend\n\nif nargin < 3; idx = []; end\n[sim, obs, idx] = check_and_select(sim, obs, idx); \n\n%% Calculate metric\nval = sqrt(mean((obs-sim).^2));\nend\n\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Functions/Objective functions/of_RMSE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6919426135510788}} {"text": "% Ambiguity function\n%\n% Computes the ambiguity function of the input signal. An analytic\n% signal generator is called if the input signal is real. This version\n% takes advantage of the property K(n,-m)=K*(n,m) to increase\n% calculation speed.\n%\n% Usage: \n%\n% af = ambf( signal, lag_res, window_length )\n%\n%\n% Parameters:\n%\n% af\n%\n%\t The computed ambiguity function representation. size(af) will\n%\t return [a, b], where b is the next largest power of two above\n%\t (2*window_length), and a is equal signal length.\n%\n% signal\n%\n%\t Input one dimensional signal to be analysed. An analytic signal\n%\t is required for this function, however, if signal is real, a\n%\t default analytic transformer routine will be called from this\n%\t function before computing the ambiguity function.\n%\n% window_length\n%\n%\t The number of signal samples used for analysis.\n%\n% lag_res\n%\n%\t The number of lag to skip between successive slices of\n%\t the analysis.\n%\n%\n%\n% See Also: analyt\n%\n% TFSAP 7.0\n% Copyright Prof. B. Boashash\n% Qatar University, Doha\n% email: tfsap.research@gmail.com\n\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tfsa_7.0/win64_bin/ambf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.691942611350959}} {"text": "function [um] = pm2um(pm)\n% Convert length from picometers to micrometers (or microns).\n% Chad A. Greene 2012\num = pm*1e-6;", "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/35258-unit-converters/unit_converters/pm2um.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6919426047505993}} {"text": "function [sol, val] = gaDemo1Eval(sol,options)\n% Demonstration evaluation function used in gademo1.\n% f(x)=x+10sin(5x)+7cos(4x)\n%\n% function [val,sol] = gaDemo1Eval(sol,options)\n% \n% val - the fittness of this individual\n% sol - the individual, returned to allow for Lamarckian evolution\n% options - [current_generation]\n\n% Binary and Real-Valued Simulation Evolution for Matlab \n% Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay \n%\n% C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function\n% optimization: A Matlab implementation. ACM Transactions on Mathmatical\n% Software, Submitted 1996.\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 1, or (at your option)\n% 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. A copy of the GNU \n% General Public License can be obtained from the \n% Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\nx=sol(1);\nval = x + 10*sin(5*x)+7*cos(4*x);\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/\u300aMATLAB \u795e\u7ecf\u7f51\u7edc30\u4e2a\u6848\u4f8b\u5206\u6790\u300b\u6e90\u7a0b\u5e8f \u6570\u636e/chapter27/gaot/gademo1eval1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692236, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6919419253161359}} {"text": "function I = gcmi_model_cd(x, y, Ym)\n% GCMI_MODEL_CD Gaussian-Copula Mutual Information between a continuous and a \n% discrete variable in bits based on ANOVA style model comparison.\n% I = gcmi_model_gd(x,y,Ym) returns the MI between the (possibly multidimensional)\n% continuous variable x and the discrete variable y.\n% For 1D x this is a lower bound to the mutual information.\n% Rows of x correspond to samples, columns to dimensions/variables. \n% (Samples first axis)\n% y should contain integer values in the range [0 Ym-1] (inclusive).\n% See also: GCMI_MIXTURE_CD\n\n% ensure samples first axis for vectors\nif isvector(x)\n x = x(:);\nend\nif ndims(x)~=2\n error('gcmi_model_cd: input array should be 2d')\nend\n\nif isvector(y)\n y = y(:);\nelse\n error('gcmi_model_cd: only univariate discrete variable supported');\nend\n\nNtrl = size(x,1);\nNvar = size(x,2);\n\nif size(y,1) ~= Ntrl\n error('gcmi_model_cd: number of trials do not match');\nend\n\n% check for repeated values\nfor xi=1:Nvar\n if length(unique(x(:,xi)))./Ntrl < 0.9\n warning('Input x has more than 10% repeated values.')\n break\n end\nend\n\n% check values of discrete variable\nif min(y)~=0 || max(y)~=(Ym-1) || any(round(y)~=y)\n error('Values of discrete variable y are not correct')\nend\n\n% copula normalisation\ncx = copnorm(x);\n% parametric Gaussian MI\nI = mi_model_gd(cx,y,Ym,true,true);\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/gcmi/gcmi_model_cd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067147399245, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6919125780425038}} {"text": "function fv= proc_rSquare(fv, varargin)\n%PROC_RSQUARE - computes r^2 values (measure for discriminance)\n%\n%Synopsis:\n% \tfv = proc_rSquare(fv, )\n%\n%Returns:\n% FV_RVAL - data structure of squared biserial correlation coefficients \n% .x - squared biserial correlation between each feature and the class label\n% .se - standard error of atanh(r), if opt.Stats==1\n% .p - p value of null hypothesis that there is zero\n% correlation between feature and class-label, if opt.Stats==1\n% .sgnlogp - contains the signed log10 p-value, if opt.Stats==1\n% if opt.Bonferroni==1, the p-value is multiplied by\n% fv_rval.corrfac\n% .sgnlogp - contains the signed log10 p-value, if opt.Stats==1\n% if opt.Bonferroni==1, the p-value is multiplied by\n% fv_rval.corrfac, cropped, and then logarithmized\n% .sigmask - binary array indicating significance at alpha level\n% opt.Alphalevel, if opt.Stats==1 and opt.Alphalevel > 0\n% .corrfac - Bonferroni correction factor (number of simultaneous tests), \n% if opt.Bonferroni==1\n%\n%Properties:\n% 'TolerateNans': observations with NaN value are skipped\n% (nanmean/nanstd are used instead of mean/std). Deafult: 0\n% 'ValueForConst': constant feauture dimensions are assigned this\n% value. Default: NaN.\n% 'MulticlassPolicy': possible options: 'pairwise' (default), \n% 'all-against-last', 'each-against-rest', or provide specified\n% pairs as an [nPairs x 2] sized matrix. ('specified_pairs' is obsolete)\n% 'Stats' - if true, additional statistics are calculated, including the\n% standard error of atanh(r), the p-value for the null \n% Hypothesis that the correlation is zero, \n% and the \"signed log p-value\"\n% 'Bonferroni' - if true, Bonferroni corrected is used to adjust p-values\n% and their logarithms\n% 'Alphalevel' - if provided, a binary indicator of the significance to the\n% alpha level is returned for each feature in fv_rval.sigmask\n% \n%Description\n% Computes the r^2 value for each feature. The r^2 value is a measure\n% of how much variance of the joint distribution can be explained by\n% class membership.\n%\n% See also proc_classmeanDiff, proc_rValues, proc_rSquareSigned\n%\n% 03-03 Benjamin Blankertz\n% 09-2012 stefan.haufe@tu-berlin.de\n\nif nargin==0,\n fv=proc_rValues; return\nend\n\nfv= proc_rValues(fv, varargin{:});\nfv.x= fv.x.^2;\nfor cc= 1:length(fv.className),\n fv.className{cc}= ['r^2' fv.className{cc}(2:end)];\nend\nfv.yUnit= 'r^2';\n\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/processing/proc_rSquare.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6919043850070049}} {"text": "function triangle01_monomial_integral_test ( )\n\n%*****************************************************************************80\n%\n%% TRIANGLE01_MONOMIAL_INTEGRAL_TEST estimates integrals over the unit triangle.\n%\n% Location:\n%\n% http://people.sc.fsu.edu/~jburkardt/m_src/triangle_integrals/triangle01_monomial_integral_test.m\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 April 2015\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGLE01_MONOMIAL_INTEGRAL_TEST\\n' );\n fprintf ( 1, ' TRIANGLE01_MONOMIAL_INTEGRAL returns the integral Q of\\n' );\n fprintf ( 1, ' a monomial X^I Y^J over the interior of the unit triangle.\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I J Q(I,J)\\n' );\n\n for d = 0 : 5\n fprintf ( 1, '\\n' );\n for i = 0 : d\n j = d - i;\n q = triangle01_monomial_integral ( i, j );\n fprintf ( 1, ' %2d %2d %14.6g\\n', i, j, q );\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/triangle_integrals/triangle01_monomial_integral_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.6919039652237471}} {"text": "% Usage [L, inliers] = ransacfitline(XYZ, t, feedback)\n%\n% Arguments:\n% XYZ - 3xNpts array of xyz coordinates to fit line to.\n% t - The distance threshold between data point and the line\n% used to decide whether a point is an inlier or not.\n% feedback - Optional flag 0 or 1 to turn on RANSAC feedback\n% information.\n%\n% Returns:.\n% V - Line obtained by a simple fitting on the points that\n% are considered inliers. The line goes through the\n% calculated mean of the inlier points, and is parallel to\n% the principal eigenvector. The line is scaled by the\n% square root of the largest eigenvalue.\n% This line is a n*2 matrix. The first column is the\n% beginning point, the second column is the end point of the\n% line.\n% L - The two points in the data set that were found to\n% define a line having the most number of inliers.\n% The two columns of L defining the two points.\n% inliers - The indices of the points that were considered\n% inliers to the fitted line.\n%\n% See also: RANSAC, FITPLANE, RANSACFITPLANE\n\n% Copyright (c) 2003-2006 Peter Kovesi and Felix Duvallet (CMU)\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% Aug 2006 - created ransacfitline from ransacfitplane\n% author: Felix Duvallet\n\nfunction [V, L, inliers] = ransacfitparabola(XY, t, feedback)\n \n if nargin == 2\n\tfeedback = 0;\n end\n \n [rows, npts] = size(XY);\n \n if rows ~= 2\n error('data is not 2D');\n end\n \n if npts < 2\n error('too few points to fit line');\n end\n \n s = 3; % Minimum No of points needed to fit a line.\n \n fittingfn = @defineParabola;\n distfn = @paraptdist;\n degenfn = @isdegenerate;\n\n [L, inliers] = ransac(XY, fittingfn, distfn, degenfn, s, t, feedback);\n \n V = fitparabola(XY(:, inliers));\n \n%------------------------------------------------------------------------\n% Function to define a parabola given 3 data points as required by\n% RANSAC.\n\nfunction L = defineParabola(X)\n L = X;\n%------------------------------------------------------------------------\n% Function to calculate distances between a line and an array of points.\nfunction [inliers, L] = paraptdist(L, X, t)\n p = polyfit( L(1, :), L(2, :), 2 );\n YEst = polyval(p, X(1, :) );\n d = YEst - X(2, :);\n inliers = find(abs(d) < t);\n \n%------------------------------------------------------------------------\n% Function to determine whether a set of 2 points are in a degenerate\n% configuration for fitting a line as required by RANSAC.\n% In this case two points are degenerate if they are the same point\n% or if they are exceedingly close together.\n\nfunction r = isdegenerate(X)\n %find the norm of the difference of the two points\n % this will be 0 iff the two points are the same (the norm of their\n % difference is zero)\n r0 = norm(X(:,1) - X(:,2)) < eps;\n r1 = norm(X(:,1) - X(:,3)) < eps;\n r = r0 | r1;", "meta": {"author": "DrGabor", "repo": "LiDAR", "sha": "707ca635db955cf00d833578ad1236f0790cdf98", "save_path": "github-repos/MATLAB/DrGabor-LiDAR", "path": "github-repos/MATLAB/DrGabor-LiDAR/LiDAR-707ca635db955cf00d833578ad1236f0790cdf98/RoadSegmenter/Ransac/ransacfitparabola.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.6918639065193697}} {"text": "function [leftpt,leftcurve,rightpt,rightcurve]=slicesurf3(node,elem,p1,p2,p3,step,minangle)\n%\n% [leftpt,leftcurve,rightpt,rightcurve]=slicesurf3(node,elem,p1,p2,p3,step,minangle)\n%\n% Slice a closed surface by a plane and extract the landmark nodes along\n% the intersection between p1 and p3, then output into 2 segments: between\n% p2 to p1 (left half), and p2 to p3 (right half)\n%\n% author: Qianqian Fang (q.fang at neu.edu)\n%\n% input:\n% node: an N x 3 array defining the 3-D positions of the mesh\n% elem: an N x 3 interger array specifying the surface triangle indices;\n% p1: 3D position of the start on the curve-of-interest\n% p2: 3D position of the middle on the curve-of-interest\n% p3: 3D position of the end on the curve-of-interest\n% step: (optional) a percentage (0-100) specifying the spacing of the\n% output landmark nodes; step=20 means the landmarks on the left\n% curve are spaced as 20% of the total lengths of the left-half, and\n% those on the right-curve are spaced at 20% of the right-half,\n% starting from p2.\n% minangle: (optional) a positive minangle will ask this function to\n% call polylinesimplify to remove sharp turns on the curve.\n%\n% output:\n% leftpt: the equal-spaced landmark nodes on the left-half (p2-p1)\n% intersection curve; spacing between these nodes are\n% (step% * length of the curve between p2-p1)\n% leftcurve: all nodes on the left-half (p2-p1) intersection curve\n% rightpt: the equal-spaced landmark nodes on the right-half (p2-p3)\n% intersection curve; spacing between these nodes are\n% (step% * length of the curve between p2-p3)\n% rightcurve: all nodes on the left-half (p2-p1) intersection curve\n%\n% -- this function is part of brain2mesh toolbox (http://mcx.space/brain2mesh)\n% License: GPL v3 or later, see LICENSE.txt for details\n%\n\nfullcurve=slicesurf(node, elem, [p1;p2;p3]);\nif(nargin>=7 && minangle>0)\n fullcurve=polylinesimplify(fullcurve,minangle);\nend\n\n[fulllen, fullcurve]=polylinelen(fullcurve, p1,p3,p2);\n\n[leftlen, leftcurve]=polylinelen(fullcurve, p2, p1);\nif(nargin>=6)\n [idx, weight, leftpt]=polylineinterp(leftlen, sum(leftlen)*(step:step:(100-step*0.5))*0.01, leftcurve);\nelse\n leftpt=leftcurve;\nend\n\nif(nargout>2)\n [rightlen, rightcurve]=polylinelen(fullcurve, p2, p3);\n if(nargin>=6)\n [idx, weight, rightpt]=polylineinterp(rightlen, sum(rightlen)*(step:step:(100-step*0.5))*0.01, rightcurve);\n else\n rightpt=rightcurve;\n end\nend\n", "meta": {"author": "fangq", "repo": "iso2mesh", "sha": "556f4c321467a3ee042d4c559b4edc11e01dc574", "save_path": "github-repos/MATLAB/fangq-iso2mesh", "path": "github-repos/MATLAB/fangq-iso2mesh/iso2mesh-556f4c321467a3ee042d4c559b4edc11e01dc574/slicesurf3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.691863903887281}} {"text": "function [count, h, parent, post, L] = symbfact2 (A, mode, Lmode)\t %#ok\n%SYMBFACT2 symbolic factorization\n%\n% Analyzes the Cholesky factorization of A, A'*A, or A*A'.\n%\n% Example:\n% count = symbfact2 (A) returns row counts of R=chol(A)\n% count = symbfact2 (A,'col') returns row counts of R=chol(A'*A)\n% count = symbfact2 (A,'sym') same as symbfact2(A)\n% count = symbfact2 (A,'lo') same as symbfact2(A'), uses tril(A)\n% count = symbfact2 (A,'row') returns row counts of R=chol(A*A')\n%\n% The flop count for a subsequent LL' factorization is sum(count.^2)\n%\n% [count, h, parent, post, R] = symbfact2 (...) returns:\n%\n% h: height of the elimination tree\n% parent: the elimination tree itself\n% post: postordering of the elimination tree\n% R: a 0-1 matrix whose structure is that of chol(A) for the symmetric\n% case, chol(A'*A) for the 'col' case, or chol(A*A') for the\n% 'row' case.\n%\n% symbfact2(A) and symbfact2(A,'sym') uses the upper triangular part of A\n% (triu(A)) and assumes the lower triangular part is the transpose of\n% the upper triangular part. symbfact2(A,'lo') uses tril(A) instead.\n%\n% With one to four output arguments, symbfact2 takes time almost proportional\n% to nnz(A)+n where n is the dimension of R, and memory proportional to\n% nnz(A). Computing the 5th argument takes more time and memory, both\n% O(nnz(L)). Internally, the pattern of L is computed and R=L' is returned.\n%\n% The following forms return L = R' instead of R. They are faster and take\n% less memory than the forms above. They return the same count, h, parent,\n% and post outputs.\n%\n% [count, h, parent, post, L] = symbfact2 (A,'col','L')\n% [count, h, parent, post, L] = symbfact2 (A,'sym','L')\n% [count, h, parent, post, L] = symbfact2 (A,'lo', 'L')\n% [count, h, parent, post, L] = symbfact2 (A,'row','L')\n%\n% See also CHOL, ETREE, TREELAYOUT, SYMBFACT\n\n% Copyright 2006-2007, Timothy A. Davis\n% http://www.cise.ufl.edu/research/sparse\n\nerror ('symbfact2 mexFunction not found!') ;\n\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/SuiteSparse/CHOLMOD/MATLAB/symbfact2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6918638996213013}} {"text": "function S=smoothHeaviside(varargin)\n\nswitch nargin\n case 1\n x=varargin{1};\n k=6;\n r=0;\n case 2\n x=varargin{1};\n k=varargin{2};\n r=0;\n case 3\n x=varargin{1};\n k=varargin{2};\n r=varargin{3};\nend\nk=k*2;\nS=exp(2*k*(x-r))./(1+exp(2*k*(x-r)));\n\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/smoothHeaviside.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220786, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.6918638949928165}} {"text": "function yprime = decay1(t,y)\n%DECAY1 Calculates the decay rates of Thorium 227 and Radium 223.\n% Function DECAY1 Calculates the rates of change of Thorium 227 \n% and Radium 223 (yprime) for a given current concentration y. \n \n% Define variables:\n% t -- Time (in days)\n% y -- Vector of current concentrations\n%\n% Record of revisions:\n% Date Programmer Description of change\n% ==== ========== =====================\n% 03/15/07 S. J. Chapman Original code\n\n% Set decay constants.\nlambda_th = 0.03710636;\nlambda_ra = 0.0606428;\n\n% Calculate rates of decay\nyprime = zeros(2,1);\nyprime(1) = -lambda_th * y(1);\nyprime(2) = -lambda_ra * y(2) + lambda_th * y(1);\n\n", "meta": {"author": "101Hub", "repo": "Matlab101", "sha": "07273f68f1147a110443aeb121fa10962234f298", "save_path": "github-repos/MATLAB/101Hub-Matlab101", "path": "github-repos/MATLAB/101Hub-Matlab101/Matlab101-07273f68f1147a110443aeb121fa10962234f298/assets/\u300aMatlab\u7f16\u7a0b\u300b\u6e90\u7801/chap7/decay1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6918638932223319}} {"text": "% ACWMF algorithm implementation\n%function [y, noise_matrix] = ACWMF(I);\nfunction output = ACWMF(I);\n\n\n% Threshold parameters\n%delta = [40 25 10 5]; %% for uniform impulse noise\ndelta = [55,40,25,15]; %% for salt and pepper noise\n%delta = (delta1+delta2)/2; %% for mixed impulse noise\n\nx = double(I);\nimage_size = size(I);\nB = im2col(padarray(x,[1 1],'symmetric','both'),[3 3],'sliding');\n\n% Compute filter output\nm = medfilt2(x,[3 3],'symmetric');\n\n%Compute differences\nd = abs(x-m);\nd0 = d(:)';\nclear d;\nB(10,:) = x(:)';\nB(11,:) = x(:)';\nm1 = median(B);\nd1 = abs(x(:)'-m1);\nB(12,:) = x(:)';\nB(13,:) = x(:)';\nm1=median(B);\nd2 = abs(x(:)'-m1);\nB(14,:) = x(:)';\nB(15,:) = x(:)';\nm1=median(B);\nd3 = abs(x(:)'-m1);\nclear B;\n\n% Compute MAD values\nB_x = im2col(padarray(x,[1 1],'symmetric','both'),[3 3],'sliding');\n\nfor i = 1:9\n B(i,:) = abs(B_x(i,:) - m(:)');\nend\nMAD = median(B);\n\nclear B;\n\n% Compute threshold values\ns = 0.1;\nT1 = (MAD * s) + delta(1);\nT2 = (MAD * s) + delta(2);\nT3 = (MAD * s) + delta(3);\nT4 = (MAD * s) + delta(4);\n\nx2 = x(:);\n\n% Detect noisy pixels\nF = find((d0>T1)|(d1>T2)|(d2>T3)|(d3>T4));\n\n%noise_matrix = zeros(image_size);\n%noise_matrix(F) = 1;\n\n% Replace noisy pixels\nx2(F) = m(F);\nclear F m d0 d1 d2 d3 T x;\noutput = uint8(col2im(x2,[1 1],image_size,'sliding')); \n \n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u53bb\u566a\u7b97\u6cd5/noise-adaptive-switching-non-local-means-master/NASNLM/ACWMF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6917657858009902}} {"text": "function y = logDirichlet(X, a)\n% Compute log pdf of a Dirichlet distribution.\n% Input:\n% X: d x n data matrix, each column sums to one (sum(X,1)==ones(1,n) && X>=0)\n% a: d x k parameter of Dirichlet\n% y: k x n probability density\n% Output:\n% y: k x n probability density in logrithm scale y=log p(x)\n% Written by Mo Chen (sth4nth@gmail.com).\nX = bsxfun(@times,X,1./sum(X,1));\nif size(a,1) == 1\n a = repmat(a,size(X,1),1);\nend\nc = gammaln(sum(a,1))-sum(gammaln(a),1);\ng = (a-1)'*log(X);\ny = bsxfun(@plus,g,c');\n", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter02/logDirichlet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6917085304357842}} {"text": "% fft_compress.m\n\n% \u4f5c\u7528\uff1a\u4f7f\u7528\u79bb\u6563\u5085\u91cc\u53f6\u53d8\u6362\u5bf9\u8f93\u5165\u7684 JPG \u56fe\u7247 image \u6309\u7167\u6307\u5b9a\u7684\u6ee4\u6ce2\u6bd4\u4f8b ratio \u8fdb\u884c\u538b\u7f29\n% \u8fd4\u56de\u503c\uff1a\u8fd4\u56de\u4f4e\u901a\u6ee4\u6ce2\u4e4b\u540e\u7684\u9891\u7387\u5206\u5e03\u548c\u538b\u7f29\u4e4b\u540e\u7684\u56fe\u7247\nfunction [z, k] = fft_compress(image, ratio)\n\n % \u5bf9\u539f JPG \u56fe\u7247\u5728\u4e09\u4e2a\u989c\u8272\u4e0a\u5206\u522b\u505a\u4e8c\u7ef4\u79bb\u6563\u5085\u91cc\u53f6\u53d8\u6362\uff0c\u5f97\u5230\u9891\u7387\u5206\u5e03\n z(:,:,1) = fft2(image(:,:,1));\n z(:,:,2) = fft2(image(:,:,2));\n z(:,:,3) = fft2(image(:,:,3));\n\n % \u83b7\u53d6\u56fe\u7247\u7684\u5c3a\u5bf8\u5927\u5c0f\n [a, b, ~] = size(image);\n\n % \u4f4e\u901a\u6ee4\u6ce2\n for i = 1 : a\n for j = 1 : b\n if (i + j > (a+b) * ratio)\n z(i, j, 1) = 0;\n z(i, j, 2) = 0;\n z(i, j, 3) = 0;\n end\n end\n end\n\n % \u5bf9\u8fc7\u6ee4\u4e4b\u540e\u7684\u7ed3\u679c\u5728\u4e09\u4e2a\u989c\u8272\u4e0a\u5206\u522b\u505a\u8fdb\u884c\u4e8c\u7ef4\u53cd\u79bb\u6563\u5085\u91cc\u53f6\u53d8\u6362\n k(:,:,1) = ifft2(z(:,:,1));\n k(:,:,2) = ifft2(z(:,:,2));\n k(:,:,3) = ifft2(z(:,:,3));\n\n % \u7c7b\u578b\u8f6c\u6362\uff0c\u8f6c\u6362\u4e3a 0-255 \u8303\u56f4\u5185\u7684\u989c\u8272\u503c\n k = uint8(k);\nend", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/study/linear_algebra/fft_compress.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6917085284978096}} {"text": "function [in2] = mm22in2(mm2)\n% Convert area from square millimeters to square inches.\n% Chad A. Greene 2012\nin2 = mm2*0.001550003100006;", "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/35258-unit-converters/unit_converters/mm22in2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6917085226838855}} {"text": "%% Checking Solutions\n% note remove the private setting from the opti class\nclear all\n\n%% Bounds\nclc\nf = [-1;-2;-3;-4];\nlb = [0;0;0;0];\nub = [1;1;1;1];\n\nO = opti('f',f,'bounds',lb,ub,'options',optiset('solver','clp'));\nO.sol = [-1;-1;2;2];\nO.ef = 1;\n\n[status,msg] = checkSol(O)\n\n%% LP General Constraints\nclc\nf = [-1;-2];\nA = [1 0;0 1];\nb = [0;0];\nAeq = [1 0; 0 1];\nbeq = [0.5;0.5];\n\nO = opti('f',f,'ineq',A,b,'eq',Aeq,beq,'options',optiset('solver','cplex'));\nO.sol = [1;1];\nO.ef = 1;\n\n[status,msg] = checkSol(O)\n\n%% LP Row Constraints\nclc\nf = [-1;-2];\nA = sparse([1 0;0 1;1 0;0 1;1 0;0 1]);\nrl = [2;2;-Inf;-Inf;0.5;0.5];\nru = [Inf;Inf;0;0;0.5;0.5];\n\nO = opti('f',f,'lin',A,rl,ru,'options',optiset('solver','clp'));\nO.sol = [1;1];\nO.ef = 1;\n\n[status,msg] = checkSol(O)\n\n%% QC Single Constraint\nclc\nf = [-1;-2];\nQ = eye(2);\nl = [-1;-2];\n\nO = opti('H',zeros(2),'f',f,'qc',Q,l,-1.5,'options',optiset('solver','scip'));\nO.sol = [1;1];\nO.ef = 1;\n\n[status,msg] = checkSol(O)\n\n%% QC Multiple Constraints\nclc\nf = [-1;-2];\nQ = {eye(2);eye(2)};\nl = [-1 -1;-2 -3];\n\nO = opti('H',zeros(2),'f',f,'qc',Q,l,[-1.5;-3],'options',optiset('solver','scip'));\nO.sol = [1;1];\nO.ef = 1;\n\n[status,msg] = checkSol(O)\n\n%% NLP General Constraints\nclc\nfun = @(x) x(1)+x(2);\nnlcon = @(x) [x(1);x(2);x(1);x(2);x(1);x(2)];\nnlrhs = [2;2;0;0;0.5;0.5];\nnle = [1;1;-1;-1;0;0];\n\nO = opti('fun',fun,'nlmix',nlcon,nlrhs,nle,'ndec',2,'options',optiset('solver','nlopt'));\nO.sol = [1;1];\nO.ef = 1;\n\n[status,msg] = checkSol(O)\n\n%% NLP Row Constraints\nclc\nfun = @(x) x(1)+x(2);\nnlcon = @(x) [x(1);x(2);x(1);x(2);x(1);x(2)];\ncl = [2;2;-Inf;-Inf;0.5;0.5];\ncu = [Inf;Inf;0;0;0.5;0.5];\n\nO = opti('fun',fun,'nl',nlcon,cl,cu,'ndec',2,'options',optiset('solver','ipopt'));\nO.sol = [1;1];\nO.ef = 1;\n\n[status,msg] = checkSol(O)\n\n%% Integer Constraints\nclc\nf = [-1;-2;-3;-4];\nlb = [0;0;0;0];\nub = [1;1;1;1];\n\nO = opti('f',f,'bounds',lb,ub,'int','ICCI','options',optiset('solver','cbc'));\nO.sol = [-1.1;-1.5;2;2.1];\nO.ef = 1;\n\n[status,msg] = checkSol(O)\n\n%% Binary Constraints\nclc\nf = [-1;-2;-3;-4];\nlb = [0;0;0;0];\nub = [1;1;1;1];\n\nO = opti('f',f,'bounds',lb,ub,'int','ICBI','options',optiset('solver','cbc'));\nO.sol = [-1.1;-1.5;1.001;2.1];\nO.ef = 1;\n\n[status,msg] = checkSol(O)", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Test Problems/Development/test_checkSol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6916975195800905}} {"text": "\n\nclear all; close all;\nI=imread('cameraman.tif');\nI=im2double(I);\nI=imnoise(I, 'salt & pepper', 0.05);\nJ=medfilt2(I, [3, 3]);\nfigure;\nsubplot(121); imshow(I);\nsubplot(122); imshow(J);\n\n\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/\u300aMATLAB\u56fe\u50cf\u5904\u7406\u300b\u6e90\u6587\u4ef6/\u672c\u4e66\u6e90\u6587\u4ef6/chap6/chap6_12.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.7853085834000791, "lm_q1q2_score": 0.6916975080270118}} {"text": "function sphere_triangle_quad_test03 ( )\n\n%*****************************************************************************80\n%\n%% SPHERE_TRIANGLE_TEST03 tests SPHERE01_TRIANGLE_QUAD_ICOS1C.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 23 April 2014\n%\n% Author:\n%\n% John Burkardt\n%\n e_test = [ ...\n 0, 0, 0; ...\n 1, 0, 0; ...\n 0, 1, 0; ...\n 0, 0, 1; ...\n 2, 0, 0; ...\n 0, 2, 2; ...\n 2, 2, 2; ...\n 0, 2, 4; ...\n 0, 0, 6; ...\n 1, 2, 4; ...\n 2, 4, 2; ...\n 6, 2, 0; ...\n 0, 0, 8; ...\n 6, 0, 4; ...\n 4, 6, 2; ...\n 2, 4, 8; ...\n 16, 0, 0 ]';\n n_mc1 = 1000;\n n_mc2 = 10000;\n n_mc3 = 100000;\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPHERE_TRIANGLE_QUAD_TEST03\\n' );\n fprintf ( 1, ' SPHERE01_TRIANGLE_QUAD_ICOS1C approximates the\\n' );\n fprintf ( 1, ' integral of a function over a spherical triangle on\\n' );\n fprintf ( 1, ' the surface of the unit sphere using a centroid rule.\\n' );\n fprintf ( 1, '\\n' ); \n fprintf ( 1, ' We do not have an exact result, so we compare each\\n' );\n fprintf ( 1, ' estimate to the final one.\\n' );\n%\n% Choose three points at random to define a spherical triangle.\n%\n [ v1, seed ] = sphere01_sample ( 1, seed );\n [ v2, seed ] = sphere01_sample ( 1, seed );\n [ v3, seed ] = sphere01_sample ( 1, seed );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Vertices of random spherical triangle:\\n' );\n fprintf ( 1, '\\n' );\n r8vec_transpose_print ( 3, v1, ' V1:' );\n r8vec_transpose_print ( 3, v2, ' V2:' );\n r8vec_transpose_print ( 3, v3, ' V3:' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' FACTOR N RESULT\\n' );\n\n for j = 1 : 17\n\n e(1:3) = e_test(1:3,j);\n\n e = polyterm_exponent ( 'SET', e );\n\n polyterm_exponent ( 'PRINT', e );\n\n% factor = 2 ^ 11;\n factor = 2 ^ 7;\n [ best, node_num ] = sphere01_triangle_quad_icos1c ( v1, v2, v3, factor, ...\n @polyterm_value_3d );\n\n factor = 1;\n for factor_log = 0 : 5\n\n [ result, node_num ] = sphere01_triangle_quad_icos1c ( v1, v2, v3, ...\n factor, @polyterm_value_3d );\n\n error = abs ( result - best );\n\n fprintf ( 1, ' %4d %8d %16.8g %10.2e\\n', ...\n factor, node_num, result, error );\n\n factor = factor * 2;\n\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/sphere_triangle_quad/sphere_triangle_quad_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.6916975033568948}} {"text": "function x=demean(x,dim)\n\n% DEMEAN(X) \n% Removes the Average or mean value.\n%\n% DEMEAN(X,DIM)\n% Removes the mean along the dimension DIM of X. \n\nif(nargin==1),\n dim = 1;\n if(size(x,1) > 1)\n dim = 1;\n elseif(size(x,2) > 1)\n dim = 2;\n end;\nend;\n\ndims = size(x);\ndimsize = size(x,dim);\ndimrep = ones(1,length(dims));\ndimrep(dim) = dimsize;\n\nx = x - repmat(mean(x,dim),dimrep);", "meta": {"author": "yetianmed", "repo": "subcortex", "sha": "76179cf552b773e79b06a54568eae1fdd13722f4", "save_path": "github-repos/MATLAB/yetianmed-subcortex", "path": "github-repos/MATLAB/yetianmed-subcortex/subcortex-76179cf552b773e79b06a54568eae1fdd13722f4/functions/wishart/demean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.6916974994200581}} {"text": "%KLMS Karhunen Loeve Mapping, followed by scaling\n% \n% [W,FRAC] = KLMS(A,N)\n% [W,N] = KLMS(A,FRAC)\n% \n% INPUT\n% A Dataset\n% N or FRAC Number of dimensions (>= 1) or fraction of variance (< 1) \n% to retain; if > 0, perform PCA; otherwise MCA. Default: N = inf.\n%\n% OUTPUT\n% W Affine Karhunen-Loeve mapping\n% FRAC or N Fraction of variance or number of dimensions retained.\n%\n% DESCRIPTION\n% First a Karhunen Loeve Mapping is performed (i.e. PCA or MCA on the average \n% prior-weighted class covariance matrix). The result is scaled by the mean \n% class standard deviations. For N and FRAC, see KLM.\n%\n% Default N: select all ('pre-whiten' the average covariance matrix, i.e.\n% orthogonalize and scale). The resulting mapping has a unit average\n% covariance matrix.\n% \n% SEE ALSO (PRTools Guide)\n% MAPPINGS, DATASETS, KLM, PCA\n\n% Copyright: R.P.W. Duin, duin@ph.tn.tudelft.nl\n% Faculty of Applied Physics, Delft University of Technology\n% P.O. Box 5046, 2600 GA Delft, The Netherlands\n\n% $Id: klms.m,v 1.2 2006/03/08 22:06:58 duin Exp $\n\nfunction [w,truefrac] = klms(a,n)\n\n\t\tif (nargin < 2), n = []; end;\n\tif (nargin < 1) | (isempty(a))\n\t\tw = prmapping('klms',n);\n\t\tw = setname(w,'Scaled KL Mapping');\n\t\treturn\n\tend\n\t\n\t[w,truefrac] = klm(a,n); % Calculate KL mapping\n\tb = a*w; % Combine KL mapping with scaling on\n\tw = w*scalem(b,'c-variance'); % KL-mapped data\n\tw = setname(w,'Scaled KL Mapping');\n\n\treturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/klms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6916974984423508}} {"text": "function accuracy = ClassifyDataset(dataset, labels, P, G)\n% returns the accuracy of the model P and graph G on the dataset \n%\n% Inputs:\n% dataset: N x 10 x 3, N test instances represented by 10 parts\n% labels: N x 2 true class labels for the instances.\n% labels(i,j)=1 if the ith instance belongs to class j \n% P: struct array model parameters (explained in PA description)\n% G: graph structure and parameterization (explained in PA description) \n%\n% Outputs:\n% accuracy: fraction of correctly classified instances (scalar)\n%\n% Copyright (C) Daphne Koller, Stanford Univerity, 2012\n\nN = size(dataset, 1);\naccuracy = 0.0;\ncalclabels = zeros(size(labels));\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% YOUR CODE HERE\nif size(size(G),2) == 2\n\tG1 = G; G2 = G;\nelse\n\tG1 = reshape(G(:,:,1),10,2);\n\tG2 = reshape(G(:,:,2),10,2);\nend\n\nfor i = 1:N\n\tdata = reshape(dataset(i,:,:),10,3);\n\tlog1 = log(P.c(1));\n\tlog2 = log(P.c(2));\n\tfor j = 1:10\n\t\tif G1(j,1) == 1 % construct g1 and g2 in the beginning from g\n\t\t\t%do shit\n\t\t\ttheta1 = P.clg(j).theta(1,:); theta2 = P.clg(j).theta(2,:);\n\t\t\tparent1 = data(G1(j,2),:); parent2 = data(G2(j,2),:);\n\t\t\tmu_y1 = sum(theta1(1:4).*[1, parent1]);mu_y2 = sum(theta2(1:4).*[1, parent2]);\n\t\t\tmu_x1 = sum(theta1(5:8).*[1, parent1]);mu_x2 = sum(theta2(5:8).*[1, parent2]);\n\t\t\tmu_a1 = sum(theta1(9:12).*[1, parent1]);mu_a2 = sum(theta2(9:12).*[1, parent2]);\n\t\t\tlog1 += lognormpdf(data(j,1),mu_y1,P.clg(j).sigma_y(1));\n\t\t\tlog1 += lognormpdf(data(j,2),mu_x1,P.clg(j).sigma_x(1));\n\t\t\tlog1 += lognormpdf(data(j,3),mu_a1,P.clg(j).sigma_angle(1));\n\t\t\tlog2 += lognormpdf(data(j,1),mu_y2,P.clg(j).sigma_y(2));\n\t\t\tlog2 += lognormpdf(data(j,2),mu_x2,P.clg(j).sigma_x(2));\n\t\t\tlog2 += lognormpdf(data(j,3),mu_a2,P.clg(j).sigma_angle(2));\n\n\t\telse\n\t\t\tlog1 += lognormpdf(data(j,1),P.clg(j).mu_y(1),P.clg(j).sigma_y(1));\n\t\t\tlog1 += lognormpdf(data(j,2),P.clg(j).mu_x(1),P.clg(j).sigma_x(1));\n\t\t\tlog1 += lognormpdf(data(j,3),P.clg(j).mu_angle(1),P.clg(j).sigma_angle(1));\n\t\t\tlog2 += lognormpdf(data(j,1),P.clg(j).mu_y(2),P.clg(j).sigma_y(2));\n\t\t\tlog2 += lognormpdf(data(j,2),P.clg(j).mu_x(2),P.clg(j).sigma_x(2));\n\t\t\tlog2 += lognormpdf(data(j,3),P.clg(j).mu_angle(2),P.clg(j).sigma_angle(2));\n\t\tend\n\tend\n\tcalclabels(i,:) = [log1,log2];\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[temp,temp1] = max(calclabels,[],2);\n[temp,temp2] = max(labels,[],2);\naccuracy = sum(temp1==temp2)/N;\nfprintf('Accuracy: %.2f\\n', accuracy);\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/8.Learning Tree Structured Networks/ClassifyDataset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6916974891021166}} {"text": "function x=windinfo(w,fs)\n%V_WINDINFO window information and figures of merit X=(W,FS)\n% Usage: (1) v_windinfo(v_windows('hamming',720,'ds'),720); % plot hamming window info\n%\n% Inputs: W is a vector containing the window\n% FS is the sampling frequency (default=1)\n%\n% Outputs: X.len length of the window (samples)\n% X.nw length of the window (samples)\n% X.ewgdelay energy centroid delay from first sample (samples)\n% X.dcgain DC gain (dB)\n% X.sidelobe maximum sdelobe level in dB relative to DC gain\n% X.falloff rate at which sidelobes decay (dB/octave)\n% X.enbw equivalent noise bandwidth (*fs/len Hz)\n% X.scallop scalloping loss (dB)\n% X.ploss processing loss (dB)\n% X.wcploss worst case processing loss (dB)\n% X.band3 3dB bandwidth (Hz)\n% X.band6 6 dB bandwidth (Hz)\n% X.band0 essential bandwidth (to first minimum) (Hz)\n% X.gain0 gain at first minimum (Hz)\n% X.olc50 50% overlap correction\n% X.olc75 75% overlap correction\n% X.cola overlap factors giving constant overlap add (exlcuding multiples)\n% X.cola2 as X.cola but for squared window\n%\n% If no output argument is given, the window and frequency response\n% will be plotted e.g. v_windinfo(v_windows('hamming',720,'ds'),720);\n%\n% To obtain the figures of merit listed in Table 1 of [1] set\n% fs = length(W), multiply X.olc50 and X.olc75 by 100%. The \"coherent gain\n% listed in the table is 10^(x.dcgain/20)/(max(w)*length(w)).\n%\n% [1] F. J. Harris. On the use of windows for harmonic analysis with the\n% discrete fourier transform. Proc IEEE, 66 (1): 51-83, Jan. 1978.\n\n%\t Copyright (C) Mike Brookes 2009-2014\n% Version: $Id: v_windinfo.m 6801 2015-09-12 09:30:42Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\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 can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n\nif nargin<2\n fs=1;\nend\nw=w(:);\nnw=length(w);\nx.len=nw/fs;\nx.nw=nw;\n% energy weighted group delay = centre of energy\nx.ewgdelay=((1:nw)*w.^2/sum(w.^2)-1)/fs;\n% now calculate spectrum\nof=16; % spectrum oversample factor must be even\nnwo=of*nw;\nf=rfft(w,nwo);\np=f.*conj(f);\n% sidelobe attenuation is maximum peak (note DC peak at p(1) is not found)\n[kp,vp]=v_findpeaks(p,'q');\n[kt,vt]=v_findpeaks(-p,'q');\n% dbpo=10*log10(vp(2:end)./vp(1:end-1))./log2((kp(2:end)-1)./(kp(1:end-1)-1)); % slope in dB/octave\nif ~numel(kp)\n x.sidelobe=10*log10(min(p)/p(1));\nelse\n x.sidelobe=10*log10(max(vp)/p(1));\nend\nnp=length(kp);\nipa=floor(np/4);\nif ~ipa\n x.falloff=0;\nelse\n ipb=floor(np/2);\n x.falloff=10*log10(vp(ipb)/vp(ipa))/log2((ipb-1)/(ipa-1));\nend\nsumw2=sum(w.^2);\nsumw=sum(w);\nenbwbin=nw*sumw2/sumw^2;\nx.enbw=enbwbin*fs/nw;\nx.dcgain=20*log10(sumw);\n% do linear interpolation in p() to find 3dB and 6dB points\np3=0.5*p(1);\ni3=find(p0\n x.gain0=10*log10(p0/p(1));\n else\n x.gain0=-Inf;\n end\nend\n% overlap factors\ni50=round(nw*0.5);\nx.olc50=sum(w(1:nw-i50).*w(1+i50:nw))/sumw2;\ni75=round(nw*0.25);\nx.olc75=sum(w(1:nw-i75).*w(1+i75:nw))/sumw2;\n% processing loss and scalloping loss\nx.scallop=10*log10(p(1)/p(1+of/2));\nx.ploss=10*log10(enbwbin);\nx.wcploss=x.ploss+x.scallop;\nco=zeros(1,nw);\nco2=co;\nw2=w.^2;\nfor i=1:nw\n if i*fix(nw/i)==nw % check i is a factor of the window length\n if co(i)==0\n co(i)=all(abs(sum(reshape(w',nw/i,i),2)-i*mean(w))2000\n ff=ff/1000;\n fqi=fqi/1000;\n xlab='kcyc/L';\n else\n xlab='cyc/L';\n end\n dbn=20*log10(x.nw); % window width in dB\n dbrange=min(100,-1.5*x.sidelobe);\n dd=10*log10(max(p(1:nf),p(1)*0.1^(dbrange/10)));\n ffs=[0 ff(end)];\n dbs=repmat(x.dcgain+x.sidelobe,1,2);\n ffb=[0 fqi(1) fqi(1)];\n dbb=[dd(1) dd(1) dd(1)-dbrange];\n ff3=[0 fqi(2) fqi(2)];\n db3=[dd(1)+db(0.5)/2 dd(1)+db(0.5)/2 dd(1)-dbrange];\n ff6=[0 fqi(3) fqi(3)];\n db6=[dd(1)+db(0.5) dd(1)+db(0.5) dd(1)-dbrange];\n area(ffb,dbb-dbn,max(dd)-dbrange-dbn,'facecolor',[1 0.7 0.7]);\n hold on\n plot(ffs,dbs-dbn,':k',ff3,db3-dbn,':k',ff6,db6-dbn,':k',ffb,dbb-dbn,'r',ff,dd-dbn,'b');\n legend(['Equiv Noise BW = ' sprintsi(x.enbw,-2) 'cyc/L'],['Max sidelobe = ' sprintf('%.0f',x.sidelobe) ' dB'],['-3 & -6dB BW = ' sprintf('%.2g',(x.band3)) ' & ' sprintf('%.2g',(x.band6)) ' cyc/L']);\n hold off\n axis([0 ff(end) max(dd)-dbrange-dbn max(dd)+2-dbn]);\n ylabel('Gain/N (dB)');\n xlabel(sprintf('Freq (%s)',xlab));\n %\n % Now plot the window itself\n %\n subplot(211);\n tax=(0:nw-1)/fs-x.ewgdelay;\n area(tax,w,'FaceColor',[0.7 0.7 1]);\n ylabel('Window');\n xlabel('Time/L');\n dtax=(tax(end)-tax(1))*0.02;\n axv=[tax(1)-dtax tax(end)+dtax min(0,min(w)) max(w)*1.05];\n texthvc(tax(end),max(w),sprintf('N=%d',nw),'rtk');\n if length(x.cola)>3\n tcola=sprintf(',%d',x.cola(1:3));\n tcola=[tcola ',...'];\n else\n tcola=sprintf(',%d',x.cola);\n end\n if length(x.cola2)>3\n tcola2=sprintf(',%d',x.cola2(1:3));\n tcola2=[tcola2 ',...'];\n else\n tcola2=sprintf(',%d',x.cola2);\n end\n texthvc(tax(1),max(w),sprintf('COLA=%s\\nCOLA^2=%s',tcola(2:end),tcola2(2:end)),'ltk');\n axis(axv);\nend\n\n\n\n", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_windinfo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.6916209495432549}} {"text": "function pdf = pdf_discrete_value ( x_num, x, y, v_num, v )\n\n%*****************************************************************************80\n%\n%% PDF_DISCRETE_VALUE evaluates the PDF of a discrete histogram.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer V_NUM, the number of sample values.\n%\n% Input, real V(V_NUM,1), the sample values.\n%\n% Input, integer X_NUM, the number of values in the discrete histogram.\n%\n% Input, real X(X_NUM,1), the histogram data values.\n%\n% Input, real Y(X_NUM,1), the normalized histogram values.\n%\n% Output, real PDF(V_NUM,1), the values of the discrete PDF.\n%\n pdf = zeros ( v_num, 1 );\n%\n% Seek bracket intervals for each sample point.\n%\n b(1:v_num,1) = r8vec_bracket6 ( x_num, x, v_num, v );\n%\n% Sample points outside the interval are ignored.\n%\n i = find ( b ~= -1 );\n%\n% Linearly interpolate values within the interval.\n%\n l = b(i);\n r = l + 1;\n%\n% pdf(i) = ( ( x(r) - v(i) ) .* y(l) ...\n% + ( v(i) - x(l) ) .* y(r) ) ...\n% ./ ( x(r) - x(l) );\n\n for i = 1 : v_num\n if ( b(i) ~= -1 )\n l = b(i);\n r = l + 1;\n pdf(i) = ( ( x(r) - v(i) ) .* y(l) ...\n + ( v(i) - x(l) ) .* y(r) ) ...\n ./ ( x(r) - x(l) );\n end\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/histogram_discrete/pdf_discrete_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.6916209488326215}} {"text": "function isContained=rectContainedInRect(rectMin1,rectMax1,rectMin2,rectMax2)\n%RECTCONTAINEDINRECT Determine whether an axis-aligned rectangle (or a\n% more general axis-aligned hyperrectangle if the number\n% of dimensions is not two) is completely engulfed by\n% another rectangle. This does not indicate which\n% rectangle is contained in the other.\n%\n%INPUTS: rectMin1 A kX1 or 1Xk vector of the lower bounds of each of the\n% dimensions of the first k-dimensional hyperrectangle.\n% rectMax1 A kX1 or 1Xk vector of the upper bounds of the first\n% hyperectangle.\n% rectMin2 A kX1 or 1Xk vector of the lower bounds of the second\n% hyperrectangle.\n% rectMax2 A kX1 or 1Xk vector of the upper bounds of the second\n% hyperrectangle.\n%\n%OUTPUTS: isContained A boolean value that is true if one hyperrectangle\n% is completely contained in the other and is false otherwise.\n%\n%December 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nk=length(rectMin1);\n\nisContained=true;\nfor curIdx=1:k\n if(rectMin1(curIdx)rectMax2(curIdx))\n isContained=false;\n break;\n end\nend\n\nif(isContained==true)\n return;\nend\n\nisContained=true;\nfor curIdx=1:k\n if(rectMin2(curIdx)rectMax1(curIdx))\n isContained=false;\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/Geometry/rectContainedInRect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8459424314825852, "lm_q1q2_score": 0.6916209403093518}} {"text": "function [sigma,dkm,g,r]=noiseest(dlogCr,dlogr,method)\n%Syntax: [sigma,dkm,g,r]=noiseest(dlogCr,dlogr,method)\n%_____________________________________________________\n%\n% Calculates the noise standard deviation from the derivative of the \n% Correlation Integral. Requires the auxilary function \"dkmminusg\".\n%\n% sigma is the noise standard deviation.\n% dkm is the empirical effect of noise on the Correlation Integral.\n% g is the theoritical effect of noise on the Correlation Integral.\n% r is the range.\n% dlogCr is the derivative of the logCr.\n% dlogr is the log(range).\n% method can take one of the folloing values:\n% 'full' for Schreiber's full minimization\n% 'mod' for Leontitsis et al. modified minimization\n%\n%\n% References:\n%\n% Schreiber T (1993): Determination of the noise level of chaotic time\n% series. Physical Review E 48(1): R13-R16\n%\n% Leontitsis A, Pange J., Bountis T. (2003): Large noise level estimation.\n% International Journal of Bifurcation and Chaos 13(8): 2309-2313\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% June 15, 2001.\n\n% dlogCr and dlogr must have the same number of rows\nif size(dlogCr,1)~=size(dlogr,1)\n error('dlogCr and dlogr must have the same number of rows.');\nend\n\nr=10.^dlogr;\noptions=optimset('Display','off');\nfor i=2:size(dlogCr,2)\n dkm(:,i-1)=(dlogCr(:,i)-dlogCr(:,1))/(i-1);\n sigma(i-1)=fminbnd(@dkmminusg,r(1),r(end),options,dkm(:,i-1),r,method);\nend\nz=r./2./sigma(1);\ng=2.*z.*exp(-z.^2)./sqrt(pi)./erf(z);\n\n\nfunction error=dkmminusg(s,dkm,r,method)\n%Syntax: error=dkmminusg(s,dkm,r,method)\n%_______________________________________\n%\n% Auxilary function for \"noiseest\". Calculates the error between the dkm\n% and function \"g\" given a noise standard deviation (s) and a vector of \n% range values (r).\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% June 15, 2001.\n\n% Calculate the auxilary variable z\nz=r./2./s;\n\n% Calpculate the g fumction\ng=2*z.*exp(-z.^2)/sqrt(pi)./erf(z);\n\nswitch method\n case 'full'\n % The ordinary (low noise) calculation\n error=norm(dkm-g); \n case 'mod'\n % The modified (large noise) estimation\n if any(dkm along a given\n% dimension .\n%\n% x: array to be detrended\n% dim: dimension along which to detrend, default is first nonsingleton\n% type: linear detrend (1) or demean (0), default is linear.\n% breaks: breakpoint indices for a piecewise linear trend\n%\n% See also DETREND, MEAN\n\n% Based on DETREND.M\n% Copyright 1984-2004 The MathWorks, Inc.\n% Modified by Bill Winter May 2006\nfunction x = ndetrend(x,dim,o,b)\nsiz = size(x); % array size\nif nargin < 2, dim = find(siz > 1,1); end % default: nonsingleton\nN = siz(dim); % dimension length\na = ones(N,1); % constant\nif nargin < 3 || o % default: linear\n if nargin < 4, b = []; end % default: no breaks\n b = unique([1;b(:)]); % breaks unique\n b(b < 1 | b > N-1) = []; % breaks within array\n l = length(b); % number linear pieces\n a = [zeros(N,l) a]; % preallocate linear\n M = N - b; % length of linear piece\n for k = 1:l, a(1+b(k):N,k) = (1:M(k))'/M(k); end% linear pieces\nend\nif length(siz) > 2\n if dim ~= 1 % permute 1 with dim\n per = 1:length(siz);\n per([1 dim]) = [dim 1];\n siz([1 dim]) = siz([dim 1]);\n x = builtin('permute',x,per);\n end\n for k = 1:prod(siz(3:end)), x(:,:,k) = x(:,:,k) - a*(a\\x(:,:,k));end\n if dim ~= 1, x = builtin('permute',x,per);end % depermute 1 with dim\nelseif dim == 2, x = x - (x/a')*a'; % right-regress\nelseif dim == 1, x = x - a*(a\\x); % left-regress\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/11139-array-tool-set/array/ndetrend.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6915852495678212}} {"text": "function cinh_values_test ( )\n\n%*****************************************************************************80\n%\n%% CINH_VALUES_TEST demonstrates the use of CINH_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 January 2015\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CINH_VALUES_TEST:\\n' );\n fprintf ( 1, ' CINH_VALUES stores values of\\n' );\n fprintf ( 1, ' the Hyperbolic Cosine Integral function CINH(X).\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X CINH(X)\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, x, fx ] = cinh_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %12f %24.16f\\n', x, fx );\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/test_values/cinh_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.6915852406629452}} {"text": "%converts frequency to mel\n%>\n%> @param fInHz: frequency\n%> @param cModel: 'Fant','Shaughnessy', or 'Umesh'\n%>\n%> @retval mel pitch value\n% ======================================================================\nfunction [mel] = ToolFreq2Mel(fInHz, cModel)\n\n if (nargin < 2)\n cModel = 'Fant';\n end\n\n % set function handle\n hPitchFunc = str2func (['aca' cModel '_I']);\n \n mel = hPitchFunc(fInHz);\nend\n\n% Fant\nfunction [mel] = acaFant_I(f)\n mel = 1000 * log2(1 + f/1000);\nend\n\n% Shaughnessy\nfunction [mel] = acaShaughnessy_I(f)\n mel = 2595 * log10(1 + f/700);\nend\n\n% Umesh\nfunction [mel] = acaUmesh_I(f)\n mel = f./(2.4e-4*f + 0.741);\nend", "meta": {"author": "alexanderlerch", "repo": "ACA-Code", "sha": "85d7258d5fcee1ca52bac52f651d26b665717687", "save_path": "github-repos/MATLAB/alexanderlerch-ACA-Code", "path": "github-repos/MATLAB/alexanderlerch-ACA-Code/ACA-Code-85d7258d5fcee1ca52bac52f651d26b665717687/ToolFreq2Mel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6915848753188599}} {"text": "function A = TriArea3D(X1,X2,X3)\n\n% Xi n*3 are the three points of triangles where n is the number of\n% triangle\n\nx1 = X1(:,1); y1 = X1(:,2); z1 = X1(:,3);\nx2 = X2(:,1); y2 = X2(:,2); z2 = X2(:,3);\nx3 = X3(:,1); y3 = X3(:,2); z3 = X3(:,3);\nA = 1/2*(((x1-x3).*(y2-y1) - (x1-x2).*(y3-y1)).^2 + ...\n ((y1-y3).*(z2-z1) - (y1-y2).*(z3-z1)).^2 + ...\n ((z1-z3).*(x2-x1) - (z1-z2).*(x3-x1)).^2).^(1/2);\n\nA = abs(A);\n\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/TriArea3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6915848668093513}} {"text": "function [features,F,M] = lpc2spec(lpcas, nout)\n% [features,F,M] = lpc2spec(lpcas,nout)\n% Convert LPC coeffs back into spectra\n% nout is number of freq channels, default 17 (i.e. for 8 kHz)\n% 2003-04-11 dpwe@ee.columbia.edu part of rastamat\n\nif nargin < 2\n nout = 17;\nend\n\n[rows, cols] = size(lpcas);\norder = rows - 1;\n\ngg = lpcas(1,:);\naa = lpcas./repmat(gg,rows,1);\n\n% Calculate the actual z-plane polyvals: nout points around unit circle\nzz = exp((-j*[0:(nout-1)]'*pi/(nout-1))*[0:order]);\n\n% Actual polyvals, in power (mag^2)\nfeatures = ((1./abs(zz*aa)).^2)./repmat(gg,nout,1);\n\nF = zeros(cols, floor(rows/2));\nM = F;\n\nfor c = 1:cols;\n aaa = aa(:,c);\n rr = roots(aaa');\n ff = angle(rr');\n% size(ff)\n% size(aaa)\n zz = exp(j*ff'*[0:(length(aaa)-1)]);\n mags = sqrt(((1./abs(zz*aaa)).^2)/gg(c))';\n \n [dummy, ix] = sort(ff);\n keep = ff(ix) > 0;\n ix = ix(keep);\n F(c,1:length(ix)) = ff(ix);\n M(c,1:length(ix)) = mags(ix);\nend\n", "meta": {"author": "stephencwelch", "repo": "Perceptual-Coding-In-Python", "sha": "2993f57570663768c02745019185091a23f021fe", "save_path": "github-repos/MATLAB/stephencwelch-Perceptual-Coding-In-Python", "path": "github-repos/MATLAB/stephencwelch-Perceptual-Coding-In-Python/Perceptual-Coding-In-Python-2993f57570663768c02745019185091a23f021fe/matlabCode/bark_domain_exploration/rastamat/lpc2spec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.7520125793176223, "lm_q1q2_score": 0.6915827585461166}} {"text": "% Chapter 8 - Planar Systems.\n% Program_8b - Phase Portrait (Fig. 8.8(a)).\n% Copyright Birkhauser 2013. Stephen Lynch.\n\n% Phase portrait of a linear system of ODE's.\n% IMPORTANT - Program_8a is vectorfield.m.\nclear;\n% sys=inline('[2*x(1)+x(2);x(1)+2*x(2)]','t', 'x');\nsys = @(t,x) [2*x(1)+x(2);x(1)+2*x(2)]; \nvectorfield(sys,-3:.25:3,-3:.25:3)\n hold on\n for x0=-3:1.5:3\n for y0=-3:1.5:3\n [ts,xs] = ode45(sys,[0 5],[x0 y0]);\n plot(xs(:,1),xs(:,2))\n end\n end\n for x0=-3:1.5:3\n for y0=-3:1.5:3\n [ts,xs] = ode45(sys,[0 -5],[x0 y0]);\n plot(xs(:,1),xs(:,2))\n end\n end\n hold off\naxis([-3 3 -3 3])\nfsize=15;\nset(gca,'XTick',-3:1:3,'FontSize',fsize)\nset(gca,'YTick',-3:1:3,'FontSize',fsize)\nxlabel('x(t)','FontSize',fsize)\nylabel('y(t)','FontSize',fsize)\nhold off\n\n% End of Program_8b.", "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/2374-dynamical-systems-with-applications-using-matlab/MATLAB files 20013a/Program_8b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6914964998195169}} {"text": "function IIDAnalysis(Dates,Data)\n% this function performs simple invariance (i.i.d.) tests on a time series\n% 1. it checks that the variables are identically distributed by looking at the \n% histogram of two subsamples\n% 2. it checks that the variables are independent by looking at the 1-lag scatter plot\n% under i.i.d. the location-dispersion ellipsoid should be a circle\n% see \"Risk and Asset Allocation\"-Springer (2005), by A. Meucci\n\n\n\n\n% plot time series\n\nfigure\nh=plot(Dates,Data,'.'); \nxlim([Dates(1) Dates(end)])\ndatetick('x','mmmyy','keeplimits','keepticks');\ngrid on\n\n\n% test \"identically distributed hypothesis\": split observations into two sub-samples and plot histogram\nSample_1=Data(1:round(length(Data)/2));\nSample_2=Data(round(length(Data)/2)+1:end);\nnum_bins_1=round(5*log(length(Sample_1)));\nnum_bins_2=round(5*log(length(Sample_2)));\nX_lim=[min(Data)-.1*(max(Data)-min(Data)) max(Data)+.1*(max(Data)-min(Data))];\n[n1,xout1]=hist(Sample_1,num_bins_1);\n[n2,xout2]=hist(Sample_2,num_bins_2);\n\nfigure\nsubplot('Position',[0.03 .59 .44 .35])\nh1=bar(xout1,n1,1);\nset(h1,'FaceColor',[.7 .7 .7],'EdgeColor','k')\nset(gca,'ytick',[],'xlim',X_lim,'ylim',[0 max(max(n1),max(n2))])\ngrid off\n\nsubplot('Position',[.53 .59 .44 .35])\nh2=bar(xout2,n2,1);\nset(h2,'FaceColor',[.7 .7 .7],'EdgeColor','k');\nset(gca,'ytick',[],'xlim',X_lim,'ylim',[0 max(max(n1),max(n2))]);\ngrid off\n\n% test \"independently distributed hypothesis\": scatter plot of observations at lagged times\nsubplot('Position',[.28 .01 .43 .43])\nX=Data(1:end-1);\nY=Data(2:end);\nh3=plot(X,Y,'.');\ngrid off\naxis equal\nset(gca,'xlim',X_lim,'ylim',X_lim);\n\nm=mean([X Y])';\nS=cov([X Y]);\nTwoDimEllipsoid(m,S,2,0,0);", "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/23554-review-of-discrete-and-continuous-processes-in-finance/Matlab/01RandomWalk/Empirical/IIDAnalysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6914964956616634}} {"text": "function pass = test_coeffs2vals(pref)\n% test various coeffs2vals, vals2coeffs, vals2vals, and coeffs2coeffs codes.\nif ( nargin == 0 )\n pref = chebfunpref();\nend\n\ntol = 1000*eps;\n\nf = chebfun(@exp, pref);\nN = length(f);\nc_leg = legcoeffs(f);\nc_cheb = chebcoeffs(f);\nv_leg = f(legpts(N));\nv_cheb1 = f(chebpts(N,1));\nv_cheb2 = f(chebpts(N,2));\n\npass(1) = norm(c_leg - chebcoeffs2legcoeffs(c_cheb), inf) < tol;\npass(2) = norm(c_leg - legvals2legcoeffs(v_leg), inf) < tol;\npass(3) = norm(c_leg - chebvals2legcoeffs(v_cheb1, 1), inf) < tol;\npass(4) = norm(c_leg - chebvals2legcoeffs(v_cheb2, 2), inf) < tol;\n\npass(5) = norm(c_cheb - legcoeffs2chebcoeffs(c_leg), inf) < tol;\npass(6) = norm(c_cheb - legvals2chebcoeffs(v_leg), inf) < tol;\npass(7) = norm(c_cheb - chebvals2chebcoeffs(v_cheb1, 1), inf) < tol;\npass(8) = norm(c_cheb - chebvals2chebcoeffs(v_cheb2, 2), inf) < tol;\n\npass(9) = norm(v_leg - legcoeffs2legvals(c_leg), inf) < tol;\npass(10) = norm(v_leg - chebcoeffs2legvals(c_cheb), inf) < tol;\npass(11) = norm(v_leg - chebvals2legvals(v_cheb1, 1), inf) < tol;\npass(12) = norm(v_leg - chebvals2legvals(v_cheb2, 2), inf) < tol;\n\npass(13) = norm(v_cheb1 - legcoeffs2chebvals(c_leg, 1), inf) < tol;\npass(14) = norm(v_cheb1 - chebcoeffs2chebvals(c_cheb,1), inf) < tol;\npass(15) = norm(v_cheb1 - legvals2chebvals(v_leg, 1), inf) < tol;\npass(16) = norm(v_cheb1 - chebvals2chebvals(v_cheb2, 2, 1), inf) < tol;\n\npass(17) = norm(v_cheb2 - legcoeffs2chebvals(c_leg, 2), inf) < tol;\npass(18) = norm(v_cheb2 - chebcoeffs2chebvals(c_cheb,2), inf) < tol;\npass(19) = norm(v_cheb2 - legvals2chebvals(v_leg, 2), inf) < tol;\npass(20) = norm(v_cheb2 - chebvals2chebvals(v_cheb1, 1, 2), inf) < tol;\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/misc/test_coeffs2vals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6914964778282737}} {"text": "function [xPred,SPred,exitCode]=sqrtCDEKFPred(xPrev,SPrev,a,D,AJacob,tPrev,tPred,RKOptions)\n%%SQRTCDEKFPRED Predict forward a Gaussian state estimate through time when\n% the evolution of the state is described by a\n% continuous-time stochastic diferential equation using a\n% square root continuous-discrete extended Kalman filter.\n% This uses a Gaussian approximation throughout the entire\n% prediction, allowing for a solution based on deterministic\n% differential equations. The differential equations are\n% integrated forward using the RKAdaptiveOverRange function,\n% an explicit Runge-Kutta method, which can take a number of\n% options.\n%\n%INPUTS: xPrev The xDim X 1 state estimate at time tPrior.\n% SPrev The xDim X xDim square root state covariance matrix at time\n% tPrior.\n% a The drift function in the continuous-time stochastic\n% dynamic model. It takes the state and a time variable as its\n% arguments.\n% D The diffusion function in the continuous-time stochastic\n% dynamic model. It takes the state and a time variable as its\n% arguments.\n% AJacob The derivative wrt x of the drift function in the\n% continuous-time stochastic dynamic model. It takes the\n% state and a time variable as its arguments. If an empty\n% matrix is passed, then AJacob will be found using\n% numerical differentiation via the numDiff function with\n% default parameters.\n% tPrev The time of xPrev and SPrev.\n% tPred The time to which xPrev and SPrev should be predicted.\n% RKOptions An optional structure whose components have the same name\n% and meaning as the corresponding components in the\n% RKAdaptiveOverRange function. The possible compnents of\n% the RKOptions function (with default values if omitted)\n% are\n% RKOptions.initStepSize: (tPred-tPrev)/RKOptions.maxSteps\n% RKOptions.order: 5\n% RKOptions.solutionChoice: 0\n% RKOptions.RelTol: 1e-3.\n% RKOptions.AbsTol: 1e-6\n% RKOptions.maxSteps: 1024\n% If an empty matrix is passed in place of RKOptions, then\n% only the default values will be used.\n%\n%OUTPUTS: xPred The xDim X 1 predicted state estimate. If the\n% RKAdaptiveOverRange function failed, which might occur,\n% for example, if the maximum number of allowed steps is\n% too small, then an empty matrix is returned.\n% SPred The xDim X xDim predicted square root state covariance\n% matrix, or an empty matrix if the RKAdaptiveOverRange\n% failed.\n% exitCode The exit code from the RKAdaptiveOverRange function. This\n% is zero if the integration was a success. Otherwise, the\n% value identifies what the problem was. See the\n% RKAdaptiveOverRange function for more details.\n%\n%The algorithm is modified from the mean-covariance Runge-Kutta (MC-RK4)\n%method described in [1]. Other methods in this paper are criticized in\n%Section III of [2].\n%\n%Parts of the calculation for the derivative of the square root state\n%covariance matrix are taken from Section VI of [3].\n%\n%REFERENCES:\n%[1] P. Frogerais., J. Bellanger, and L. Senhadji. \"Various ways to compute\n% the continuous-discrete extended Kalman filter,\" IEEE\n% Transactions on Automatic Control, vol. 57, no. 4, pp. 1000-1004,\n% 2012.\n%[2] G. Y. Kulikov and M. V. Kulikova. \"Accurate numerical implementation\n% of the continuous-discrete extended Kalman filter,\" IEEE Transactions\n% on Automatic Control, vol. 59, no. 1, pp. 273-279, Jan. 2014.\n%[3] D. F. Crouse, \"Basic tracking using nonlinear continuous-time dynamic\n% models,\" IEEE Aerospace and Electronic Systems Magazine, vol. 30, no.\n% 2, Part II, pp. 4-41, Feb. 2015.\n%\n%March 2015 David Karnick, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n xDim=length(xPrev);\n \n if(nargin<8)\n RKOptions=[];\n end\n if(isempty(AJacob))\n AJacob=@(x,t)numDiff(x,@(y) a(y,t),xDim);\n end\n \n %The default options for the RKAdaptiveOverRange function. The\n %initStepSize default option is not set until the other options are\n %read, since the default depends on the value of maxSteps.\n initStepSize=[];\n order=5;\n solutionChoice=0;\n RelTol=1e-3;\n AbsTol=1e-6;\n maxSteps=1024;\n if(~isempty(RKOptions)) \n if(isfield(RKOptions,'initStepSize'))\n initStepSize=RKOptions.initStepSize;\n end\n if(isfield(RKOptions,'order'))\n order=RKOptions.order;\n end\n if(isfield(RKOptions,'solutionChoice'))\n solutionChoice=RKOptions.solutionChoice;\n end\n if(isfield(RKOptions,'RelTol'))\n RelTol=RKOptions.RelTol;\n end\n if(isfield(RKOptions,'AbsTol'))\n AbsTol=RKOptions.AbsTol;\n end\n if(isfield(RKOptions,'maxSteps'))\n maxSteps=RKOptions.maxSteps;\n end\n end\n \n if(isempty(initStepSize))\n initStepSize=(tPred-tPrev)/maxSteps;\n end\n \n %The zeros in S are not given to the differential equation solver.\n %lowerTriEls holds the indices of the lower-triangular elements.\n lowerTriEls=tril(true(xDim,xDim));\n [xVals,~,~,exitCode]=RKAdaptiveOverRange([xPrev;SPrev(lowerTriEls)],[tPrev tPred],@f,initStepSize,0,order,solutionChoice,RelTol,AbsTol,maxSteps);\n if(isempty(xVals))%If the RKAdaptiveOverRange function failed.\n xPred=[];\n SPred=[];\n return;\n end\n\n xSVec=xVals(:,end);\n xPred=xSVec(1:xDim,end);\n SEls=xSVec((xDim+1):end,end);\n SPred=zeros(xDim,xDim);\n SPred(lowerTriEls)=SEls;\n\n function dVal=f(x,t)\n %This function provides the derivatives of the state and the\n %lower-triangular square root covariance matrix at a particular\n %time.\n xCur=x(1:xDim);\n SElsCur=x((xDim+1):end);\n %Only the nonzero elements of S were passed.\n SCur=zeros(xDim,xDim);\n SCur(lowerTriEls)=SElsCur;\n PCur=SCur*SCur';\n \n dx=a(xCur,t);\n \n dPoints=D(xCur,t);\n F=AJacob(xCur,t);\n dP=PCur*F'+F*PCur'+dPoints*dPoints';\n SInv=pinv(SCur);\n dS=SCur*triLower(SInv*dP*SInv');\n \n dVal=[dx;dS(lowerTriEls)];\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/Dynamic_Estimation/State_Propagation/Continuous_Time/sqrtCDEKFPred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6914868102657572}} {"text": "% Figure 10.70 Feedback Control of Dynamic Systems, 5e\n% Franklin, Powell, Emami\n%\n% fig10_87.m is a script to generate Fig. 10.70 the linear RTP response \n% LQG method with internal model\n% RTP chamber demo Example\nclf;\na=[-0.068208813989939 0.014929776357245 0.000000065782442;...\n 0.045809672136430 -0.118134773528570 0.021802006306129;...\n 0.000000433637498 0.046839194867347 -0.100884399149872];\nb3=[0.37873508304055 0.110575403544586 0.022912893467038;...\n 0.000000002974222 0.449046982554739 0.073572900808161;...\n 0.000000027324116 0.000702342292121 0.417797228783230];\nc3=eye(3,3);\nd=0*eye(3,3);\nsysp=ss(a,b3,c3,d);\n[eol]=eig(a);\n[zol]=tzero(sysp);\n[zol22]=tzero(a,b3(:,2),c3(2,:),d(2,2));\n% Combine 3 lamps into a single actuator\nb=b3(:,1)+b3(:,2)+b3(:,3);\n% Select center temperature\nc=c3(2,:)\naa=[zeros(1,1) c;zeros(3,1) a];\nbb=[zeros(1,1);b];\n%\n% weight temperature differences\nq1hat=[eye(1,1) zeros(1,3);0 2 -1 -1; 0 -1 2 -1; 0 -1 -1 2]+1e-6*eye(4,4);\nq1hat=diag([1 10 10 10])*q1hat;\nq2hat=eye(1,1);\n[kk,sric,ee]=lqr(aa,bb,q1hat,q2hat);\nk1=kk(1,1);\nko=kk(:,2:4);\nacl=[a-b*ko b;-k1*c zeros(1,1)];\nbcl=[zeros(3,1);k1];\nccl=[c zeros(1,1)];\ndcl=zeros(1,1);\n[ecl]=eig(acl);\n[zcl]=tzero(acl,bcl,ccl,dcl);\n%CL DC gain\n[cldcgain]=dcl-ccl*inv(acl)*bcl;\n%CL Step Response\n%[y,t]=step(acl,bcl,ccl,dcl);\n%s1y=plot(y(:,:,1));\n%grid;\n%pause;\n%Control effort\n%cclu=[-ko eye(1,1)];\n%dclu=[0];\n%[uu,t]=step(acl,bcl,cclu,dclu);\n%su=plot(uu(:,:,1));\n%grid;\n%pause\n%Step in all channels\n%t=0:.1:100;\n%u=[25*ones(1,251) 25*ones(1,500)0*ones(1,250)];\n%u10=[u'];\n%sysc1=ss(acl,bcl,ccl,dcl);\n%[yy1,t]=lsim(sysc1,u10,t);\n%plot(t,yy1)\n%grid\n%pause;\n%cclu=[-ko eye(1,1)];\n%dclu=[0];\n%syscl2=ss(acl,bcl,cclu,dclu);\n%[uu1,t]=lsim(syscl2,u10,t);\n%su=plot(uu1(:,:,1));\n%grid;\n%pause\n% Estimator design\nqe=eye(1,1);\nre=0.001*eye(1,1);\n[ll,pp,el]=lqe(a,b,c,qe,re);\nac=zeros(1,1);\nbc=-k1;\ncc=eye(1,1);\ndc=-ko;\nacle=[a, b*cc, -b*ko;\n bc*c, ac, zeros(1,3);\n ll*c, b*cc, a-ll*c-b*ko];\nbcle=[zeros(3,1);-bc;zeros(3,1)];\nccle=[c, zeros(1,4)];\ndcle=zeros(1,1);\n[ecle]=eig(acle);\n[zcle]=tzero(acle,bcle,ccle,dcle);\ndcgain=dcle-ccle*inv(acle)*bcle;\nt=0:.1:100;\nR=[0:.1:25, 25*ones(1,500), 0*ones(1,250)];\nR11=[R'];\nsyscl=ss(acle,bcle,ccle,dcle);\n[yy,t]=lsim(syscl,R11,t);\nplot(t,yy,'--');\ngrid on;\nhold on;\nplot(t,R11,'-');\nxlabel('Time (sec)');\nylabel('Temperature (K)');\ntitle('Fig. 10.70 (a) Internal model controller: temperature tracking response');\n%legend('y')\npause;\nhold off;\ncclu=[zeros(1,3), eye(1,1), -ko];\ndclu=zeros(1,1);\nsyscu=ss(acle,bcle,cclu,dclu);\n[uuu,t]=lsim(syscu,R11,t);\nplot(t(1:753,:),uuu(1:753,:));\nhold on;\nplot(t(752:818,:),0*ones(67,3));\nhold on;\nplot(t(753:818,:),uuu(753:818,:),'--');\nhold on;\nplot(t(819:1001,:),uuu(819:1001,:));\nxlabel('Time (sec)');\nylabel('Lamp voltage');\ntitle('Fig. 10.70 (b) Internal model controller: control effort');\nlegend('u')\ngrid;\nhold off;\n\n\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/9907-feedback-control-of-dynamic-systems-fifth-ed/fig10_70.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6914389879391115}} {"text": "function [qt1,qdt1,qddt1,time1] = interpola3(delta_t,qi,qf,t)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%INTERPOLADOR DE 3ER ORDEN\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\namax = 2; %rad/s/s\nwmax = 1; %rad/s\nt=[0 t];\n\nq=[qi qf];\n\n\n[qt1,qdt1,qddt1,time1,k1]=interpola3orden(q, [0 wmax], [0 amax], t, delta_t);\n\n\n\n\n\n\n\n\n\n\n\nfunction [q_t, qd_t, qdd_t, time, k]=interpola3orden(q, qd, qdd, t, delta_t)\n\nA=[1 t(1) t(1)^2 t(1)^3;\n 1 t(2) t(2)^2 t(2)^3;\n 0 1 2*t(1) 3*t(1)^2;\n 0 0 2 6*t(1)];\nk=inv(A)*[q(1) q(2) qd(1) qdd(1)]';\n\ntime=t(1):delta_t:t(2);\nq_t = k(1) + k(2)*time + k(3)*time.^2 + k(4)*time.^3;\nqd_t= k(2)*ones(1,length(time)) + 2*k(3)*time + 3*k(4)*time.^2;\nqdd_t=2*k(3)*ones(1,length(time)) + 6*k(4)*time;\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/demos/projects/two_robots_and_a_fruit_box/interpola3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361628580401, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6914389833702468}} {"text": "function [Recognized_index filename] = Recognition(Test_image, Mean, A, eigenfaces)\n\n\nProjectedImages = [];\nTrain_Number = size(eigenfaces,2);\nfor i = 1 : Train_Number\n temp = eigenfaces'*A(:,i); \n ProjectedImages = [ProjectedImages temp]; \nend\n\n% Extract the PCA features from test image\n\ntemp = Test_image;\n\n[irow icol] = size(temp);\nInImage = reshape(temp',irow*icol,1);\nDifference = double(InImage)-Mean; \nProjectedTestImage = eigenfaces'*Difference; \n\n% Calculate Euclidean distances \n% Test image is supposed to have minimum distance with its corresponding\n% image in the training database.\n\ndist = [];\nfor i = 1 : Train_Number\n q = ProjectedImages(:,i);\n temp = ( norm( ProjectedTestImage - q ) )^2;\n dist = [dist temp];\nend\n\n[dist_min , Recognized_index] = min(dist);\n\n filename=sprintf('s%d.1.tif', Recognized_index);\n disp(['matched image is ',filename]);\n \n \nsubplot(1,2,1); imshow(Test_image);\ntitle('Test Image');\nsubplot(1,2,2); imshow(filename);\ntitle('Matched Image')\n \n\nend\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u8bc6\u522b\u7b97\u6cd5/ImageRecognition-master/Recognition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6914389797614803}} {"text": "function y=PSNR_RGB(X,Y)\n \n% Y= PSNR_RGB(X,Y)\n% Computes the Peak Signal to Noise Ratio for two RGB images\n% Class input : double [0,1] ,\n% july ,25, 2012\n% KHMOU Youssef\n \n \n \nif size(X)~=size(Y)\n error('The images must have the same size');\nend\n \n%if ~isa(X,'double') \n% X=double(X)./255.00;\n%end\n%if ~isa(Y,'double')\n% Y=double(Y)./255.00;\n%end\n \n% begin\nd1=max(X(:));\nd2=max(Y(:));\nd=max(d2);\nsigma=mean2((X-Y).^2);\n \ny=10*log10((d.^2)./sigma);", "meta": {"author": "andrewssobral", "repo": "mctc4bmi", "sha": "fbcbcd25654b818646387c3d6a64304fb60e12dd", "save_path": "github-repos/MATLAB/andrewssobral-mctc4bmi", "path": "github-repos/MATLAB/andrewssobral-mctc4bmi/mctc4bmi-fbcbcd25654b818646387c3d6a64304fb60e12dd/algs_tc/BCPF/Evaluation/PSNR_RGB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6914389765748561}} {"text": "%THIS FUMCTION ILLUSTRATES HOW TO USE THE USER-DEFINED ALGORITHM\nfunction [AH,XH] = user_alg5(Y,r,X)\n%\n% The example of implementing the user-defined algorithm (this is the Lee-Seung algorithm based on the KL divergence)\n%\n% INPUTS:\n% Y - mixed signals (matrix of size [m by T])\n% r - number of estimated signals\n% X - true source signals\n%\n% OUTPUTS\n% AH - estimated mixing matrix (matrix of size [m by r])\n% XH - estimated source signals (matrix of size [r by T])\n%\n% #########################################################################\n% Initialization\n[m,T]=size(Y);\nY(Y <=0) = eps; % this enforces the positive value in the data \nAH=rand(m,r);\nXH=rand(r,T);\n\nIterNo = 1000; % number of alternating steps\n\n% Iterations\nfor k = 1:IterNo \n XH = XH.*(AH'*(Y./(AH*XH + eps)));\n AH = AH.*((Y./(AH*XH + eps))*XH')./repmat(sum(XH,2)',m,1);\n AH = AH*diag(1./(sum(AH,1) + eps));\nend\n \n \n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/NMFLABSP_ver1.2/user_alg5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391621868805, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6914368232574929}} {"text": "function M = shapefitfactory(VJt)\n% Linear manifold structure for optimization over the ShapeFit search space\n%\n% function M = shapefitfactory(VJt)\n%\n% Input: VJt is a matrix of size dxn, such that VJt * ones(n, 1) = 0.\n%\n% Returns M, a structure describing the Euclidean space of d-by-n matrices\n% equipped with the standard Frobenius distance and associated trace inner\n% product, as a manifold for Manopt. Matrices on M, denoted by T, have size\n% dxn and obey T*ones(n, 1) = 0 (centered columns) and = 1, where\n% = Trace(A' * B).\n%\n% See this paper: http://arxiv.org/abs/1506.01437\n% ShapeFit: Exact location recovery from corrupted pairwise directions, 2015\n% Paul Hand, Choongbum Lee, Vladislav Voroninski\n%\n% See also: shapefit_smoothed\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, June 18, 2015.\n% Contributors: \n% Change log: \n%\n% Jan. 25, 2017 (NB):\n% M.tangent = M.proj now, instead of being identity. This is notably\n% necessary so that checkgradient will pick up on gradients that do\n% not lie in the appropriate tangent space.\n%\n% Jan. 4, 2021 (NB):\n% Changes for compatibility with Octave 6.1.0.\n \n [d, n] = size(VJt);\n\n M.name = @() sprintf('ShapeFit space of size %d x %d', d, n);\n \n M.dim = @() d*n - d - 1;\n \n M.inner = @(x, d1, d2) d1(:).'*d2(:);\n \n M.norm = @(x, d) norm(d, 'fro');\n \n M.dist = @(x, y) norm(x-y, 'fro');\n \n M.typicaldist = @() sqrt(d*n);\n \n VJt_normed = VJt / norm(VJt, 'fro');\n M.proj = @(T, U) projection(U, VJt_normed);\n function PU = projection(U, VJt_normed)\n % Center the columns\n PU = bsxfun(@minus, U, mean(U, 2));\n % Remove component along VJt\n % Note: these two actions can be executed separately, without\n % interference, owing to VJt having centered columns itself.\n PU = PU - (VJt_normed(:)'*U(:))*VJt_normed;\n end\n \n M.egrad2rgrad = M.proj;\n \n M.ehess2rhess = @(x, eg, eh, d) projection(eh, VJt_normed);\n \n M.tangent = M.proj;\n \n M.exp = @exp;\n function y = exp(x, d, t)\n if nargin == 3\n y = x + t*d;\n else\n y = x + d;\n end\n end\n \n M.retr = M.exp;\n \n M.log = @(x, y) y-x;\n\n M.hash = @(x) ['z' hashmd5(x(:))];\n \n M.randvec = @(x) randvec(VJt, VJt_normed);\n function u = randvec(VJt, VJt_normed)\n u = projection(randn(size(VJt)), VJt_normed);\n u = u / norm(u, 'fro');\n end\n \n % We exploit the fact that VJt_normed belongs to the manifold\n M.rand = @() VJt_normed + randn(1) * randvec(VJt, VJt_normed);\n \n M.lincomb = @matrixlincomb;\n \n M.zerovec = @(x) zeros(d, n);\n \n M.transp = @(x1, x2, d) d;\n \n M.pairmean = @(x1, x2) .5*(x1+x2);\n \n M.vec = @(x, u_mat) u_mat(:);\n M.mat = @(x, u_vec) reshape(u_vec, [d, n]);\n M.vecmatareisometries = @() true;\n\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/euclidean/shapefitfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6913913444078488}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% demo script for surface smoothing\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% preparation\n% user must add the path of iso2mesh to matlab path list\n% addpath('../');\n\n% user need to add the full path to .../iso2mesh/bin directory\n% to windows/Linux/Unix PATH environment variable\n\n%% load the sample data\nload rat_head.mat\n\n% volimage is a volumetric image such as an X-ray or MRI image\n% A,b are registration matrix and vector, respectively\n%% perform mesh generation\n\n[node,face]=v2s(volimage,0.5,2,'cgalmesh');\n\nface=face(:,1:3);\n\np0=min(node);\np1=max(node);\n\nrownum=3;\ncolnum=4;\nfigure;\nsubplot(rownum,colnum,1);\n\nplotmesh(node,face(:,1:3));\nif(~isoctavemesh) \n\ttitle({'Laplacian+HC Smoothing Test','no smoothing'}); \nelse\n\ttitle('Laplacian+HC - no smoothing');\nend\naxis equal;\nset(gca,'xlim',[p0(1),p1(1)],'ylim',[p0(2),p1(2)],'zlim',[p0(3),p1(3)])\n\n%=========================================================\n% apply Laplacian+HC smoothing\n%=========================================================\n\nn1=node;\nfor i=1:rownum*colnum-1\n n1=sms(n1,face(:,1:3),1,0.5); % apply Laplacian+HC mesh smoothing\n subplot(rownum,colnum,i+1);\n plotmesh(n1,face(:,1:3));\n title(['iter=' num2str(i)]);\n axis equal;\n set(gca,'xlim',[p0(1),p1(1)],'ylim',[p0(2),p1(2)],'zlim',[p0(3),p1(3)])\nend\n\n%=========================================================\n% apply Laplacian smoothing\n%=========================================================\n\nfigure;\nsubplot(rownum,colnum,1);\n\nplotmesh(node,face(:,1:3));\nif(~isoctavemesh)\n title({'Laplacian Smoothing Test','no smoothing'});\nelse\n title('Laplacian - no smoothing');\nend\naxis equal;\nset(gca,'xlim',[p0(1),p1(1)],'ylim',[p0(2),p1(2)],'zlim',[p0(3),p1(3)])\n\nconn=meshconn(face(:,1:3),size(node,1));\n\nn1=node;\nfor i=1:rownum*colnum-1\n n1=smoothsurf(n1,[],conn,1,0.5,'laplacian');\n subplot(rownum,colnum,i+1);\n plotmesh(n1,face(:,1:3));\n title(['iter=' num2str(i)]);\n axis equal;\n set(gca,'xlim',[p0(1),p1(1)],'ylim',[p0(2),p1(2)],'zlim',[p0(3),p1(3)])\nend\n\n\n%=========================================================\n% apply Low-pass smoothing\n%=========================================================\n\nfigure;\nsubplot(rownum,colnum,1);\n\nplotmesh(node,face(:,1:3));\nif(~isoctavemesh)\n title({'Low-pass Smoothing Test','no smoothing'});\nelse\n title('Low-pass - no smoothing');\nend\naxis equal;\nset(gca,'xlim',[p0(1),p1(1)],'ylim',[p0(2),p1(2)],'zlim',[p0(3),p1(3)])\n\nconn=meshconn(face(:,1:3),size(node,1));\n\nn1=node;\nfor i=1:rownum*colnum-1\n n1=smoothsurf(n1,[],conn,1,0.5,'lowpass');\n subplot(rownum,colnum,i+1);\n plotmesh(n1,face(:,1:3));\n title(['iter=' num2str(i)]);\n axis equal;\n set(gca,'xlim',[p0(1),p1(1)],'ylim',[p0(2),p1(2)],'zlim',[p0(3),p1(3)])\nend\n\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/Iso2meshToolbox/sample/demo_mesh_smoothing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.7879311881731379, "lm_q1q2_score": 0.6913913277549149}} {"text": "function psi_test ( )\n\n%*****************************************************************************80\n%\n%% PSI_TEST tests R4_PSI and R8_PSI.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2011\n%\n% Author:\n%\n% John Burkardt\n%\n addpath ( '../test_values' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PSI_TEST:\\n' );\n fprintf ( 1, ' Test PSI_VALUES, R4_PSI, R8_PSI.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X PSI(X)\\n' );\n fprintf ( 1, ' R4_PSI(X) Diff\\n' );\n fprintf ( 1, ' R8_PSI(X) Diff\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, x, fx1 ] = psi_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fx2 = r4_psi ( single ( x ) );\n fx3 = r8_psi ( x );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' %14.4f %14.6g\\n', x, fx1 );\n fprintf ( 1, ' %14.6g %14.6g\\n', fx2, abs ( fx1 - fx2 ) );\n fprintf ( 1, ' %14.6g %14.6g\\n', fx3, abs ( fx1 - fx3 ) );\n\n end\n\n rmpath ( '../test_values' );\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/fn/psi_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.8633916011860785, "lm_q1q2_score": 0.6913107579590649}} {"text": "function varargout = gradientFD(f, dn, dim, deriv_order, accuracy_order)\n%GRADIENTFD Calculate the gradient using a finite-difference method.\n%\n% DESCRIPTION:\n% gradientFD calculates the gradient of an n-dimensional input matrix\n% using the finite-difference method. For one-dimensional inputs, the\n% gradient is always computed along the non-singleton dimension. For\n% higher dimensional inputs, the gradient for singleton dimensions is\n% returned as 0. For elements in the centre of the grid, the gradient\n% is computed using centered finite-differences. For elements on the\n% edge of the grid, the gradient is computed using forward or\n% backward finite-differences. The order of accuracy of the\n% finite-difference approximation is controlled by accuracy_order\n% (default = 2). The calculations are done using sparse\n% multiplication, so the input matrix is always cast to double\n% precision. \n%\n% USAGE:\n% fx = gradientFD(f, dx)\n% fx = gradientFD(f, dx, [], deriv_order)\n% fx = gradientFD(f, dx, [], deriv_order, accuracy_order)\n% fn = gradientFD(f, dn, dim)\n% fn = gradientFD(f, dn, dim, deriv_order, accuracy_order)\n% [fx, fy] = gradientFD(f, dn)\n% [fx, fy] = gradientFD(f, dn, [], deriv_order, accuracy_order)\n% [fx, fy, fz, ...] = gradientFD(f, dn)\n% [fx, fy, fz, ...] = gradientFD(f, dn, [], deriv_order, accuracy_order)\n%\n% INPUTS:\n% f - matrix or vector to find the gradient of\n% dn - array of values for the grid point spacing in each\n% dimension. If a value for dim is given, dn is the\n% spacing in dimension dim.\n% \n% OPTIONAL INPUTS:\n% dim - optional input to specify a single dimension over\n% which to compute the gradient for n-dimension\n% input functions\n% deriv_order - order of the derivative to compute, e.g., use 1\n% to compute df/dx, 2 to compute df^2/dx^2, etc. \n% (default = 1)\n% accuracy_order - order of accuracy for the finite difference\n% coefficients. Because centered differences are\n% used, this must be set to an integer multiple of\n% 2 (default = 2)\n% \n% OUTPUTS:\n% fx, fy, ... - gradient in the each dimension, where x corresponds\n% to dim = 1, y corresponds to dim = 2 etc \n% \n% ABOUT:\n% author - Bradley Treeby\n% date - 24th August 2012\n% last update - 3rd September 2012\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 getFDMatrix, gradient, gradientSpect\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% % display warning if input is not double precision\n% if ~isa(f, 'double')\n% disp('gradientFD: converting input to double precision');\n% end\n\n% force input to be in double precision (sparse operations are only\n% supported in double or logical formats)\nf = double(f);\n\n% get size of the input function\nsz = size(f);\n\n% check dimension of input\nf_dims = numDim(f);\n\n% check for user input for accuracy_order\nif nargin < 5 || isempty(accuracy_order)\n accuracy_order = 2;\nelseif rem(accuracy_order, 2)\n error('Input for accuracy_order must be an integer multiple of 2');\nend\n\n% check for user input for deriv_order\nif nargin < 4 || isempty(deriv_order)\n deriv_order = 1;\nelseif ~((deriv_order > 0) && (deriv_order == round(deriv_order)))\n error('Input for deriv_order must be an integer > 0');\nend\n\n% check for user input for dim\nif (nargin < 3) || isempty(dim)\n \n % check if input is 1D\n if f_dims == 1\n % only compute gradient over required dimension\n if sz(1) == 1\n dim_array = 2;\n else\n dim_array = 1;\n end\n else\n % otherwise compute gradient over all dimensions\n dim = 0;\n dim_array = 1:f_dims;\n \n % check for the correct number of dn values\n if length(dn) ~= length(sz)\n error([num2str(length(sz)) ' values for dn must be specified for a ' num2str(length(sz)) '-dimensional input matrix']);\n end\n end\nelse\n dim_array = dim;\nend\n\n% only allow 1, 2, or 3D inputs (only these cases are implemented)\nif f_dims > 3\n error('Input for f must have 1, 2, or 3 dimensions');\nend\n\n% if input is 1D, only allow it to be a row or column vector\nif (f_dims == 1) && (length(sz) > 2)\n error('1D inputs for f must be row or column vectors');\nend\n\n% if input is 2D, only allow it to be a regular matrix\nif (f_dims == 2) && (length(sz) > 2)\n error('2D inputs for f must be of size m x n');\nend\n\n% if input is 2D or 3D, check dim input isn't bigger than the matrix size\nif (f_dims > 1) && (dim > f_dims)\n error('Input for dim cannot be greater than the number of dimensions of f');\nend\n\n% set output argument index\nargout_index = 1;\n\n% loop through required dimensions\nfor dim_index = dim_array\n\n % set dimension\n dim = dim_index;\n \n % check if a single dn value is given, if not, extract the required\n % value\n if numel(dn) ~= 1\n dn_val = dn(dim);\n else\n dn_val = dn;\n end\n \n % get the grid size along the specified dimension, or the longest\n % dimension if 1D\n if nargout == 1 && (max(sz) == prod(sz))\n [Nx, dim] = max(sz);\n else\n Nx = sz(dim);\n end\n \n % get the finite-difference matrix\n FDM = getFDMatrix(Nx, dn_val, deriv_order, accuracy_order);\n \n % compute derivatives of 1D or 2D matrix\n if ndims(f) < 3 \n switch dim\n\n % derivative along dimension 1 (columns)\n case 1\n varargout{argout_index} = FDM * f;\n\n % derivative along dimension 2 (rows)\n case 2\n varargout{argout_index} = f * FDM.';\n\n end\n\n % compute derivatives of 3D matrix \n else\n switch dim\n\n % derivative along dimension 1\n case 1\n\n % preallocate output matrix\n varargout{argout_index} = zeros(size(f));\n\n % loop through z-plane\n for dim3_index = 1:sz(3)\n varargout{argout_index}(:, :, dim3_index) = FDM * f(:, :, dim3_index);\n end\n\n % derivative along dimension 2\n case 2\n\n % preallocate output matrix\n varargout{argout_index} = zeros(size(f));\n\n % rotate FDM\n FDM = FDM.';\n\n % loop through z-plane\n for dim3_index = 1:sz(3)\n varargout{argout_index}(:, :, dim3_index) = f(:, :, dim3_index) * FDM;\n end\n\n % derivative along dimension 3 \n case 3\n\n % preallocate output matrix\n varargout{argout_index} = zeros(size(f));\n\n % rotate FDM\n FDM = FDM.';\n\n % loop through x-plane\n for dim1_index = 1:sz(1)\n varargout{argout_index}(dim1_index, :, :) = squeeze(f(dim1_index, :, :)) * FDM;\n end\n\n end\n \n end\n \n % increment output argument index\n argout_index = argout_index + 1;\n \nend\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/K-wave/k-Wave/gradientFD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.6913107562523354}} {"text": "% VL_IMINTEGRAL Compute integral image\n% J = VL_IMINTEGRAL(I) calculates the integral image J of the image\n% I. I must a matrix with DOUBLE, SINGLE, UINT32, or INT32 storage\n% class. J is given by\n%\n% J(i,j) = sum(I(1:i,1:j)).\n%\n% J has the same size as I and the same storage class.\n%\n% Example::\n% The following identity holds:\n% VL_IMINTEGRAL(ONES(3)) = [ 1 2 3 ;\n% 2 4 6 ;\n% 3 6 9 ]\n%\n% See also: VL_HELP().\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n", "meta": {"author": "yihui-he", "repo": "panorama", "sha": "0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b", "save_path": "github-repos/MATLAB/yihui-he-panorama", "path": "github-repos/MATLAB/yihui-he-panorama/panorama-0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b/lib/vlfeat-0.9.20/toolbox/imop/vl_imintegral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.6912890665606178}} {"text": "% Modelling Power Law Absorption Example\n%\n% This example describes the characteristics of the absorption and\n% dispersion encapsulated by the k-Wave simulation functions\n%\n% For a more detailed discussion of the absorption model used in k-Wave,\n% see Treeby, B. E. and Cox, B. T., \"Modeling power law absorption and\n% dispersion for acoustic propagation using the fractional Laplacian,\" J.\n% Acoust. Soc. Am., vol. 127, no. 5, pp. 2741-2748, 2010.\n%\n% author: Bradley Treeby\n% date: 4th February 2011\n% last update: 24th August 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% 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\nclear all;\n\n% modify this parameter to run the different examples\nexample_number = 1;\n% 1: Simulation using kspaceSecondOrder \n% 2: Simulation using kspaceFirstOrder1D with default CFL\n% 3: Simulation using kspaceFirstOrder1D with CFL = 0.05\n\n% =========================================================================\n% SIMULATION\n% =========================================================================\n\n% create the computational grid\nNx = 1024; % number of grid points in the x (row) direction\nx = 12.8e-3; % grid size in the x direction [m]\ndx = x/Nx; % grid point spacing in the x direction [m]\nkgrid = makeGrid(Nx, dx);\n\n% define the properties of the propagation medium\nmedium.sound_speed = 1500; % [m/s]\n\n% define time array\nt_end = 4e-6;\nif example_number < 3\n [kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed, [], t_end);\nelse\n [kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed, 0.05, t_end);\nend\n\n% create a spatial delta pulse\nsource_pos = Nx/4; % [grid points]\nsource.p0 = zeros(Nx, 1);\nsource.p0(source_pos) = 1;\n\n% define the sensor positions\nsource_sensor_dist = 0.5e-3; % [m]\nsensor_sensor_dist = 1e-3; % [m]\nsensor_pos_1 = source_pos + round(source_sensor_dist/dx);\nsensor_pos_2 = source_pos + round((source_sensor_dist + sensor_sensor_dist)/dx);\n\n% calculate discrete distance between the sensor positions\nd = (sensor_pos_2 - sensor_pos_1)*dx; % [m]\nd_cm = d*100;\n\n% index where the relative dispersion is defined\nf_index = 30;\n\n% create a Binary sensor mask\nsensor.mask = zeros(Nx, 1);\nsensor.mask(sensor_pos_1) = 1;\nsensor.mask(sensor_pos_2) = 1;\n\n% preallocate the storage variables\nattenuation = zeros(3, floor(length(kgrid.t_array)/2) + 1);\nattenuation_th = zeros(3, floor(length(kgrid.t_array)/2) + 1);\ncp = zeros(3, floor(length(kgrid.t_array)/2) + 1);\ncp_kk = zeros(3, floor(length(kgrid.t_array)/2) + 1);\n\nfor loop = 1:3\n\n % define the absorption properties of the propagation medium\n switch loop\n case 1\n medium.alpha_coeff = 0.5;\n medium.alpha_power = 1.1;\n case 2 \n medium.alpha_coeff = 0.25;\n medium.alpha_power = 1.5;\n case 3 \n medium.alpha_coeff = 0.1;\n medium.alpha_power = 1.9;\n end\n\n % run the simulation without visualisation\n if example_number == 1\n sensor_data = kspaceSecondOrder(kgrid, medium, source, sensor, 'PlotSim', false); \n else\n sensor_data = kspaceFirstOrder1D(kgrid, medium, source, sensor, 'PlotSim', false);\n end\n \n % calculate the amplitude and phase spectrum at the two sensor\n % positions\n [f, as1, ps1] = spect(sensor_data(1, :), 1/dt);\n [f, as2, ps2] = spect(sensor_data(2, :), 1/dt);\n \n % calculate the attenuation from the amplitude spectrums\n attenuation(loop, :) = -20*log10(as2./as1)./d_cm;\n \n % calculate the corresponding theoretical attenuation in dB/cm\n attenuation_th(loop, :) = medium.alpha_coeff.*(f./1e6).^medium.alpha_power;\n \n % calculate the dispersion (dependence of the sound speed on frequency)\n % from the phase spectrums\n cp(loop, :) = 2*pi.*f.*d./(unwrap(ps1) - unwrap(ps2));\n \n % calculate the corresponding theoretical dispersion using the\n % Kramers-Kronig relation for power law absorption\n cp_kk(loop, :) = powerLawKramersKronig(2*pi*f, 2*pi*f(f_index), cp(loop, f_index), db2neper(medium.alpha_coeff, medium.alpha_power), medium.alpha_power);\nend\n\n% =========================================================================\n% VISUALISATION\n% =========================================================================\n\n% set downsampling factor so there is sufficient space between plot markers\nds = 8;\n\n% plot the attenuation\nfigure;\nf_max = 50;\nplot(f(1:ds:end)./1e6, attenuation(:, 1:ds:end), 'ko', f./1e6, attenuation_th, 'k-');\nset(gca, 'XLim', [0 f_max]);\nbox on;\nxlabel('Frequency [MHz]');\nylabel('\\alpha [dB/cm]');\n\n% label the plots\ntext(40, 160, 'y = 1.9');\ntext(40, 90, 'y = 1.5');\ntext(40, 40, 'y = 1.1');\n\n% plot the dispersion\nfigure\nplot(f(1:ds:end)./1e6, cp(:, 1:ds:end), 'ko', f./1e6, cp_kk, 'k-');\nset(gca, 'XLim', [0 f_max]);\nbox on;\nxlabel('Frequency [MHz]');\nylabel('C_p [m/s]');\n\n% label the plots\ntext(40, 1517, 'y = 1.1');\ntext(40, 1509, 'y = 1.5');\ntext(40, 1500, 'y = 1.9');", "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/examples/example_na_modelling_absorption.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6912890620656689}} {"text": "function determ = rectangle_adj_determinant ( row_num, col_num )\n\n%*****************************************************************************80\n%\n%% RECTANGLE_ADJ_DETERMINANT returns the determinant of the RECTANGLE_ADJ matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer ROW_NUM, COL_NUM, the number of rows and\n% columns in the rectangle.\n%\n% Output, real DETERM, the determinant.\n%\n\n%\n% If ROW_NUM == 1 or COL_NUM == 1 we have a case of the LINE_ADJ matrix.\n%\n if ( row_num == 1 )\n\n if ( mod ( row_num, 4 ) == 1 )\n determ = 0.0;\n elseif ( mod ( row_num, 4 ) == 2 )\n determ = - 1.0;\n elseif ( mod ( row_num, 4 ) == 3 )\n determ = 0.0;\n elseif ( mod ( row_num, 4 ) == 0 )\n determ = + 1.0;\n end\n\n elseif ( col_num == 1 )\n\n if ( mod ( col_num, 4 ) == 1 )\n determ = 0.0;\n elseif ( mod ( col_num, 4 ) == 2 )\n determ = - 1.0;\n elseif ( mod ( col_num, 4 ) == 3 )\n determ = 0.0;\n elseif ( mod ( col_num, 4 ) == 0 )\n determ = + 1.0;\n end\n%\n% Otherwise, we can form at least one square, hence a null vector,\n% hence the matrix is singular.\n%\n else\n\n determ = 0.0;\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/test_mat/rectangle_adj_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.6912890533608631}} {"text": "function [dWx,dWy] = vl_dwaffine(x,y)\n% VL_DWAFFINE Derivative of an affine warp\n% [DWX,DWY]=VL_DWAFFINE(X,Y) returns the derivative of the 2-D affine\n% warp [WX; WY] = [A T] [X; Y] with respect to the parameters A,T\n% computed at points X,Y.\n%\n% See also: VL_WAFFINE(), VL_HELP().\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\n% dW = [ kron(x',I) I ]\n% |\n% = [ x1 0 x2 0 1 0 ]\n% [ 0 x1 0 x2 0 1 ]\n\nz = zeros(length(x(:)),1) ;\no = ones(length(x(:)),1) ;\n\ndWx = [ x(:) z y(:) z o z ] ;\ndWy = [ z x(:) z y(:) z o ] ;\n", "meta": {"author": "yihui-he", "repo": "panorama", "sha": "0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b", "save_path": "github-repos/MATLAB/yihui-he-panorama", "path": "github-repos/MATLAB/yihui-he-panorama/panorama-0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b/lib/vlfeat-0.9.20/toolbox/imop/vl_dwaffine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.691140796336221}} {"text": "% Propagation of uncertainty as in Atlas\n% Propagating uncertainty from node to node using relative motion.\n%\n%\nfunction propagation_of_uncertainty_example\nclose all\n\nposes = [0 0 0;\n 10 0 0;\n 10 10 pi/2;\n 10 20 pi/2;\n 0 20 pi;\n 0 10 -pi/2;\n -10 -10 0];\nn = 7\n% figure, hold on\n% plot(poses(:, 1), poses(:, 2), 'o')\n\nS00 = diag([0.0 0.0 0.0])\nsigmas = {}\nsigmas{1} = S00\nS = S00\nfor i=1:n-1\n S = propagate_uncertainty(poses(i, :), poses(i+1, :) , S)\n sigmas{i+1} = S;\nend\n\n% axis equal, hold on\n% for i=1:n\n% plot_error_ellipse(poses(i,1:2), sigmas{i}(1:2, 1:2), 0.99)\n% end\n\nM = 500;\nsamples = zeros(M, 3);\nsets = {};\nsets{1} = samples;\nfor i=1:n-1\n samples = propagate_uncertainty_sampled(poses(i, :), poses(i+1, :) , samples);\n sets{i+1} = samples;\nend\n\n% plot everything\nfigure, hold on\nplot(poses(:, 1), poses(:, 2), 'o')\naxis equal, hold on\nfor i=1:n\n plot_error_ellipse(poses(i,1:2), sigmas{i}(1:2, 1:2), 0.99)\n plot(sets{i}(:,1), sets{i}(:,2), '.')\nend\n\n\n\nfunction Sres=propagate_uncertainty(posea, poseb, Si)\n\nSij = diag([0.1, 0.01, 0.001]);\nTi = T(posea(1), posea(2), posea(3));\nTj = T(poseb(1), poseb(2), poseb(3));\nTij = inv(Ti)*Tj;\nxij = Tij(1,4);\nyij = Tij(2,4);\nthij = atan2(Tij(2,1), Tij(1,1));\n\n[J1, J2] = Jacobians(posea(1), posea(2), posea(3), xij, yij, thij);\n\nSres = J1*Si*J1' + J2*Sij*J2';\n\n\nfunction Set=propagate_uncertainty_sampled(ti, tj, Set)\n\nSjk = diag([0.1, 0.01, 0.001]);\nSjk = sqrt(Sjk);\nTi = T(ti(1), ti(2), ti(3));\nTj = T(tj(1), tj(2), tj(3));\nTij = inv(Ti)*Tj;\ntij = t2v(Tij);\nxij = tij(1);\nyij = tij(2);\nthij = tij(3);\n\nfor i=1:length(Set)\n xis = Set(i,1);\n yis = Set(i,2);\n this = Set(i, 3);\n Tis = T(xis, yis, this);\n % sample-based error propagation, add noise\n tx = xij + normrnd(0, Sjk(1,1));\n ty = yij + normrnd(0, Sjk(2,2));\n th = thij + normrnd(0, Sjk(3,3));\n Tijs = T(tx, ty, th);\n Tjs = Tis*Tijs;\n Set(i, :)= t2v(Tjs);\nend\n\n\n\n\nfunction A = T(x, y, th)\n\ncth = cos(th);\nsth = sin(th);\n\nA=[cth -sth 0 x;\n sth cth 0 y;\n 0 0 1 0;\n 0 0 0 1];\n\nfunction t = t2v(T)\nx = T(1,4);\ny = T(2,4);\nth = atan2(T(2,1), T(1,1));\nt = [x, y, th];\n\n\nfunction [J1, J2] = Jacobians(xi, yi, thi, xij, yij, thij)\n\nci = cos(thi);\nsi = sin(thi);\n\nJ1=[1 0 -si*xij-ci*yij;\n 0 1 ci*xij-si*yij; \n 0 0 1];\n\nJ2=[ci -si 0;\n si ci 0; \n 0 0 1];\n\n\nfunction plot_error_ellipse(mu, Sigma, p)\ns = -2 * log(1 - p);\n[V, D] = eig(Sigma * s);\nt = linspace(0, 2 * pi, 50);\na = (V * sqrt(D)) * [cos(t(:))'; sin(t(:))'];\nplot(a(1, :) + mu(1), a(2, :) + mu(2));\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/exercises/book/propagation_of_uncertainty_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6911407895239468}} {"text": "function [D,P] = dijk(A,s,t)\n%DIJK Shortest paths from nodes 's' to nodes 't' using Dijkstra algorithm.\n% D = dijk(A,s,t)\n% A = n x n node-node weighted adjacency matrix of arc lengths\n% (Note: A(i,j) = 0 => Arc (i,j) does not exist;\n% A(i,j) = NaN => Arc (i,j) exists with 0 weight)\n% s = FROM node indices\n% = [] (default), paths from all nodes\n% t = TO node indices\n% = [] (default), paths to all nodes\n% D = |s| x |t| matrix of shortest path distances from 's' to 't'\n% = [D(i,j)], where D(i,j) = distance from node 'i' to node 'j' \n%\n%\t(If A is a triangular matrix, then computationally intensive node\n% selection step not needed since graph is acyclic (triangularity is a \n% sufficient, but not a necessary, condition for a graph to be acyclic)\n% and A can have non-negative elements)\n%\n%\t(If |s| >> |t|, then DIJK is faster if DIJK(A',t,s) used, where D is now\n% transposed and P now represents successor indices)\n%\n% (Based on Fig. 4.6 in Ahuja, Magnanti, and Orlin, Network Flows,\n% Prentice-Hall, 1993, p. 109.)\n\n% Copyright (c) 1998-2000 by Michael G. Kay\n% Matlog Version 1.3 29-Aug-2000\n% \n% Modified by JBT, Dec 2000, to delete paths\n\n% Input Error Checking ******************************************************\nerror(nargchk(1,3,nargin));\n\n[n,cA] = size(A);\n\nif nargin < 2 | isempty(s), s = (1:n)'; else s = s(:); end\nif nargin < 3 | isempty(t), t = (1:n)'; else t = t(:); end\n\nif ~any(any(tril(A) ~= 0))\t\t\t% A is upper triangular\n isAcyclic = 1;\nelseif ~any(any(triu(A) ~= 0))\t% A is lower triangular\n isAcyclic = 2;\nelse\t\t\t\t\t\t\t\t\t\t% Graph may not be acyclic\n isAcyclic = 0;\nend\n\nif n ~= cA\n error('A must be a square matrix');\nelseif ~isAcyclic & any(any(A < 0))\n error('A must be non-negative');\nelseif any(s < 1 | s > n)\n error(['''s'' must be an integer between 1 and ',num2str(n)]);\nelseif any(t < 1 | t > n)\n error(['''t'' must be an integer between 1 and ',num2str(n)]);\nend\n% End (Input Error Checking) ************************************************\n\nA = A';\t\t% Use transpose to speed-up FIND for sparse A\n\nD = zeros(length(s),length(t));\nP = zeros(length(s),n);\n\nfor i = 1:length(s)\n j = s(i);\n \n Di = Inf*ones(n,1); Di(j) = 0;\n \n isLab = logical(zeros(length(t),1));\n if isAcyclic == 1\n nLab = j - 1;\n elseif isAcyclic == 2\n nLab = n - j;\n else\n nLab = 0;\n UnLab = 1:n;\n isUnLab = logical(ones(n,1));\n end\n \n while nLab < n & ~all(isLab)\n if isAcyclic\n Dj = Di(j);\n else\t% Node selection\n [Dj,jj] = min(Di(isUnLab));\n j = UnLab(jj);\n UnLab(jj) = [];\n isUnLab(j) = 0;\n end\n \n nLab = nLab + 1;\n if length(t) < n, isLab = isLab | (j == t); end\n \n [jA,kA,Aj] = find(A(:,j));\n Aj(isnan(Aj)) = 0;\n \n if isempty(Aj), Dk = Inf; else Dk = Dj + Aj; end\n \n P(i,jA(Dk < Di(jA))) = j;\n Di(jA) = min(Di(jA),Dk);\n \n if isAcyclic == 1\t\t\t% Increment node index for upper triangular A\n j = j + 1;\n elseif isAcyclic == 2\t% Decrement node index for lower triangular A\n j = j - 1;\n end\n \n %disp( num2str( nLab ));\n end\n D(i,:) = Di(t)';\nend\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/dijk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6911360830125596}} {"text": "%% testinitWeighted.m\n\n% This test file implements the Weighted initializer. The code builds\n% a synthetic formulation of the Phase Retrieval problem, b = |Ax| and\n% computes an estimate to x. The code finally outputs the correlation\n% achieved.\n\n% PAPER TITLE:\n% Solving Almost all Systems of Random Quadratic Equations.\n\n% ARXIV LINK:\n% https://arxiv.org/pdf/1705.10407.pdf\n\n\n\n% This is a test script for the weighted initializer. \n\n% 1.) Each test script for an initializer starts out by defining the length\n% of the unknown signal, n and the number of measurements, m. These\n% mesurements can be complex by setting the isComplex flag to be true.\n\n% 2.) We then build the test problem by generating random gaussian\n% measurements and using b0 = abs(Ax) where A is the measurement matrix.\n\n% 3.) We run x0 = initSpectral(A,[],b0,n,isTruncated,isScaled) which runs\n% the initialier and and recovers the test vector with high correlation. \n\n\n% PhasePack by Rohan Chandra, Ziyuan Zhong, Justin Hontz, Val McCulloch,\n% Christoph Studer, & Tom Goldstein \n% Copyright (c) University of Maryland, 2017\n\n\n%% ---------------------------------START-----------------------------\n\n\nclc\nclear\nclose all\n\n% Parameters\nn = 500; % number of unknowns\nm = 20*n; % number of measurements\nisComplex = true; % use complex matrices? or just stick to real?\n\n% Build the test problem\nxt = randn(n,1)+isComplex*randn(n,1)*1i; % true solution\nA = randn(m,n)+isComplex*randn(m,n)*1i; % matrix\nb0 = abs(A*xt); % data\n\n% Invoke the truncated spectral initial method\nx0 = initWeighted(A,[],b0,n);\n\n% Calculate the correlation between the recovered signal and the true signal\ncorrelation = abs(x0'*xt/norm(x0)/norm(xt));\n\nfprintf('correlation: %f\\n', correlation);", "meta": {"author": "tomgoldstein", "repo": "phasepack-matlab", "sha": "aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9", "save_path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab", "path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab/phasepack-matlab-aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9/examples/runInitWeighted.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6911360817657619}} {"text": "function derivativeVector = helmholtzHelper(inputVector, q, alpha)\n%Generates the helmholtz derivative vector for forward/backward convolving.\n%\n%helmholtzHelper takes a row or column input vector and a float, q, that is\n%the order of the derivative to be taken, and generates a shifted operator\n%operator that is modified for the Helmholtz equation. The vector returned\n%is the equivalent of [I - A] where A is the operator.\n\n %Generates the derivative operator vector.\n [step, lowerBound, upperBound] = defaultBoundaries(numel(inputVector));\n derivativeVector = -additiveConvolutionVector(step, lowerBound, ...\n upperBound, q);\n\n %Undoes a derivative.\n derivativeVector = helmholtzModifier(derivativeVector, alpha);\n derivativeVector = shiftOperator(derivativeVector);\n\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/38956-nonrigid-image-registration-with-fractional-differential-equations/fractionalRegistration/private/helmholtzHelper.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7662936484231888, "lm_q1q2_score": 0.6911360817657618}} {"text": "function W = compute_point_weight(pts, type, rings, options)\n\n% compute_point_weight - compute a weight matrix\n%\n% W = compute_point_weight(pts, type, rings, options);\n%\n% W is sparse weight matrix and W(i,j)=0 is vertex i and vertex j are not\n% connected.\n%\n% type is either \n% 'combinatorial': W(i,j)=1 is vertex i is conntected to vertex j.\n% 'distance': W(i,j) = 1/d_ij^2 where d_ij is distance between vertex\n% i and j.\n% 'spring': W(i,j) = 1/d_ij where d_ij is distance between vertex\n% i and j.\n% 'conformal' or 'dcp': W(i,j) = cot(alpha_ij)+cot(beta_ij) where alpha_ij and\n% beta_ij are the adjacent angle to edge (i,j). Refer to Skeleton\n% Extraction by Mesh Extraction_08, and Intrinsic Parameterizations of Surface Meshes_02.\n% 'Laplace-Beltrami': W(i,j) = (cot(alpha_ij)+cot(beta_ij))/2 where alpha_ij and\n% beta_ij are the adjacent angle to edge (i,j). Refer to Computing discrete minimal surfaces\n% andtheir conjugates_93, Lemma 2 of On the convergence of metric and geometric properties of\n% polyhedral surfaces_06, and Characterizing Shape Using\n% Conformal Factors_08, and ,\n% 'mvc': W(i,j) = [tan(/_kij/2)+tan(/_jil/2)]/d_ij where /_kij and /_jil\n% are angles at i\n%\n% If options.normalize=1, the the rows of W are normalize to sum to 1.\n% If M.ring is offered, we can avoid compute it.\n% \n% NB: we adapt it for better numeric stablity for contracting a model by adding the following lines\n% tmp = sum(W(i,:));\n% if tmp>10000\n% W(i,:) = W(i,:)*10000/tmp;\n% end\n% Copyright (c) 2009 jjcao\noptions.null = 0;\n\nif nargin<2\n type = 'conformal';\nend\n \nswitch lower(type)\n case 'combinatorial'\n W = compute_point_weight_combinatorial(pts, rings);\n case 'distance'\n warning('not implemented!'); \n case 'spring'\n W = compute_point_weight_spring(pts, rings); \n case {'conformal','dcp'} % conformal laplacian \n W = compute_point_weight_dcp(pts, rings);\n case 'laplace-beltrami' %\n W = compute_point_weight_dcp(pts, rings)*0.5;\n case 'mvc'% mvc laplacian\n W = compute_point_weight_mvc(pts, rings); \n otherwise\n error('Unknown type!!')\nend\n\n%#########################################################################\nfunction W = compute_point_weight_combinatorial(points, rings)\nn = length(points);\nW = sparse(n,n);\nfor i = 1:n\n ring = rings{i};\n if ring(1) == ring(end)\n ring = ring(1,1:(end-1));\n end\n for j = ring\n W(i,j) = 1.0;\n end\nend\nfunction W = compute_point_weight_spring(points, rings)\nn = length(points);\nW = sparse(n,n);\nfor i = 1:n\n vi = points(i,:);\n ring = rings{i};\n if ring(1) == ring(end)\n ring = ring(1,1:(end-1));\n end\n for j = ring \n vj = points(j,:); \n W(i,j) = 1./sqrt(sum((vi-vj).^2));\n end\n tmp = sum(W(i,:));\n if tmp>10000\n W(i,:) = W(i,:)*10000/tmp;\n end\nend\n%#########################################################################\nfunction W = compute_point_weight_dcp(points, rings)\nn = length(points);\nW = sparse(n,n);\nfor i = 1:n\n ring = rings{i};\n\n tmp = size(ring,2)-1;\n for ii = 1: tmp\n j = ring(ii); k = ring(ii+1);\n vi = points(i,:);\n vj = points(j,:);\n vk = points(k,:);\n \n % new % Oscar08 use this \n u = vk-vi; v = vk-vj;\n cot1 = dot(u,v)/norm(cross(u,v));\n W(i,j) = W(i,j) + cot1;\n u = vj-vi; v = vj-vk;\n cot2 = dot(u,v)/norm(cross(u,v));\n W(i,k) = W(i,k) + cot2; \n% % old\n% % angles\n% alpha = myangle(vk-vi,vk-vj);\n% beta = myangle(vj-vi,vj-vk);\n% % add weight\n% W(i,j) = W(i,j) + cot( alpha );\n% W(i,k) = W(i,k) + cot( beta );\n end\n \n tmp = abs(sum(W(i,:)));\n if tmp>10000\n W(i,:) = W(i,:)*10000/tmp;\n end\nend\nfunction W = compute_point_weight_mvc(points, rings)\nn = length(points);\nW = sparse(n,n);\nfor i = 1:n\n ring = rings{i};\n\n tmp = size(ring,2)-1;\n for ii = 1: tmp\n j = ring(ii); k = ring(ii+1);\n vi = points(i,:);\n vj = points(j,:);\n vk = points(k,:);\n \n % angles\n alpha = myangle(vi-vk,vi-vj);\n % add weight\n W(i,j) = W(i,j) + tan( 0.5*alpha )/sqrt(sum((vi-vj).^2));\n W(i,k) = W(i,k) + tan( 0.5*alpha )/sqrt(sum((vi-vk).^2));\n end\n \n tmp = sum(W(i,:));\n if tmp>10000\n W(i,:) = W(i,:)*10000/tmp;\n end \nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction beta = myangle(u,v);\n\ndu = sqrt( sum(u.^2) );\ndv = sqrt( sum(v.^2) );\ndu = max(du,eps); dv = max(dv,eps);\nbeta = acos( sum(u.*v) / (du*dv) ); ", "meta": {"author": "taiya", "repo": "cloudcontr", "sha": "9c27e747136c5286c9a6e9f9c6b278f63cd5312f", "save_path": "github-repos/MATLAB/taiya-cloudcontr", "path": "github-repos/MATLAB/taiya-cloudcontr/cloudcontr-9c27e747136c5286c9a6e9f9c6b278f63cd5312f/matlab/toolbox/compute_point_weight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6911360802189871}} {"text": "function [U,H,it] = qdwh(A,alpha,L,piv)\n%QDWH QR-based dynamically weighted Halley iteration for polar decomposition.\n% [U,H,it,res] = qdwh(A,alpha,L,PIV) computes the\n% polar decomposition A = U*H of a full rank M-by-N matrix A with \n% M >= N. Optional arguments: ALPHA: an estimate for norm(A,2),\n% L: a lower bound for the smallest singular value of A, and \n% PIV = 'rc' : column pivoting and row sorting,\n% PIV = 'c' : column pivoting only,\n% PIV = '' (default): no pivoting.\n% The third output argument IT is the number of iterations.\n\n[m,n] = size(A);\n\ntol1 = 10*eps/2; tol2 = 10*tol1; tol3 = tol1^(1/3);\nif m == n && norm(A-A','fro')/norm(A,'fro') < tol2;\n symm = 1;\nelse\n symm = 0;\nend\n\nit = 0; \n\nif m < n, error('m >= n is required.'), end\n\nif nargin < 2 || isempty(alpha) % Estimate for largest singular value of A.\n alpha = normest(A,0.1);\nend\n\n% Scale original matrix to form X0.\nU = A/alpha; Uprev = U;\n\nif nargin < 3 || isempty(L) % Estimate for smallest singular value of U.\n Y = U; if m > n, [Q,Y] = qr(U,0); end\n smin_est = norm(Y,1)/condest(Y); % Actually an upper bound for smin.\n L = smin_est/sqrt(n); \nend\n\nif nargin < 4, piv = ''; end\n\ncol_piv = strfind(piv,'c');\nrow_sort = strfind(piv,'r');\n\nif row_sort\n row_norms = sum(abs(U),2);\n [ignore,rind] = sort(row_norms,1,'descend');\n U = U(rind,:);\nend\n\nwhile norm(U-Uprev,'fro') > tol3 || it == 0 || abs(1-L) > tol1\n\n it = it + 1;\n Uprev = U;\n\n % Compute parameters L,a,b,c (second, equivalent way).\n L2 = L^2;\n dd = ( 4*(1-L2)/L2^2 )^(1/3);\n sqd = sqrt(1+dd);\n a = sqd + sqrt(8 - 4*dd + 8*(2-L2)/(L2*sqd))/2;\n a = real(a);\n b = (a-1)^2/4;\n c = a+b-1;\n % Update L.\n L = L*(a+b*L2)/(1+c*L2);\n\n if c > 100 % Use QR.\n B = [sqrt(c)*U; eye(n)];\n\n if col_piv\n [Q,R,E] = qr(B,0,'vector');\n else\n [Q,R] = qr(B,0); %E = 1:n;\n end\n\n Q1 = Q(1:m,:); Q2 = Q(m+1:end,:);\n U = b/c*U + (a-b/c)/sqrt(c)*Q1*Q2';\n\n else % Use Cholesky when U is well conditioned; faster.\n C = chol(c*(U'*U)+eye(n));\n % Utemp = (b/c)*U + (a-b/c)*(U/C)/C';\n % Next three lines are slightly faster.\n opts1.UT = true; opts1.TRANSA = true;\n opts2.UT = true; opts2.TRANSA = false;\n U = (b/c)*U + (a-b/c)*(linsolve(C,linsolve(C,U',opts1),opts2))';\n end\n if symm\n U = (U+U')/2;\n end\nend\nif row_sort\n U(rind,:) = U;\nend\n\nif nargout > 1\n H = U'*A; H = (H'+H)/2;\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/36830-symmetric-eigenvalue-decomposition-and-the-svd/qdwh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6911360761786172}} {"text": "function [Y_F,U] = SimulateFactorsResiduals(Corr_Y_F, volU, J)\n%[Y_F,U] = SimulateFactorsResiduals(Corr_Y_F, volU, J)\n% Generates simulations of unit normal factors Y_F and residuals U. The\n% first two sample joint moments of Y_F are forced to match the given\n% inputs and assumptions. Sample covariance of each residual U with each\n% factor is enforced to be zero, but the sample covariances between\n% elements of U are not forced to be zero (for complexity reasons).\n% U is assumed to be zero-mean, uncorrelated and jointly normal.\n%\n% IMPORTANT: The order of computations in the following expressions is\n% important for efficiency. Please use the same order, or have a good reason\n% to change it! \n% Code by S. Gollamudi. This version December 2009. \n\nK = size(Corr_Y_F,1);\nN = length(volU);\nif size(volU,2)==1, volU = volU'; end\n \n% Simulate Y_F with sample mean and covariance exactly matching the\n% desired values\nY_F = MvnRndMatchCrossCov(Corr_Y_F, zeros(0,K), zeros(J,0));\n\n% Simulate residuals that are orthogonal to columns of F\nU = randn(J/2,N);\nU = [U\n -U];\nU = U - (Y_F/Corr_Y_F)*((Y_F'*U)/J);\n\n% Scale residuals to have the correct sample variance\nnorm_factors = volU./sqrt(mean(U.^2,1));\nU = U .* repmat(norm_factors,J,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/26853-factors-on-demand/FactorsOnDemand/StatisticalVsCrossSectional/SimulateFactorsResiduals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.691136070118062}} {"text": "function M = symmetricfactory(n, k)\n% Returns a manifold struct to optimize over k symmetric matrices of size n\n%\n% function M = symmetricfactory(n)\n% function M = symmetricfactory(n, k)\n%\n% Returns M, a structure describing the Euclidean space of n-by-n symmetric\n% matrices equipped with the standard Frobenius distance and associated\n% trace inner product, as a manifold for Manopt.\n% By default, k = 1. If k > 1, points and vectors are stored in 3D matrices\n% X of size nxnxk such that each slice X(:, :, i), for i = 1:k, is\n% symmetric.\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Jan. 22, 2014.\n% Contributors: \n% Change log: \n \n if ~exist('k', 'var') || isempty(k)\n k = 1;\n end\n\n M.name = @() sprintf('(Symmetric matrices of size %d)^%d', n, k);\n \n M.dim = @() k*n*(n+1)/2;\n \n M.inner = @(x, d1, d2) d1(:).'*d2(:);\n \n M.norm = @(x, d) norm(d(:), 'fro');\n \n M.dist = @(x, y) norm(x(:)-y(:), 'fro');\n \n M.typicaldist = @() sqrt(k)*n;\n \n M.proj = @(x, d) multisym(d);\n \n M.egrad2rgrad = M.proj;\n \n %M.ehess2rhess = @(x, eg, eh, d) eh;\n \n M.tangent = @(x, d) d;\n \n M.exp = @exp;\n function y = exp(x, d, t)\n if nargin == 3\n y = x + t*d;\n else\n y = x + d;\n end\n end\n \n M.retr = M.exp;\n\t\n\tM.log = @(x, y) y-x;\n\n M.hash = @(x) ['z' hashmd5(x(:))];\n \n M.rand = @() multisym(randn(n, n, k));\n \n M.randvec = @randvec;\n function u = randvec(x) %#ok\n u = multisym(randn(n, n, k));\n u = u / norm(u(:), 'fro');\n end\n \n M.lincomb = @lincomb;\n function v = lincomb(x, a1, d1, a2, d2) %#ok\n if nargin == 3\n v = a1*d1;\n elseif nargin == 5\n v = a1*d1 + a2*d2;\n else\n error('Bad usage of euclidean.lincomb');\n end\n end\n \n M.zerovec = @(x) zeros(n, n, k);\n \n M.transp = @(x1, x2, d) d;\n \n M.pairmean = @(x1, x2) .5*(x1+x2);\n \n M.vec = @(x, u_mat) u_mat(:);\n M.mat = @(x, u_vec) reshape(u_vec, [m, n]);\n M.vecmatareisometries = @() true;\n\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/manopt/manopt/manifolds/euclidean/symmetricfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.6910456137828478}} {"text": "function value = c8_cube_root ( x )\n\n%*****************************************************************************80\n%\n%% C8_CUBE_ROOT returns the principal cube root of a C8.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 September 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, complex X, the number whose cube root is desired.\n%\n% Output, complex VALUE, the cube root of X.\n%\n a = real ( x );\n b = imag ( x );\n mag = sqrt ( a * a + b * b );\n\n if ( mag == 0.0 )\n\n value = 0.0;\n\n else\n\n theta = atan2 ( b, a );\n\n value = mag.^( 1 / 3 ) * ( cos ( theta / 3 ) + i * sin ( theta / 3 ) );\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/c8lib/c8_cube_root.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6910455999184653}} {"text": "function chebyshev1_compute_test ( )\n\n%*****************************************************************************80\n%\n%% CHEBYSHEV1_COMPUTE_TEST tests CHEBYSHEV1_COMPUTE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 15 April 2015\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHEBYSHEV1_COMPUTE_TEST\\n' );\n fprintf ( 1, ' CHEBYSHEV1_COMPUTE computes\\n' );\n fprintf ( 1, ' a Chebyshev Type 1 quadrature rule over [-1,1]\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Index X W\\n' );\n fprintf ( 1, '\\n' );\n\n for n = 1 : 10\n\n [ x, w ] = chebyshev1_compute ( n );\n\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n fprintf ( 1, ' %2d %12g %12g\\n', i, x(i), w(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/quadrule/chebyshev1_compute_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.6910455895201782}} {"text": "function bti_test04 ( )\n\n%*****************************************************************************80\n%\n%% BTI_TEST04 tests BURGERS_TIME_INVISCID.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 April 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BTI_TEST04\\n' );\n fprintf ( 1, ' Test BURGERS_TIME_INVISCID\\n' );\n\n method = 4;\n nx = 81;\n nt = 200;\n t_max = 2.0;\n bc = 4;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Method: 4, Lax Wendroff.\\n' );\n fprintf ( 1, ' Initial condition: expansion\\n' );\n fprintf ( 1, ' Number of space nodes = %d\\n', nx );\n fprintf ( 1, ' Number of time steps = %d\\n', nt );\n fprintf ( 1, ' Final time T_MAX = %g\\n', t_max );\n fprintf ( 1, ' Boundary condition = %d\\n', bc );\n\n U = burgers_time_inviscid ( method, @ic_expansion, nx, nt, t_max, bc );\n\n x = linspace ( -1.0, +1.0, nx );\n\n figure ( 4 )\n\n plot ( x, U(1:50:(nt+1),:), 'Linewidth', 3 )\n grid on\n xlabel ( '<-- X -->' )\n ylabel ( '<-- U(X,T) -->' )\n title ( 'Burgers, inviscid, initial expansion, Lax Wendroff' )\n\n filename = 'bti_test04.png';\n print ( '-dpng', filename )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Saved plot as \"%s\"\\n', filename );\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/burgers_time_inviscid/bti_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143954, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.6910455771204111}} {"text": "function [A,b,Aeq,beq]=addBounds(A0,b0,Aeq0,beq0,lb,ub)\n%addBounds - given a sextuplet {A, b, Aeq, beq, lb, ub} of matrices and vectors \n%of the kind used by the Optimization Toolbox to express linear\n%constraints, the routine will convert the sextuplet to a quadruplet {A, b,\n%Aeq, beq}. \n%\n% [A,b,Aeq,beq]=addBounds(A,b,Aeq,beq,lb,ub)\n%\n%In other words, it will re-write the bounds given by vectors lb, ub as equalities\n%and inequalities C*x<=c, D*x=d and append these as new rows to the matrices\n%A, b, Aeq, beq.\n%\n%\n%EXAMPLE:\n%\n% >> [A,b,Aeq,beq]=addBounds([1 1 1],1,[],[],[0;0;1],[1;1;1])\n% \n% A =\n% \n% 1 1 1\n% -1 0 0\n% 0 -1 0\n% 1 0 0\n% 0 1 0\n% \n% \n% b =\n% \n% 1\n% 0\n% 0\n% 1\n% 1\n% \n% \n% Aeq =\n% \n% 0 0 1\n% \n% \n% beq =\n% \n% 1\n\n\n\n\n %%%%begin parsing\n \n if nargin<5, error 'At least 5 arguments required'; end\n \n if size(A0,1)~=length(b0)\n error 'Incompatible inequality matrix data sizes: size(A,1) ~= length(b)'\n end\n \n if size(Aeq0,1)~=length(beq0)\n error 'Incompatible equality matrix data sizes: size(Aeq,1) ~= length(beq)'\n end\n\n\n\n if ~exist('lb','var'), lb=[]; end\n if ~exist('ub','var'), ub=[]; end \n \n if ~isempty(lb)\n N=length(lb);\n elseif ~isempty(ub);\n N=length(ub);\n else\n error 'Either lb or ub must be nonempty.'\n end\n \n if isempty(lb)\n lb=-inf(N,1); \n end\n\n if isempty(ub)\n ub=+inf(N,1); \n end\n \n if length(ub)~=length(lb)\n error 'Arguments lb and ub must be either [] or the same lengths' \n end\n \n \n lb=lb(:); ub=ub(:);\n\n %%%end parsing\n \n \n lisinf=~isfinite(lb);\n uisinf=~isfinite(ub); \n idx_eq=(ub==lb)& ~lisinf & ~uisinf;\n\n Au=[eye(N),ub];\n Al=[-eye(N),-lb]; \n Aeq=Au(idx_eq,:);\n Au(idx_eq|uisinf,:)=[];\n Al(idx_eq|lisinf,:)=[];\n \n A=[Al;Au]; b=A(:,end); A(:,end)=[];\n beq=Aeq(:,end); Aeq(:,end)=[];\n \n \n A=[A0;A];\n b=[b0;b];\n Aeq=[Aeq0;Aeq];\n beq=[beq0;beq];\n \n if any(lb==inf | ub==-inf)\n A(end+1,end)=0; b(end+1)=-1; \n end\n \n ", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/polytopes_2017_10_04_v1.9/addBounds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6909845595703886}} {"text": "function sphere_triangle_quad_test04 ( )\n\n%*****************************************************************************80\n%\n%% SPHERE_TRIANGLE_TEST04 tests SPHERE01_TRIANGLE_QUAD_ICOS1M.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 23 April 2014\n%\n% Author:\n%\n% John Burkardt\n%\n e_test = [ ...\n 0, 0, 0; ...\n 1, 0, 0; ...\n 0, 1, 0; ...\n 0, 0, 1; ...\n 2, 0, 0; ...\n 0, 2, 2; ...\n 2, 2, 2; ...\n 0, 2, 4; ...\n 0, 0, 6; ...\n 1, 2, 4; ...\n 2, 4, 2; ...\n 6, 2, 0; ...\n 0, 0, 8; ...\n 6, 0, 4; ...\n 4, 6, 2; ...\n 2, 4, 8; ...\n 16, 0, 0 ]';\n n_mc1 = 1000;\n n_mc2 = 10000;\n n_mc3 = 100000;\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPHERE_TRIANGLE_QUAD_TEST04\\n' );\n fprintf ( 1, ' SPHERE01_TRIANGLE_QUAD_ICOS1M approximates the\\n' );\n fprintf ( 1, ' integral of a function over a spherical triangle on\\n' );\n fprintf ( 1, ' the surface of the unit sphere using a midpoint rule.\\n' );\n fprintf ( 1, '\\n' ); \n fprintf ( 1, ' We do not have an exact result, so we compare each\\n' );\n fprintf ( 1, ' estimate to the final one.\\n' );\n%\n% Choose three points at random to define a spherical triangle.\n%\n [ v1, seed ] = sphere01_sample ( 1, seed );\n [ v2, seed ] = sphere01_sample ( 1, seed );\n [ v3, seed ] = sphere01_sample ( 1, seed );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Vertices of random spherical triangle:\\n' );\n fprintf ( 1, '\\n' );\n r8vec_transpose_print ( 3, v1, ' V1:' );\n r8vec_transpose_print ( 3, v2, ' V2:' );\n r8vec_transpose_print ( 3, v3, ' V3:' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' FACTOR N RESULT\\n' );\n\n for j = 1 : 17\n\n e(1:3) = e_test(1:3,j);\n\n e = polyterm_exponent ( 'SET', e );\n\n polyterm_exponent ( 'PRINT', e );\n\n% factor = 2 ^ 11;\n factor = 2 ^ 7;\n [ best, node_num ] = sphere01_triangle_quad_icos1m ( v1, v2, v3, factor, ...\n @polyterm_value_3d );\n\n factor = 1;\n for factor_log = 0 : 5\n\n [ result, node_num ] = sphere01_triangle_quad_icos1m ( v1, v2, v3, ...\n factor, @polyterm_value_3d );\n\n error = abs ( result - best );\n\n fprintf ( 1, ' %4d %8d %16.8g %10.2e\\n', ...\n factor, node_num, result, error );\n\n factor = factor * 2;\n\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/sphere_triangle_quad/sphere_triangle_quad_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6909845574135898}} {"text": "% BS2RV.m - Binary string to real vector\n%\n% This function decodes binary chromosomes into vectors of reals. The\n% chromosomes are seen as the concatenation of binary strings of given\n% length, and decoded into real numbers in a specified interval using\n% either standard binary or Gray decoding.\n%\n% Syntax: Phen = bs2rv(Chrom,FieldD)\n%\n% Input parameters:\n%\n% Chrom - Matrix containing the chromosomes of the current\n% population. Each line corresponds to one\n% individual's concatenated binary string\n%\t\t\t representation. Leftmost bits are MSb and\n%\t\t\t rightmost are LSb.\n%\n% FieldD - Matrix describing the length and how to decode\n%\t\t\t each substring in the chromosome. It has the\n%\t\t\t following structure:\n%\n%\t\t\t\t[len;\t\t(num)\n%\t\t\t\t lb;\t\t(num)\n%\t\t\t\t ub;\t\t(num)\n%\t\t\t\t code;\t\t(0=binary | 1=gray)\n%\t\t\t\t scale;\t\t(0=arithmetic | 1=logarithmic)\n%\t\t\t\t lbin;\t\t(0=excluded | 1=included)\n%\t\t\t\t ubin];\t\t(0=excluded | 1=included)\n%\n%\t\t\t where\n%\t\t\t\tlen - row vector containing the length of\n%\t\t\t\t\teach substring in Chrom. sum(len)\n%\t\t\t\t\tshould equal the individual length.\n%\t\t\t\tlb,\n%\t\t\t\tub - Lower and upper bounds for each\n%\t\t\t\t\tvariable. \n%\t\t\t\tcode - binary row vector indicating how each\n%\t\t\t\t\tsubstring is to be decoded.\n%\t\t\t\tscale - binary row vector indicating where to\n%\t\t\t\t\tuse arithmetic and/or logarithmic\n%\t\t\t\t\tscaling.\n%\t\t\t\tlbin,\n%\t\t\t\tubin - binary row vectors indicating whether\n%\t\t\t\t\tor not to include each bound in the\n%\t\t\t\t\trepresentation range\n%\n% Output parameter:\n%\n% Phen - Real matrix containing the population phenotypes.\n\n%\n% Author: Carlos Fonseca, \tUpdated: Andrew Chipperfield\n% Date: 08/06/93,\t\tDate: 26-Jan-94\n\nfunction Phen = bs2rv(Chrom,FieldD)\n\n% Identify the population size (Nind)\n% and the chromosome length (Lind)\n[Nind,Lind] = size(Chrom);\n\n% Identify the number of decision variables (Nvar)\n[seven,Nvar] = size(FieldD);\n\nif seven ~= 7\n\terror('FieldD must have 7 rows.');\nend\n\n% Get substring properties\nlen = FieldD(1,:);\nlb = FieldD(2,:);\nub = FieldD(3,:);\ncode = ~(~FieldD(4,:));\nscale = ~(~FieldD(5,:));\nlin = ~(~FieldD(6,:));\nuin = ~(~FieldD(7,:));\n\n% Check substring properties for consistency\nif sum(len) ~= Lind,\n\terror('Data in FieldD must agree with chromosome length');\nend\n\nif ~all(lb(scale).*ub(scale)>0)\n\terror('Log-scaled variables must not include 0 in their range');\nend\n\n% Decode chromosomes\nPhen = zeros(Nind,Nvar);\n\nlf = cumsum(len);\nli = cumsum([1 len]);\nPrec = .5 .^ len;\n\nlogsgn = sign(lb(scale));\nlb(scale) = log( abs(lb(scale)) );\nub(scale) = log( abs(ub(scale)) );\ndelta = ub - lb;\n\nPrec = .5 .^ len;\nnum = (~lin) .* Prec;\nden = (lin + uin - 1) .* Prec;\n\nfor i = 1:Nvar,\n idx = li(i):lf(i);\n if code(i) % Gray decoding\n\t Chrom(:,idx)=rem(cumsum(Chrom(:,idx)')',2);\n end\n Phen(:,i) = Chrom(:,idx) * [ (.5).^(1:len(i))' ];\n Phen(:,i) = lb(i) + delta(i) * (Phen(:,i) + num(i)) ./ (1 - den(i));\nend\n\nexpand = ones(Nind,1);\nif any(scale)\n\tPhen(:,scale) = logsgn(expand,:) .* exp(Phen(:,scale));\nend\n\u001a", "meta": {"author": "vonsylvia", "repo": "MATLAB_Algorithm_with_cases", "sha": "646e51a377568889f48b8fdebbc44f0a2514048a", "save_path": "github-repos/MATLAB/vonsylvia-MATLAB_Algorithm_with_cases", "path": "github-repos/MATLAB/vonsylvia-MATLAB_Algorithm_with_cases/MATLAB_Algorithm_with_cases-646e51a377568889f48b8fdebbc44f0a2514048a/\u652f\u6301\u5411\u91cf\u673a\u5206\u7c7b\u2014\u2014\u57fa\u4e8e\u4e73\u817a\u7ec4\u7ec7\u7535\u963b\u6297\u7279\u6027\u7684\u4e73\u817a\u764c\u8bca\u65ad/libsvm-mat-2[1].89-3[FarutoUltimate3.0Mcode]/implement[by faruto]/myprivate/gatbx[Sheffield]/bs2rv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772220439509, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.6909845535115033}} {"text": "function f1 = p03_f1 ( x )\n\n%*****************************************************************************80\n%\n%% P03_F1 evaluates the first derivative for problem 3.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 February 2002\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the value of the variable.\n%\n% Output, real F1, the first derivative of the\n% objective function.\n%\n f1 = ( 4.0 * x * x + 4.0 ) * x + 1.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/test_min/p03_f1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.8128673223709252, "lm_q1q2_score": 0.6909138060061152}} {"text": "function [pHr, pHAdjustment] = realpH(pHa, temp, is)\n% Apparent glass electrode pH is not the same as real pH for thermodynamic calculations.\n%\n% Given the experimental glass electrode measurement of pH, this function returns\n% the pH to be used for thermodynamic calculations, `pHc = -log10[H+]`,\n% by subtracting the effect of the ion atmosphere around H+ which\n% reduces its activity coefficient below unity.\n% See `p49 Alberty 2003`.\n%\n% USAGE:\n%\n% [pHr, pHAdjustment] = realpH(pHa, temp, is)\n%\n% INPUTS:\n% pHa: apparent pH, measured by glass electrode experimentally\n% temp: experimentally measured temperature\n% is: estimate of ionic strength\n%\n% OUTPUTS:\n% pHr: real pH to be used for thermodynamic calculations\n% pHAdjustment: adjustment to pH\n%\n% .. Author: -Ronan M.T. Fleming\n\ngibbscoeff = 1.10708 - (1.54508*temp)/10^3 + (5.95584*temp^2)/10^6; % p48 Alberty\n\n%Adjust pH using Extended Debye-Huckle equation\npHAdjustment = ( (gibbscoeff*(is^(0.5))) / (log(10)*(1+1.6*(is^(0.5)))) );\n\n% fprintf('%s\\t%f\\n','pH adjustment',phAdjustment);\npHr = pHa - pHAdjustment;\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/thermo/protons/realpH.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535095, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6909087619193105}} {"text": "%SlideDistanceLimit\n\n%w = sqrt(2*g / 3*L);\n%cos(th) = 2/3;\n%sin(th) = sqrt(1-cos(th)^2);\n%\n%rg = [L*sin(th); L*cos(th)];\n%\n% Let L=1, g = 1\n%\n\ncosth = 2/3;\nsinth = sqrt(1-costh^2);\nw = sqrt(2/3);\n\nrg = [-sinth; costh];\ndrg = [-w*costh; -w*sinth];\n\n%0 = rg(2) + drg(2)*t + -0.5*t^2\nP = [-0.5,drg(2),rg(2)];\nt = max(roots(P));\n\nd = rg(1) + drg(1)*t;\n\nSlipDist = d+1;\n\n%%%%%%%%%%%%%%\n\nsyms L g\n\nL=sym(1);\ng = sym(1);\n\ncosth = sym(2/3);\nsinth = sqrt(sym(5/9));\nw = sqrt((2*g)/(3*L));\n\nrg = [-L*sinth; L*costh];\ndrg = -L*w*[costh; sinth];\na = -g/2;\nb = drg(2);\nc = rg(2);\nt = simplify((-b - sqrt(b^2-4*a*c))/(2*a));\n\nd = simplify(rg(1) + drg(1)*t);\n\nSlipDist = simplify(d + L);\n\npretty(SlipDist)\nSlipDist\ndouble(SlipDist)\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/toppling_stick/SlideDistanceLimit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6909015616491118}} {"text": "%demoL1iPotts_DecImp\n% Reconstruction of a blurred jump-sparse signal from incomplete measurements under\n% impulsive noise using the inverse L1-Potts functional\n\n% load signal\ngroundTruth = loadPcwConst('sampleDec');\nn = numel(groundTruth);\n\n% create Gaussian kernel\nK = convkernel('gaussian', 51, 6);\n\n% create measurement matrix\nAfull = spconvmatrix(K, numel(groundTruth));\nfraction = 0.5;\nidx = sort(randidx(n, fraction)) ;\nA = Afull(idx, :);\n\n% create blurred signal\nfBlurry = A * groundTruth(:);\n\n% impulsive noise (noiseFraction = number of pixels destroyed)\nnoiseFraction = 0.3;\nridx = randidx(numel(fBlurry), noiseFraction);\nf = fBlurry;\nf(ridx) = (rand(size(ridx)));\n\n% Solve inverse L1-Potts problem\ngamma = 0.4;\nu = minL1iPotts(f, gamma, A);\n\n% show result\nshowPotts(f, u, groundTruth, 'L^1-iPotts')\n\n", "meta": {"author": "mstorath", "repo": "Pottslab", "sha": "53571378ef2f60b1104fc8dacc1d8f03427987a9", "save_path": "github-repos/MATLAB/mstorath-Pottslab", "path": "github-repos/MATLAB/mstorath-Pottslab/Pottslab-53571378ef2f60b1104fc8dacc1d8f03427987a9/Demos/1D/demoL1iPotts_DecImp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6908725878125717}} {"text": "function [signal, lineNoiseOut] = cleanLineNoise(signal, lineNoiseIn)\n% Remove sharp spectral peaks from signal using Sleppian filters\n%\n% Usage:\n% signal = cleanLineNoise(signal)\n% [signal, lineNoiseOut] = hcleanLineNoise(signal, lineNoiseIn)\n%\n% Parameters:\n% signal Structure with .data and .srate fields\n% lineNoiseIn Input structure with fields described below\n%\n% Structure parameters (lineNoiseIn):\n% fPassBand Frequency band used (default [0, Fs/2] = entire band)\n% Fs \t Sampling frequency \n% fScanBandWidth +/- bandwidth centered on each f0 to scan for significant\n% lines (TM)\n% lineFrequencies Line frequencies to be removed (default \n% [60, 120, 180, 240, 300])\n% lineNoiseChannels Channels to remove line noise from (default\n% size(data, 1))\n% maximumIterations Maximum times to iterate removal (default = 10)\n% p Significance level cutoff (default = 0.01)\n% pad FFT padding factor ( -1 corresponds to no padding, \n% 0 corresponds to padding to next highest power of 2\n% etc.) (default is 0)\n% pnts\n% tapers Precomputed tapers from dpss\n% taperBandWidth Taper bandwidth (default 2 Hz)\n% taperWindowSize Taper sliding window length (default 4 sec)\n% taperWindowStep Sliding window step size (default 4 sec = no overlap)\n% tau Window overlap smoothing factor (default 100)\n%\n% This function is based on code originally written by Tim Mullen in a \n% package called tmullen-cleanline which is based on the chronux_2\n% libraries.\n%\n\nlineNoiseOut = lineNoiseIn;\n%% Remove line frequencies that are greater than Nyquist frequencies\ntooLarge = lineNoiseOut.lineFrequencies >= lineNoiseOut.Fs/2;\nif any(tooLarge)\n warning('cleanLineNoise:LineFrequenciesTooLarge', ...\n 'Eliminating frequencies greater than half the sampling rate');\n lineNoiseOut.lineFrequencies(tooLarge) = [];\n lineNoiseOut.lineFrequencies = squeeze(lineNoiseOut.lineFrequencies);\nend\n\n%% Set up multi-taper parameters\nhbw = lineNoiseOut.taperBandWidth/2; % half-bandwidth\nlineNoiseOut.taperTemplate = [hbw, lineNoiseOut.taperWindowSize, 1];\nNwin = round(lineNoiseOut.Fs*lineNoiseOut.taperWindowSize); % number of samples in window\nlineNoiseOut.tapers = checkTapers(lineNoiseOut.taperTemplate, Nwin, lineNoiseOut.Fs); \n\n%% Perform the calculation for each channel separately\nsignal.data = double(signal.data);\nchans = lineNoiseOut.lineNoiseChannels;\ndata = signal.data(chans, :);\nparfor ch = 1:size(data, 1)\n data(ch, :) = removeLinesMovingWindow(squeeze(data(ch, :)), lineNoiseOut);\nend\nsignal.data(chans, :) = data;\nclear data;\n\n", "meta": {"author": "VisLab", "repo": "EEG-Clean-Tools", "sha": "9ac9ea0c21d44b57f9e9f93b62ca727c7b75c73e", "save_path": "github-repos/MATLAB/VisLab-EEG-Clean-Tools", "path": "github-repos/MATLAB/VisLab-EEG-Clean-Tools/EEG-Clean-Tools-9ac9ea0c21d44b57f9e9f93b62ca727c7b75c73e/PrepPipeline/utilities/cleanLineNoise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6908320959650693}} {"text": "function [ n_data, mu, sigma, b, x, fx ] = ...\n truncated_normal_b_pdf_values ( n_data )\n\n%*****************************************************************************80\n%\n%% TRUNCATED_NORMAL_B_PDF_VALUES: values of the Truncated Normal B PDF.\n%\n% Discussion:\n%\n% The Normal distribution, with mean Mu and standard deviation Sigma,\n% is truncated to the interval (-oo,B].\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 September 2013\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. 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, real MU, the mean of the distribution.\n%\n% Output, real SIGMA, the standard deviation of the distribution.\n%\n% Output, real B, the upper truncation limit.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 11;\n\n b_vec = [ ...\n 150.0, ...\n 150.0, ...\n 150.0, ...\n 150.0, ...\n 150.0, ...\n 150.0, ...\n 150.0, ...\n 150.0, ...\n 150.0, ...\n 150.0, ...\n 150.0 ];\n\n fx_vec = [ ...\n 0.01507373507401876, ...\n 0.01551417047139894, ...\n 0.01586560931024694, ...\n 0.01612150073158793, ...\n 0.01627701240029317, ...\n 0.01632918226724295, ...\n 0.01627701240029317, ...\n 0.01612150073158793, ...\n 0.01586560931024694, ...\n 0.01551417047139894, ...\n 0.01507373507401876 ];\n\n mu_vec = [ ...\n 100.0, ...\n 100.0, ...\n 100.0, ...\n 100.0, ...\n 100.0, ...\n 100.0, ...\n 100.0, ...\n 100.0, ...\n 100.0, ...\n 100.0, ...\n 100.0 ]; \n\n sigma_vec = [ ...\n 25.0, ...\n 25.0, ...\n 25.0, ...\n 25.0, ...\n 25.0, ...\n 25.0, ...\n 25.0, ...\n 25.0, ...\n 25.0, ...\n 25.0, ...\n 25.0 ];\n\n x_vec = [ ...\n 90.0, ...\n 92.0, ...\n 94.0, ...\n 96.0, ...\n 98.0, ...\n 100.0, ...\n 102.0, ...\n 104.0, ...\n 106.0, ...\n 108.0, ...\n 110.0 ];\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 b = 0.0;\n mu = 0.0;\n sigma = 0.0;\n x = 0.0;\n fx = 0.0;\n else\n b = b_vec(n_data);\n mu = mu_vec(n_data);\n sigma = sigma_vec(n_data);\n x = x_vec(n_data);\n fx = fx_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/truncated_normal_b_pdf_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6908320867994728}} {"text": "function [out] = rainfall_2(In,T,p1,p2)\n%rainfall_2 \n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% Flux function\n% ------------------\n% Description: Rainfall based on a temperature threshold interval\n% Constraints: -\n% @(Inputs): In - incoming precipitation flux [mm/d]\n% T - current temperature [oC]\n% p1 - midpoint of the combined rain/snow interval [oC]\n% p2 - length of the mixed snow/rain interval [oC]\n\nout = min(In,max(0,In.*(T-(p1-0.5*p2))/p2));\n\nend\n\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Flux files/rainfall_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.690832077633876}} {"text": "%[1995]-\"Particle Swarm Optimization\" \n%[1998]-\"A modified particle swarm optimizer\"\n\n% (9/12/2020)\n\nfunction PSO = jParticleSwarmOptimization(feat,label,opts)\n% Parameters\nlb = 0; \nub = 1;\nthres = 0.5;\nc1 = 2; % cognitive factor\nc2 = 2; % social factor \nw = 0.9; % inertia weight\nVmax = (ub - lb) / 2; % Maximum velocity \n\nif isfield(opts,'N'), N = opts.N; end\nif isfield(opts,'T'), max_Iter = opts.T; end\nif isfield(opts,'c1'), c1 = opts.c1; end \nif isfield(opts,'c2'), c2 = opts.c2; end \nif isfield(opts,'w'), w = opts.w; end \nif isfield(opts,'Vmax'), Vmax = opts.Vmax; end \nif isfield(opts,'thres'), thres = opts.thres; end\n\n% Objective function\nfun = @jFitnessFunction; \n% Number of dimensions\ndim = size(feat,2); \n% Initial \nX = zeros(N,dim); \nV = zeros(N,dim); \nfor i = 1:N\n for d = 1:dim\n X(i,d) = lb + (ub - lb) * rand();\n end\nend \n% Fitness\nfit = zeros(1,N); \nfitG = inf;\nfor i = 1:N \n fit(i) = fun(feat,label,(X(i,:) > thres),opts); \n % Gbest update\n if fit(i) < fitG\n Xgb = X(i,:); \n fitG = fit(i);\n end\nend\n% PBest\nXpb = X; \nfitP = fit;\n% Pre\ncurve = zeros(1,max_Iter);\ncurve(1) = fitG;\nt = 2; \n% Iterations\nwhile t <= max_Iter\n for i = 1:N\n for d = 1:dim\n r1 = rand();\n r2 = rand();\n % Velocity update (2a)\n VB = w * V(i,d) + c1 * r1 * (Xpb(i,d) - X(i,d)) + ...\n c2 * r2 * (Xgb(d) - X(i,d));\n % Velocity limit\n VB(VB > Vmax) = Vmax; VB(VB < -Vmax) = -Vmax;\n V(i,d) = VB;\n % Position update (2b)\n X(i,d) = X(i,d) + V(i,d);\n end\n % Boundary\n XB = X(i,:); XB(XB > ub) = ub; XB(XB < lb) = lb;\n X(i,:) = XB;\n % Fitness\n fit(i) = fun(feat,label,(X(i,:) > thres),opts);\n % Pbest update\n if fit(i) < fitP(i)\n Xpb(i,:) = X(i,:); \n fitP(i) = fit(i);\n end\n % Gbest update\n if fitP(i) < fitG\n Xgb = Xpb(i,:);\n fitG = fitP(i);\n end\n end\n curve(t) = fitG; \n fprintf('\\nIteration %d Best (PSO)= %f',t,curve(t))\n t = t + 1;\nend\n% Select features based on selected index\nPos = 1:dim;\nSf = Pos((Xgb > thres) == 1); \nsFeat = feat(:,Sf); \n% Store results\nPSO.sf = Sf; \nPSO.ff = sFeat;\nPSO.nf = length(Sf);\nPSO.c = curve;\nPSO.f = feat;\nPSO.l = label;\nend\n\n\n\n", "meta": {"author": "JingweiToo", "repo": "Wrapper-Feature-Selection-Toolbox", "sha": "91b050142f331d2a58f7127aba91356b397379b3", "save_path": "github-repos/MATLAB/JingweiToo-Wrapper-Feature-Selection-Toolbox", "path": "github-repos/MATLAB/JingweiToo-Wrapper-Feature-Selection-Toolbox/Wrapper-Feature-Selection-Toolbox-91b050142f331d2a58f7127aba91356b397379b3/jParticleSwarmOptimization.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.690832077633876}} {"text": "function result = circularShift(matrix, colshift, rowshift)\n% CIRCULARSHIFT: Circular shifting of a matrix/image, i.e., pixels that get\n% shifted off one side of the image are put back on the other side.\n%\n% result = circularShift(matrix, colshift, rowshift)\n% \n% EPS, DJH '96\n\nlastrow = size(matrix, 1);\nlastcol = size(matrix, 2);\n\nresult = matrix;\n\n% Shift the cols\nif (colshift>0)\n result = [result(:,[lastcol-colshift+1:lastcol]) ...\n\t result(:,[1:lastcol-colshift])];\nelse\n colshift = -colshift;\n result = [result(:,[colshift+1:lastcol]) ...\n\t result(:,[1:colshift])];\nend\n\n% Shift the rows\nif (rowshift>0)\n result = [result([lastrow-rowshift+1:lastrow],:) ; ...\n\t result([1:lastrow-rowshift],:)];\nelse\n rowshift = -rowshift;\n result = [result([rowshift+1:lastrow],:) ; ...\n\t result([1:rowshift],:)];\nend\n\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/circularShift.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.6907987764321925}} {"text": "function [ v, more ] = triangle_lattice_point_next ( c, v, more )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_LATTICE_POINT_NEXT returns the next triangle lattice point.\n%\n% Discussion:\n%\n% The lattice triangle is defined by the vertices:\n%\n% (0,0), (C(3)/C(1), 0) and (0,C(3)/C(2))\n%\n% The lattice triangle is bounded by the lines\n%\n% 0 <= X,\n% 0 <= Y\n% X / C(1) + Y / C(2) <= C(3)\n%\n% Lattice points are listed one at a time, starting at the origin,\n% with X increasing first.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 July 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer C(3), coefficients defining the\n% lattice triangle. These should be positive.\n%\n% Input/output, integer V(2). On first call, the input\n% value is not important. On a repeated call, the input value should\n% be the output value from the previous call. On output, V contains\n% the next lattice point.\n%\n% Input/output, logical MORE. On input, set MORE to FALSE to indicate\n% that this is the first call for a given triangle. Thereafter, the input\n% value should be the output value from the previous call. On output,\n% MORE is TRUE if the returned value V is a new lattice point.\n% If the output value is FALSE, then no more lattice points were found,\n% and V was reset to 0, and the routine should not be called further\n% for this triangle.\n%\n n = 2;\n\n if ( ~more )\n\n v(1:2) = 0;\n more = 1;\n\n else\n\n c1n = i4vec_lcm ( n, c );\n rhs = c1n * c(n+1);\n\n if ( c(2) * ( v(1) + 1 ) + c(1) * v(2) <= rhs )\n v(1) = v(1) + 1;\n else\n v(1) = 0;\n if ( c(2) * v(1) + c(1) * ( v(2) + 1 ) <= rhs )\n v(2) = v(2) + 1;\n else\n v(2) = 0;\n more = 0;\n end\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/geometry/triangle_lattice_point_next.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.6907987607887219}} {"text": "function [V_RF,V_U] = SIPEVD_method(H, Vn)\n\nglobal Nrf;\n[Nt, Ns, Nk] = size(H);\nX = zeros(Nt,Nt,Nk);\nV_U = zeros(Nrf,Ns,Nk);\n\nfor k = 1:Nk\n %X(:,:,k) = (1/Vn(k)/Nt * H(:,:,k)*H(:,:,k)' + eye(Nt))^(-1);\n % X(:,:,k) = eye(Nt) - 1/Vn(k)/Nt * H(:,:,k)*H(:,:,k)';\n X(:,:,k) = 1/Vn(k)/Nt * H(:,:,k) * inv(eye(Ns)+1/Vn(k)/Nt*H(:,:,k)'*H(:,:,k))*H(:,:,k)';\nend\n\nX = sum(X,3);\n[V,D] = eig(X);\n% get the Nrf largest eigenvector\n[~,IX] = sort(diag(D),'descend');\nV = V(:,IX);\nV_RF = exp(1i*angle(V(:,1:Nrf)));\n\nfor k = 1:Nk\n V_U(:,:,k) = inv(V_RF'*H(:,:,k) * H(:,:,k)'* V_RF+ Vn(k) *(V_RF)'*V_RF)*V_RF'*H(:,:,k);\nend\n", "meta": {"author": "Zzhaoxingyu", "repo": "hybrid-beamforming-for-three-scenes", "sha": "396ae70db7dd464a65458f274a65aa113ed73c8b", "save_path": "github-repos/MATLAB/Zzhaoxingyu-hybrid-beamforming-for-three-scenes", "path": "github-repos/MATLAB/Zzhaoxingyu-hybrid-beamforming-for-three-scenes/hybrid-beamforming-for-three-scenes-396ae70db7dd464a65458f274a65aa113ed73c8b/broadband/Alogorithms/SIPEVD/SIPEVD_method.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6907884603895729}} {"text": "function d = fd05 ( p )\n\n%*****************************************************************************80\n%\n%% FD05 is a signed distance function for the cylinder with a hole.\n%\n% Modified:\n%\n% 15 September 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real P(N,3), one or more points.\n%\n% Output, real D(N), the signed distance of each point to the boundary of the region.\n%\n r = sqrt ( p(:,1).^2 + p(:,2).^2 );\n z = p(:,3);\n\n d1 = r - 1.0;\n d2 = z - 1.0;\n d3 = - z - 1.0;\n d4 = sqrt ( d1.^2 + d2.^2 );\n d5 = sqrt ( d1.^2 + d3.^2 );\n\n d = dintersect ( dintersect ( d1, d2 ), d3 );\n ix = ( 0.0 < d1 ) & ( 0.0 < d2 );\n d(ix) = d4(ix);\n ix = ( 0.0 < d1 ) & ( 0.0 < d3 );\n d(ix) = d5(ix);\n\n d = ddiff ( d, dsphere ( p, 0.0, 0.0, 0.0, 0.5 ) );\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/distmesh_3d/fd05.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6907862710580785}} {"text": "function jdoric( n,mink,maxk,a,b )\n%RIC :\n% Generates restricted and unrestricted integer compositions \n% n = integer to be partitioned \n% kmin = min. no. of summands \n% kmax = max. no. of summands\n% a = min. value of summands\n% b = max.value of summands\n%\n% from : \"A Unified Approach to Algorithms Generating Unrestricted\n% and Restricted Integer Compositions and Integer Partitions\"\n% J. D. OPDYKE, J. Math. Modelling and Algorithms (2009) V9 N1, p.53 - 97\n% \n% Matlab implementation :\n% Theophanes E. Raptis, DAT-NCSRD 2010\n% http://cag.dat.demokritos.gr\n% rtheo@dat.demokritos.gr\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ncell = [];\nrowdec = 0;\nfor i=mink:maxk\n in = n/i;\n if a>1 rowdec = i; end\n if a<=in && in <= b N2N(n,i,a,b,n-1-rowdec,i-1,0,0,cell); end\nend\nend\n\nfunction N2N(n,i,a,b,row,col,level,cumsum,cell)\nif col~=0\n if col==1\n jmax = max(a,n-cumsum-b);\n jmin = min(b,n-cumsum-a);\n for j=jmax : jmin\n cell(i-1) = j; cell(i) = n-cumsum-j;\n disp(cell);\n end\n else\n cell(level+1) = a;\n tmp = cumsum + a;\n ntmp = round((n - tmp)/(i-level-1));\n if a <= ntmp && ntmp <= b && cell(level+1)\n N2N(n,i,a,b,row-a+1,col-1,level+1,tmp,cell);\n else\n for q=1:min((b-a),(row-a)-(col-1))\n cell(level+1) = cell(level+1)+1;\n tmp = tmp + 1;\n ntmp = round((n - tmp)/(i-level-1));\n if a <= ntmp && ntmp <= b && cell(level+1)\n q2 = q; q = min((b-a),(row-a)-(col-1));\n N2N(n,i,a,b,row-a-q2+1,col-1,level+1,tmp,cell);\n end\n end\n end\n end\nelse disp(n)\nend\nif level>0 && row>1\n cell(level) = cell(level)+1;\n cumsum = cumsum + 1;\n if cell(level) 1, \n % Run nhidden times sequentially\n \n R = Y;\n A = zeros(noutput,nhidden);\n B = zeros(ninput,nhidden);\n C = zeros(1,nhidden);\n for i=1:nhidden,\n [A(:,i),B(:,i),C(i)] = sparse_bls(X,R,1,lambda1,lambda2,VERBOSE);\n if i < nhidden, % deflate\n Z = B(:,i)'*X + C(i); % hidden activations\n R = R - A(:,i)*Z; % Y activations after deflation\n end\n if VERBOSE,\n fprintf('done %d out of %d; sparsity %g\\n',i,nhidden,length(find(B(:,i)))/ninput);\n end\n end\nelse\n\n % Run for a single hidden unit\n \n B = zeros(ninput,1);\n C = 0;\n iter = 0;\n maxiter = 1000;\n tol = nhidden*noutput*(1e-10);\n \n % Initialize A to first principal component of Y\n \n optseig.disp = 0;\n if nsamples < noutput,\n [d1,d2] = eigs(Y'*Y,[],1,'LM',optseig);\n A = Y*d1;\n A = A/sqrt(A'*A);\n else\n [A,d2] = eigs(Y*Y',[],1,'LM',optseig);\n end\n \n% A = randn(size(A)); % random\n% A = A/sqrt(A'*A);\n\n Aold = A;\n while iter < maxiter,\n\t \n if VERBOSE > 1,\n fprintf(' now starting iteration %d\\n',iter+1);\n end\n \n Z = A'*Y; % reconstruct Z given A from output Y\n \n % Use elastic net code to fit reconstructed Z given input X\n \n [B,C] = elastic(X,Z,lambda1,lambda2,options,B,C);\n\n% opts = glmnetSet;\n% opt.alpha = 1;\n% opts.lambda = lambda1;\n% res = glmnet(X',Z','gaussian',opts);\n% B = res.beta;\n% C = res.a0;\n% m = ft_mv_glmnet('validator',ft_mv_crossvalidator('nfolds',0.66,'metric','coefdet'),'alpha',1,'family','gaussian');\n% m = m.train(X',Z');\n% B = m.weights(1:(end-1));\n% C = m.weights(end);\n \n Z = B'*X + C; % reconstruct Z given B and C\n \n % Find optimal A under constraint A'*A = 1\n \n Syz = Y*Z'/nsamples;\n denom = sqrt(Syz'*Syz);\n if denom,\n A = Syz/denom;\n else\n A = Aold;\n end\n if any(isnan(A(:))), % check...\n error('nans!!!\\n');\n end\n \n if sumsqr(A - Aold) < tol,\n if VERBOSE > 1,\n fprintf(' done!!\\n',iter+1);\n end\n\t\t iter = maxiter;\n else\n\t iter = iter + 1;\n Aold = A;\n end\n end\nend\n\n\n% Parse outputs\n\nif nargout > 3,\n Z = B'*X + C'*ones(1,nsamples);\n Ypredict = A*Z;\nend", "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/pls/sparse_bls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.6907862661693369}} {"text": "\nclear all; close all; clc\n\ntrainingData = csvread('cs-training.csv' , 1 , 1);\ntraining_X = trainingData(:, 2:11); training_y = trainingData(:, 1);\n\n\n\nsixCol = find(training_X(:, 5) ~= training_X(:, 5));\nNsixCol = find(training_X(: , 5) == training_X(:, 5));\n\ntraining_X(sixCol , 5) = 1.0 * sum(training_X(NsixCol , 5)) / size(NsixCol , 1);\n\n\neleCol = find(training_X(: , 10) ~= training_X(: , 10));\nNeleCol = find(training_X(: , 10) == training_X(: , 10));\n\n\ntraining_X(eleCol , 10) = 1.0 * sum(training_X(NeleCol , 10)) / size(NeleCol , 1);\n\n[training_X , mu , sigma] = featureNormalize(training_X);\n\n[m, n] = size(training_X);\n\ntraining_X = [ones(m, 1) training_X];\ninitial_theta = zeros(n + 1, 1);\n\nlambda = 1;\n\noptions = optimset('GradObj', 'on', 'MaxIter', 500);\n\n[theta, J, exit_flag] = ...\n\tfminunc(@(t)(costFunctionReg(t, training_X, training_y, lambda)), initial_theta, options);\n\t\n\np = predict(theta, training_X);\n\nfprintf('Train Accuracy: %f\\n', mean(double(p == training_y)) * 100);\n\n\n%\"--------------------Test for TestingData-------------------------------\"\n\ntestData = csvread('cs-test.csv' , 1 , 2);\ntest_X = testData;\n[tm , tn] = size(test_X);\n\nsixCol = find(test_X(:, 5) ~= test_X(: , 5));\nNsixCol = find(test_X(: , 5) == test_X(: , 5));\n\ntest_X(sixCol , 5) = 1.0 * sum(test_X(NsixCol , 5)) / size(NsixCol , 1);\n\n\neleCol = find(test_X(: , 10) ~= test_X(: , 10));\nNeleCol = find(test_X(: , 10) == test_X(: , 10));\n\n\ntest_X(eleCol , 10) = 1.0 * sum(test_X(NeleCol , 10)) / size(NeleCol , 1);\n\n[test_X , mu , sigma] = featureNormalize(test_X);\n\ntest_X = [ones(tm , 1) test_X];\n\n\n\nprediction = double(sigmoid(test_X * theta));\n\nindex = [1:tm]';\n\ndlmwrite('result.csv' , [index , prediction]);\n\n\n\n\n\n\n\n\n\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/Logistic Regression/mlclass-ex2/GiveMeSomeCredit/credit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809304, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6907862616400432}} {"text": "function [prices, stdErrs] = Price_MC_Barrier_Strikes_func(Spath, call, down, H, Kvec, M, mult, rebate, r, T)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% About: Calculates Knock-out Barrier option prices for vector of strikes, given the simulatd paths \n% This version Allows for a rebate. \n% Note: to price knock-in options, use parity\n% Returns: prices and standard errors for each of the supplied strikes\n% Author: Justin Lars Kirkby\n%\n% -----------------\n% Params\n% -----------------\n% Spath = paths of underlying, dimension N_sim x M+1, where M = number of time steps (since includes S_0)\n% call = 1 for call (else put)\n% down = 1 for down and out, else up and out\n% H = Barrier \n% Kvec = strike vector\n% M = number of monitoring points, e.g. 252 for \"daily\" monitoring\n% mult = time partitioning multiplier to reduce bias (e.g. mult = 2 or 5)\n% rebate = rebate which is paid upon barrier breach, e.g. 5.0\n% r = Interest rate\n% q = dividend yield\n% T = Time (in years)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nprices = zeros(length(Kvec),1);\nstdErrs = zeros(length(Kvec),1);\nN_sim = size(Spath,1); % number of paths\n\nknock_time = zeros(N_sim,1); % time of knock-out\n\nM_mult = M*mult; %time partitioning to reduce bias\ndt_mult = T/M_mult;\n\nif down == 1 % down and out\n for n = 1:N_sim\n for m=1:mult:M_mult+1\n if Spath(n,m) < H\n knock_time(n) = (m-1)*dt_mult;\n break\n end\n end\n end\nelse %up and out\n for n = 1:N_sim\n for m=1:mult:M_mult+1\n if Spath(n,m) > H\n knock_time(n) = (m-1)*dt_mult;\n break\n end\n end\n end \nend\n\nif rebate > 0\n disc_rebate = rebate*exp(-r*knock_time).*(knock_time>0); % discounted rebate\nelse\n disc_rebate = 0; \nend\n\nfor k = 1:length(Kvec)\n K = Kvec(k);\n if call ==1\n \tpayoffs = exp(-r*T)*max(0, Spath(:,M_mult+1) - K).*(knock_time==0) + disc_rebate;\n \n else\n payoffs = exp(-r*T)*max(0, K - Spath(:,M_mult+1)).*(knock_time==0) + disc_rebate;\n end\n \n prices(k) = mean(payoffs);\n stdErrs(k) = std(payoffs) / sqrt(N_sim);\nend\n\n\nend\n\n", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/Monte_Carlo/Barrier/Price_MC_Barrier_Strikes_func.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6907862525814555}} {"text": "function [ v, more ] = simplex_lattice_layer_point_next ( n, c, v, more )\n\n%*****************************************************************************80\n%\n%% SIMPLEX_LATTICE_LAYER_POINT_NEXT: next simplex lattice layer point.\n%\n% Discussion:\n%\n% The simplex lattice layer L is bounded by the lines\n%\n% 0 <= X(1:N),\n% L - 1 < sum X(1:N) / C(1:N) <= L.\n%\n% In particular, layer L = 0 always contains just the origin.\n%\n% This function returns, one at a time, the points that lie within \n% a given simplex lattice layer.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 08 July 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the spatial dimension.\n%\n% Input, integer C(N+1), coefficients defining the \n% lattice layer in entries 1 to N, and the laver index in C(N+1). \n% The coefficients should be positive, and C(N+1) must be nonnegative.\n%\n% Input/output, integer V(N). On first call for a given layer,\n% the input value of V is not important. On a repeated call for the same\n% layer, the input value of V should be the output value from the previous \n% call. On output, V contains the next lattice layer point.\n%\n% Input/output, logical MORE. On input, set MORE to FALSE to indicate\n% that this is the first call for a given layer. Thereafter, the input\n% value should be the output value from the previous call. On output,\n% MORE is TRUE if the returned value V is a new point.\n% If the output value is FALSE, then no more points were found,\n% and V was reset to 0, and the lattice layer has been exhausted.\n%\n\n%\n% Treat layer C(N+1) = 0 specially.\n%\n if ( c(n+1) == 0 )\n if ( ~more )\n v(1:n) = 0;\n more = 1;\n else\n more = 0;\n end\n return\n end\n%\n% Compute the first point.\n%\n if ( ~more )\n\n v(1) = ( c(n+1) - 1 ) * c(1) + 1;\n v(2:n) = 0;\n more = 1;\n\n else\n\n c1n = i4vec_lcm ( n, c );\n\n rhs1 = c1n * ( c(n+1) - 1 );\n rhs2 = c1n * c(n+1);\n%\n% Try to increment component I.\n%\n for i = 1 : n\n\n v(i) = v(i) + 1;\n\n v(1:i-1) = 0;\n\n if ( 1 < i )\n v(1) = rhs1;\n for j = 2 : n\n v(1) = v(1) - ( c1n / c(j) ) * v(j);\n end\n v(1) = floor ( ( c(1) * v(1) ) / c1n );\n v(1) = max ( v(1), 0 );\n end\n\n lhs = 0;\n for j = 1 : n\n lhs = lhs + ( c1n / c(j) ) * v(j);\n end\n\n if ( lhs <= rhs1 )\n v(1) = v(1) + 1;\n lhs = lhs + c1n / c(1);\n end\n\n if ( lhs <= rhs2 )\n return\n end\n\n end\n\n v(1:n) = 0;\n more = 0;\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/geometry/simplex_lattice_layer_point_next.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6907820311607049}} {"text": "function LC_map(lat,lon,maxlat,minlat,maxlon,minlon)\n \n %LC_MAP plot a map using a Lambert Conformal projection\n %\n % LC_MAP(lat,lon,maxlat,minlat,maxlon,minlon)\n %\n % Function to plot a map using a Lambert Conformal projection\n % with two standard parallels which are chosen to be 1/4 of the\n % vertical span of the map from the top (phi1) and bottom (phi2).\n % The standard meridian is chosen to be the center meridian of\n % the map.\n %\n % where * lat & lon: array of latitudes and longitudes of map feature\n %\t * maxlat & minlat: maximum and minimum latitude of map\n %\t * maxlon & minlon: maximum and minimum longitude of map\n %\t (remember: South & West are negative!)\n %\n %\tThe line type and line width can be set using the following\n %\tglobal variables: \"line_type\" & \"line_width\".\n %\tIf these global variables are not set, it will use the\n %\tfollowing defaults: line_type = '-' & line_width = [0.5]\n \n report_this_filefun();\n \n global scale\n global phi0 lambda0 phi1 phi2\n global maxlatg minlatg maxlong minlong\n global line_type line_width\n \n ZG = ZmapGlobal.Data;\n % grab globals\n torad = ZG.torad;\n \n \n maxlatg = maxlat; minlatg = minlat;\n maxlong = maxlon; minlong = minlon;\n \n % set some constants\n scale = 1;\n \n % get the Standard Parallels and Center Coordinates\n phi1 = (minlat + ((maxlat - minlat) / 4)) * torad;\n phi2 = (maxlat - ((maxlat - minlat) / 4)) * torad;\n phi0 = (phi1 + phi2) / 2;\n lambda0 = ((minlon + maxlon) / 2) * torad;\n \n % find index of all points which are valid for this map & that are\n % not seperator points (ie: NaN)\n index = find(minlat < lat & lat < maxlat & minlon < lon & lon < maxlon &...\n isfinite(lat) & isfinite(lon));\n \n % convert all valid points to cartesian coordinates\n if index > 0\n [x(index) y(index)] = lc_tocart(lat(index),lon(index));\n end\n \n % reinsert the segment seperator points (ie: NaN)\n idxzero = find(x == 0 & y == 0);\n \n if idxzero > 0\n x(idxzero) = ones(size(x(idxzero))) * NaN;\n y(idxzero) = ones(size(y(idxzero))) * NaN;\n end\n \n % keep in memory if HOLD was on or off to put it back the way it was\n % after the plot\n if ishold\n hold_flag = 1;\n else\n hold_flag = 0;\n end\n \n lc_borde('-k',2)\n set(gca,'NextPlot','add')\n \n lc_grid(':',0.20)\n \n if isempty(line_type), line_type = '-k'; end\n if isempty(line_width), line_width = [0.5]; end\n plot(x,y,'-k','LineWidth',line_width)\n \n axis('equal')\n set(gca,'Visible','off')\n set(gcf,'PaperPosition',[1 .5 9 6.9545])\n \n % put HOLD back the way it was before this function was called\n if hold_flag\n set(gca,'NextPlot','add')\n else\n set(gca,'NextPlot','replace')\n end\n \nend\n\n\nfunction lc_borde(line_type,line_thick)\n \n %LC_PLOT_BORDER\n %\n %\tLC_plot_border(line_type,line_thick)\n %\n %\tFunction to plot a border on the map generated by LC_MAP\n %\tLINE_TYPE is any of the line types used by the PLOT command.\n %\tLINE_THICK is the width of the line in \"points\".\n %\t (1 point = 1/72 inch).\n %\tIf no values are given, it will use the defaults: '-' & 2.\n %\n %\tNOTE: The LC_MAP function has to have been called first\n %\tto set some required global variables.\n \n global maxlatg minlatg maxlong minlong\n \n if nargin < 2\n line_thick = 2;\n if nargin < 1\n line_type = '-';\n end\n end\n \n bdlon(1:100) = minlong:(maxlong-minlong)/99:maxlong;\n bdlon(101:200) = ones(1,100) * maxlong;\n bdlon(201:300) = maxlong:-(maxlong-minlong)/99:minlong;\n bdlon(301:400) = ones(1,100) * minlong;\n \n bdlat(1:100) = ones(1,100) * maxlatg;\n bdlat(101:200) = maxlatg:-(maxlatg-minlatg)/99:minlatg;\n bdlat(201:300) = ones(1,100) * minlatg;\n bdlat(301:400) = minlatg:(maxlatg-minlatg)/99:maxlatg;\n \n [xbd, ybd] = lc_tocart(bdlat,bdlon);\n \n plot(xbd,ybd,line_type,'LineWidth',line_thick)\n \nend\n\n\nfunction lc_grid(line_type,line_width)\n \n %LC_PLOT_GRID\n %\n %\tLC_plot_grid(line_type,line_width)\n %\n %\tFunction to plot a grid on the map generated by LC_MAP\n %\tThis function sets the size of the grid automatically according\n %\tto the scale of the map.\n %\tLINE_TYPE is the grid line style as available for the PLOT command\n %\t(ie: [ - | -- | : | -. ]). The default is [ - ].\n %\tLINE_WIDTH is the line thickness to be used for the grid. It has\n %\tto be a value > [0.01].\n %\n %\tNOTE: The LC_MAP function has to have been called before\n %\tyou can use this function as it needs some global variables\n %\tto be set.\n \n global maxlatg minlatg maxlong minlong\n \n if nargin < 2\n line_width = [0.01];\n if nargin < 1\n line_type = '-';\n end\n end\n \n dlat = maxlatg - minlatg;\n dlon = maxlong - minlong;\n \n % figure out the grid increment for latitude and longitude\n if fix(dlat / 5) >= 1\n latinc = infix(dlat / 5);\n else\n if 2.5 < round(dlat) && round(dlat) <= 5\n latinc = 1;\n elseif 1.5 < round(dlat) && round(dlat) <= 2.5\n latinc = 1/2;\n else\n latinc = 1/4;\n end\n end\n \n if fix(dlon / 5) >= 1\n loninc = infix(dlon / 5);\n else\n if 2.5 < round(dlon) && round(dlon) <= 5\n loninc = 1;\n elseif 1.5 < round(dlon) && round(dlon) <= 2.5\n loninc = 1/2;\n else\n loninc = 1/4;\n end\n end\n \n % figure out at which latitude/longitude the grid starts\n % This is the best trick I found to do this in one step!\n ylatgr1 = ceil(minlatg/latinc)*latinc;\n xlongr1 = ceil(minlong/loninc)*loninc;\n \n % plot the parallel grid & labels\n k = 1;\n while ylatgr1 + (latinc * (k-1)) < maxlatg\n xlatgr = minlong:dlon/99:maxlong;\n ylatgr = ones(1,100) .* (ylatgr1 + (latinc * (k-1)));\n [x, y] = lc_tocart(ylatgr,xlatgr);\n plot(x,y,'LineWidth',line_width,'LineStyle',line_type)\n text(x(1),y(1),[num2str(ylatgr(1)) blanks(1)],'Units','data',...\n 'HorizontalAlignment','right','VerticalAlignment','middle',...\n 'FontWeight','bold','FontSize',12)\n k = k + 1;\n end\n \n % plot the meridian grid & labels\n k = 1;\n while xlongr1 + (loninc * (k-1)) < maxlong\n xlongr = ones(1,100) .* (xlongr1 + (loninc * (k-1)));\n ylongr = minlatg:dlat/99:maxlatg;\n [x, y] = lc_tocart(ylongr,xlongr);\n plot(x,y,'LineWidth',line_width,'LineStyle',line_type)\n text(x(1),y(1),[num2str(xlongr(1),5) blanks(1)],'Units','data',...\n 'HorizontalAlignment','center','VerticalAlignment','top',...\n 'FontWeight','bold','FontSize',12)\n \n k = k + 1;\n end\n \nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/lc_map.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888304, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.6907820267061532}} {"text": "% Fig. 5.20 Feedback Control of Dynamic Systems, 5e \n% Franklin, Powell, Emami\n% Script to generate Figure 5.20\nn=1;\nd=[1 8 32 0];\nrlocus(n,d)\naxis([-10 6 -6 6])\nhold on\nx=[ 0 -2 0 -2];\ny=[0 2*sqrt(3) 0 -2*sqrt(3) ];\nplot(x,y)\nr=roots([1 4 16]);\nplot(r,'*')\ntitle('Fig. 5.20 Locus for L=1/s(s^2+8s+32)')\nz=0:.1:.9;\n wn=1:1:10;\n sgrid(z, wn)\n hold 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/9907-feedback-control-of-dynamic-systems-fifth-ed/fig5_20.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6907820265200738}} {"text": "function M = convectionTermSpherical1D(u)\n% This function uses the central difference scheme to discretize a 1D\n% convection term in the form \\grad (u \\phi) where u is a face vactor\n% It is for a cylindrical coordinate in the r direction\n%\n% SYNOPSIS:\n% M = convectionTermCylindrical1D(u)\n%\n% PARAMETERS:\n%\tu - FaceVariable \n%\n% RETURNS:\n%\n%\n% EXAMPLE:\n%\n% SEE ALSO:\n%\n\n% extract data from the mesh structure\nNr = u.domain.dims(1);\nG = 1:Nr+2;\nDXe = u.domain.cellsize.x(3:end);\nDXw = u.domain.cellsize.x(1:end-2);\nDXp = u.domain.cellsize.x(2:end-1);\n% rp = u.domain.cellcenters.x;\nrf = u.domain.facecenters.x;\n\n% define the vectors to stores the sparse matrix data\niix = zeros(3*(Nr+2),1);\njjx = zeros(3*(Nr+2),1);\nsx = zeros(3*(Nr+2),1);\n\n% reassign the east, west, north, and south velocity vectors for the\n% code readability\nue = u.xvalue(2:Nr+1).*DXp./(DXp+DXe).*rf(2:Nr+1).^2./(1/3*(rf(2:Nr+1).^3-rf(1:Nr).^3));\nuw = u.xvalue(1:Nr).*DXp./(DXp+DXw).*rf(1:Nr).^2./(1/3*(rf(2:Nr+1).^3-rf(1:Nr).^3));\n\n% calculate the coefficients for the internal cells\nAE = reshape(ue,Nr,1);\nAW = reshape(-uw,Nr,1);\nAPx = reshape((ue.*DXe-uw.*DXw)./DXp,Nr,1);\n\n% build the sparse matrix based on the numbering system\nrowx_index = reshape(G(2:Nr+1),Nr,1); % main diagonal x\niix(1:3*Nr) = repmat(rowx_index,3,1);\njjx(1:3*Nr) = [reshape(G(1:Nr),Nr,1); ...\n\t\treshape(G(2:Nr+1),Nr,1); reshape(G(3:Nr+2),Nr,1)];\nsx(1:3*Nr) = [AW; APx; AE];\n\n% build the sparse matrix\nkx = 3*Nr;\nM = sparse(iix(1:kx), jjx(1:kx), sx(1:kx), Nr+2, Nr+2);\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Discretization/convectionTermSpherical1D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6907820244788769}} {"text": "function [mag, freq, h, h2, peak_freq] = fft_calc(dat, TR, varargin)\n% Simple function to calculate the FFT power of a \n% data vector (dat) as a function of frequency,\n% given a sample-to-sample repetition time (TR)\n%\n% :Usage:\n% ::\n%\n% [mag, freq, line_handle, nyquist_line_handle, peak_freq] = fft_calc(dat, TR)\n%\n% Example:\n% Create and plot a sin wave:\n% ------------------------------------------------------------------\n% Fs = 1000; % Sampling frequency, e.g., Hz (samples/sec) \n% T = 1/Fs; % Sampling period (time between samples, e.g., sec)\n% L = 1000; % Length of signal (in samples)\n% t = (0:L-1)*T; % Time vector\n% \n% % Sine wave parameters\n% theta = 0; % Phase, in radians\n% F = 10; % Frequency of sin wave (cycles/sec)\n% \n% y = sin(2 * pi * F * t + theta);\n% \n% create_figure('sin wave');\n% plot(t, y)\n% xlabel('Time (sec)')\n%\n% Downsample the sin wave at new frequency Fs and plot signal and FFT:\n% ------------------------------------------------------------------\n% Fs = 20; % New sampling frequency\n% downsample_by = round(1000/Fs);\n% \n% figure;\n% plot(t, y, 'k-'); hold on\n% set(gcf, 'Position', [0 644 1358 231])\n% \n% plot(t(1:downsample_by:end), y(1:downsample_by:end), '.-', 'Color', [1 .3 .6], 'LineWidth', 2);\n% Nyquist = Fs/2;\n% title(sprintf('Sampling rate = %3.1f, Nyquist limit = %3.2f', Fs, Nyquist))\n% \n% figure; hold on;\n% [mag, freq, line_han] = fft_calc(y, 1/1000);\n% set(line_han, 'Color', 'k', 'LineWidth', 2, 'LineStyle', '-');\n% \n% [mag, freq, line_han] = fft_calc(y(1:downsample_by:end), 1/Fs);\n% set(line_han, 'Color', [1 .3 .6], 'LineWidth', 2, 'LineStyle', '-');\n% \n% set(gca, 'XLim', [0 (max(Fs, 1.2 * F))]);\n\n\n\nn = length(dat);\n\nif ~isempty(varargin)\n if ischar(varargin{1}) && strcmp(varargin{1}, 'plot')\n else\n doplot = varargin{1};\n end\nend\n\n% from matlab example\n% power = abs(Y(1:floor(n/2))).^2;\n% nyquist = 1/2;\n% freq = (1:n/2)/(n/2)*nyquist\n\nnyq = 1 ./ (2 * TR); % Sampling rate frequency / 2. TR = sample-to-sample time, 1/Fs\n\ntimepts = floor(n ./ 2);\n\nfreq = (0:timepts-1)/timepts * nyq;\n%freq = linspace(0, nyq, timepts)';\n\nmag = fft(dat); %real(abs(fft(dat)));\nmag = abs(mag(1:timepts)) .^ 2; % power\n\nmag = mag ./ sum(mag);\n\nh = plot(freq, mag, 'LineWidth', 2); \nxlabel('Frequency (Hz)')\ntitle('Frequency domain')\n\n% nyquist = Fs ./ 2; % Any signal faster than Nyquist freq will be aliased\nhold on\nh2 = plot_vertical_line(nyq);\nset(h2, 'LineStyle', ':')\n\npeak_freq = freq(mag == max(mag));\n\nend\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/diagnostics/fft_calc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6907820062885099}} {"text": "function X_rec = recoverData(Z, U, K)\n%RECOVERDATA Recovers an approximation of the original data when using the\n%projected data\n% X_rec = RECOVERDATA(Z, U, K) recovers an approximation the\n% original data that has been reduced to K dimensions. It returns the\n% approximate reconstruction in X_rec.\n%\n\n% You need to return the following variables correctly.\nX_rec = zeros(size(Z, 1), size(U, 1));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the approximation of the data by projecting back\n% onto the original space using the top K eigenvectors in U.\n%\n% For the i-th example Z(i,:), the (approximate)\n% recovered data for dimension j is given as follows:\n% v = Z(i, :)';\n% recovered_j = v' * U(j, 1:K)';\n%\n% Notice that U(j, 1:K) is a row vector.\n%\n\nX_rec = Z * U(:, 1:K)';\n\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-ex7/ex7/recoverData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.6907751038454681}} {"text": "function meshnd_example\n%MESHND_EXAMPLE example usage of meshnd and meshsparse.\n%\n% Example:\n% meshnd_example\n%\n% See also meshnd.\n\n% Copyright 2007, Timothy A. Davis, Univ. of Florida\n\nhelp meshnd\n\n% 2D mesh, compare with Cleve Moler's demos\n\nm = 7 ;\nn = 7 ;\n\n[G p pinv Gnew] = meshnd (m,n) ;\nfprintf ('Original mesh:\\n') ;\ndisp (G) ;\nfprintf ('Permuted node numbers using meshnd.m (nested dissection):\\n') ;\ndisp (Gnew) ;\n\nMoler = nested (n+2) ;\nMoler = Moler (2:n+1,2:n+1) ;\nfprintf ('Cleve Moler''s nested dissection ordering, using nested.m\\n') ;\ndisp (Moler) ;\nfprintf ('Difference between nested.m and meshnd.m:\\n') ;\ndisp (Gnew-Moler) ;\n\n% 2D and 3D meshes\n\nstencils = [5 9 7 27] ;\nmm = [7 7 7 7] ;\nnn = [7 7 7 7] ;\nkk = [1 1 7 7] ;\n\nfor s = 1:4\n\n m = mm (s) ;\n n = nn (s) ;\n k = kk (s) ;\n [G p] = meshnd (mm (s), nn (s), kk (s)) ;\n A = meshsparse (G, stencils (s)) ;\n C = A (p,p) ;\n parent = etree (C) ;\n try\n L = chol (C, 'lower') ;\n catch\n % old version of MATLAB\n L = chol (C)' ;\n end\n subplot (4,5,(s-1)*5 + 1) ;\n do_spy (A) ;\n if (k > 1)\n\ttitle (sprintf ('%d-by-%d-by-%d mesh, %d-point stencil', ...\n\t m, n, k, stencils (s))) ;\n else\n\ttitle (sprintf ('%d-by-%d mesh, %d-point stencil', ...\n\t m, n, stencils (s))) ;\n end\n subplot (4,5,(s-1)*5 + 2) ;\n do_spy (C) ;\n title ('nested dissection') ;\n subplot (4,5,(s-1)*5 + 3) ;\n treeplot (parent) ;\n title ('etree') ;\n xlabel ('') ;\n subplot (4,5,(s-1)*5 + 4) ;\n do_spy (L) ;\n title (sprintf ('Cholesky with nd, nnz %d', nnz (L))) ;\n try\n % use the built-in AMD\n p = amd (A) ;\n catch\n try\n % use AMD from SuiteSparse\n p = amd2 (A) ;\n catch\n % use the older built-in SYMAMD\n p = symamd (A) ;\n end\n end\n try\n L = chol (A (p,p), 'lower') ;\n catch\n % old version of MATLAB\n L = chol (A (p,p))' ;\n end\n subplot (4,5,(s-1)*5 + 5) ;\n do_spy (L) ;\n title (sprintf ('Cholesky with amd, nnz %d', nnz (L))) ;\n\nend\n\n%-------------------------------------------------------------------------------\n\nfunction do_spy (A)\n%DO_SPY use cspy(A) to plot a matrix, or spy(A) if cspy not installed.\ntry\n % This function is in CSparse. It generates better looking plots than spy.\n cspy (A) ;\ncatch\n spy (A) ;\nend\n\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/SuiteSparse/MESHND/meshnd_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.6907750918359291}} {"text": "function linplus_test60 ( )\n\n%*****************************************************************************80\n%\n%% TEST60 tests R8UT_DET, R8UT_INVERSE, R8UT_MXM, R8UT_RANDOM.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n n = 5;\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST60\\n' );\n fprintf ( 1, ' For an upper triangular matrix,\\n' );\n fprintf ( 1, ' R8UT_DET computes the determinant.\\n' );\n fprintf ( 1, ' R8UT_INVERSE computes the inverse.\\n' );\n fprintf ( 1, ' R8UT_MXM computes matrix products.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix order N = %d\\n', n );\n\n [ a, seed ] = r8ut_random ( n, n, seed );\n\n r8ut_print ( n, n, a, ' The matrix A:' );\n%\n% Compute the determinant.\n%\n det = r8ut_det ( n, a );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Determinant is %f\\n', det );\n%\n% Compute the inverse matrix B.\n%\n b = r8ut_inverse ( n, a );\n\n r8ut_print ( n, n, b, ' The inverse matrix B:' );\n%\n% Check\n%\n c = r8ut_mxm ( n, a, b );\n\n r8ut_print ( n, n, c, ' The product A * B:' );\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/linplus_test60.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.6907041127719059}} {"text": "function element_node = grid_t6_element ( nelemx, nelemy )\n\n%*****************************************************************************80\n%\n%% GRID_T6_ELEMENT produces a grid of pairs of 6 node triangles.\n%\n% Example:\n%\n% Input:\n%\n% NELEMX = 3, NELEMY = 2\n%\n% Output:\n%\n% ELEMENT_NODE =\n% 1, 3, 15, 2, 9, 8;\n% 17, 15, 3, 16, 9, 10;\n% 3, 5, 17, 4, 11, 10;\n% 19, 17, 5, 18, 11, 12;\n% 5, 7, 19, 6, 13, 12;\n% 21, 19, 7, 20, 13, 14;\n% 15, 17, 29, 16, 23, 22;\n% 31, 29, 17, 30, 23, 24;\n% 17, 19, 31, 18, 25, 24;\n% 33, 31, 19, 32, 25, 26;\n% 19, 21, 33, 20, 27, 26;\n% 35, 33, 21, 34, 27, 28.\n%\n% Grid:\n%\n% 29-30-31-32-33-34-35\n% |\\ 8 |\\10 |\\12 |\n% | \\ | \\ | \\ |\n% 22 23 24 25 26 27 28\n% | \\ | \\ | \\ |\n% | 7 \\| 9 \\| 11 \\|\n% 15-16-17-18-19-20-21\n% |\\ 2 |\\ 4 |\\ 6 |\n% | \\ | \\ | \\ |\n% 8 9 10 11 12 13 14\n% | \\ | \\ | \\ |\n% | 1 \\| 3 \\| 5 \\|\n% 1--2--3--4--5--6--7\n%\n% Reference Element T6:\n%\n% |\n% 1 3\n% | |\\\n% | | \\\n% S 6 5\n% | | \\\n% | | \\\n% 0 1--4--2\n% |\n% +--0--R--1-->\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NELEMX, NELEMY, the number of elements along the\n% X and Y directions. The number of elements generated will be\n% 2 * NELEMX * NELEMY.\n%\n% Output, integer ELEMENT_NODE(6,2*NELEMX*NELEMY), the nodes that form\n% each element.\n%\n\n%\n% Node labeling:\n%\n% NW---N--NE\n% | \\ |\n% W C E\n% | \\ |\n% SW---S--SE\n%\n element = 0;\n\n for j = 1 : nelemy\n for i = 1 : nelemx\n\n sw = 2 * ( j - 1 ) * ( 2 * nelemx + 1 ) + 2 * ( i - 1 ) + 1;\n w = sw + 2 * nelemx + 1;\n nw = sw + 2 * ( 2 * nelemx + 1 );\n\n s = sw + 1;\n c = sw + 1 + 2 * nelemx + 1;\n n = sw + 1 + 2 * ( 2 * nelemx + 1 );\n\n se = sw + 2;\n e = sw + 2 + 2 * nelemx + 1;\n ne = sw + 2 + 2 * ( 2 * nelemx + 1 );\n\n element = element + 1;\n\n element_node(1,element) = sw;\n element_node(2,element) = se;\n element_node(3,element) = nw;\n element_node(4,element) = s;\n element_node(5,element) = c;\n element_node(6,element) = w;\n\n element = element + 1;\n\n element_node(1,element) = ne;\n element_node(2,element) = nw;\n element_node(3,element) = se;\n element_node(4,element) = n;\n element_node(5,element) = c;\n element_node(6,element) = e;\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/fem2d_pack/grid_t6_element.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.690704106089181}} {"text": "function p02_demo ( iteration_max, h )\n\n%*****************************************************************************80\n%\n%% P02_DEMO runs the 2D demo problem #2, with mesh size H.\n%\n% Licensing:\n%\n% (C) 2004 Per-Olof Persson. \n% See COPYRIGHT.TXT for details.\n%\n% Modified:\n%\n% 06 February 2006\n%\n% Reference:\n%\n% Per-Olof Persson and Gilbert Strang,\n% A Simple Mesh Generator in MATLAB,\n% SIAM Review,\n% Volume 46, Number 2, June 2004, pages 329-345.\n%\n% Parameters:\n%\n% Input, integer ITERATION_MAX, the maximum number of iterations that DISTMESH\n% should take. (The program might take fewer iterations if it detects convergence.)\n%\n% Input, real H, the mesh spacing parameter.\n%\n if ( nargin < 1 )\n iteration_max = 200;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P02_DEMO - Note:\\n' );\n fprintf ( 1, ' No value of ITERATION_MAX was supplied.\\n' );\n fprintf ( 1, ' The default value ITERATION_MAX = %d will be used.\\n', ...\n iteration_max );\n end\n\n if ( nargin < 2 )\n h = 0.10;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P02_DEMO - Note:\\n' );\n fprintf ( 1, ' No value of H was supplied.\\n' );\n fprintf ( 1, ' The default value H = %f will be used.\\n', h );\n end\n%\n% Put the random number generator into a fixed initial state.\n%\n rand ( 'state', 111 );\n%\n% Set the rendering method for the current figure to Z-buffering.\n%\n set ( gcf, 'rend', 'z' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Problem 2:\\n' );\n fprintf ( 1, ' Unit circle with a hole, h = %f\\n', h )\n\n fd = @p02_fd;\n fh = @p02_fh;\n box = [-1.0, -1.0; 1.0, 1.0 ];\n fixed = [];\n\n [ p, t ] = distmesh_2d ( fd, fh, h, box, iteration_max, fixed );\n\n post_2d ( p, t, fh )\n%\n% Write a PostScript image of the triangulation.\n%\n [ node_num, junk ] = size ( p );\n [ tri_num, junk ] = size ( t );\n p = p';\n t = t';\n node_show = 0;\n triangle_show = 1;\n\n triangulation_order3_plot ( 'p02_mesh.eps', node_num, p, tri_num, ...\n t, node_show, triangle_show );\n%\n% Write a text file containing the nodes.\n%\n r8mat_write ( 'p02_nodes.txt', 2, node_num, p );\n%\n% Write a text file containing the triangles.\n%\n i4mat_write ( 'p02_elements.txt', 3, tri_num, 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/distmesh/p02_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.6907040884344139}} {"text": "%% DEMO_MixedTetHexMeshing\n% Below is a demonstration of how to create a mixed mesh consisting of\n% (linear) hexahedral and tetrahedral elements. The hexahedral mesh is\n% regular while the tetrahedral mesh is derived using TetGen. \n\n%% \n\nclear; close all; clc;\n\n%%\n% Plot settings for the examples below\nfontSize=20;\nfaceAlpha1=1;\nfaceAlpha2=0.3;\nplotColors=gjet(4);\n\n%%\n\nsearchRadius=6; \n\n%% CONVERTING A TRIANGULATED SURFACE TO AN IMAGE WITH DESIRED SIZE, VOXEL SIZE AND ORIGIN\n% Defining an example triangulated surface model\n\n[Fs,Vs]=stanford_bunny;\n\n%% \n% Setting control parameters\n\n% Defining the full set of possible control parameters\nvoxelSize=6; % The output image voxel size. \nimOrigin=min(Vs,[],1)-voxelSize;\nimMax=max(Vs,[],1)+voxelSize;\nimSiz=round((imMax-imOrigin)/voxelSize);\nimSiz=imSiz([2 1 3]); %Image size (x, y corresponds to j,i in image coordinates, hence the permutation)\n\n% Using |triSurf2Im| function to convert patch data to image data\n[M,~]=triSurf2Im(Fs,Vs,voxelSize,imOrigin,imSiz);\n\n%%\n% Plotting the results\n\nhf1=cFigure;\nsubplot(1,2,1);\ntitle('Closed triangulated surface','FontSize',fontSize);\nxlabel('X','FontSize',fontSize);ylabel('Y','FontSize',fontSize); zlabel('Z','FontSize',fontSize);\nhold on;\ngpatch(Fs,Vs,'g','none');\naxis equal; view(3); axis tight; grid on; set(gca,'FontSize',fontSize);\ncamlight('headlight'); lighting phong;\nset(gca,'fontSize',fontSize);\n\nsubplot(1,2,2);\ntitle('Boundary, intertior and exterior image','FontSize',fontSize);\nxlabel('X','FontSize',fontSize);ylabel('Y','FontSize',fontSize); zlabel('Z','FontSize',fontSize);\nhold on;\n\ngpatch(Fs,Vs,'g','none',faceAlpha2);\n\nL_plot=false(size(M));\nL_plot(:,:,round(size(M,3)/2))=1;\n[Fm,Vm,Cm]=ind2patch(L_plot,double(M),'sk');\n[Vm(:,1),Vm(:,2),Vm(:,3)]=im2cart(Vm(:,2),Vm(:,1),Vm(:,3),voxelSize*ones(1,3));\nVm=Vm+imOrigin(ones(size(Vm,1),1),:);\ngpatch(Fm,Vm,Cm,'k');\n\nL_plot=false(size(M));L_plot(round(size(M,1)/2),:,:)=1;\n[Fm,Vm,Cm]=ind2patch(L_plot,M,'si');\n[Vm(:,1),Vm(:,2),Vm(:,3)]=im2cart(Vm(:,2),Vm(:,1),Vm(:,3),voxelSize*ones(1,3));\nVm=Vm+imOrigin(ones(size(Vm,1),1),:);\ngpatch(Fm,Vm,Cm,'k');\n\nL_plot=false(size(M));L_plot(:,round(size(M,2)/2),:)=1;\n[Fm,Vm,Cm]=ind2patch(L_plot,M,'sj');\n[Vm(:,1),Vm(:,2),Vm(:,3)]=im2cart(Vm(:,2),Vm(:,1),Vm(:,3),voxelSize*ones(1,3));\nVm=Vm+imOrigin(ones(size(Vm,1),1),:);\ngpatch(Fm,Vm,Cm,'k');\n\ncolormap(gray(3)); caxis([0 2]);\nhc=colorbar;\nset(hc,'YTick',[1/3 1 5/3]);\nset(hc,'YTickLabel',{'Exterior','Boundary','Intertior'});\nset(hc,'fontSize',fontSize);\naxis equal; view(3); axis tight; grid on; set(gca,'FontSize',fontSize);\nset(gca,'fontSize',fontSize);\ndrawnow;\n\n%% GET HEXAHEDRAL ELEMENT SET\n\nL_model=(M==2); %Interior&Boundary choosen here\n \n%Defining erosion/dilation kernel\nk=3;\np=k-round(k./2);\nhb=zeros(3,3);\nhb(2,2,2)=1;\nhb(2,2,1)=1;\nhb(2,2,3)=1;\nhb(1,2,2)=1;\nhb(3,2,2)=1;\nhb(2,3,2)=1;\nhb(2,1,2)=1;\n\nL_model_rep=zeros(size(L_model)+(2.*p));\nL_model_rep(p+(1:size(L_model,1)),p+(1:size(L_model,2)),p+(1:size(L_model,3)))=L_model;\nL_model_blur = convn(double(L_model_rep),hb,'valid');\nL_model=L_model_blur>=(sum(hb(:)));\n \n[E_hex,V_hex,C_hex]=ind2patch(L_model,M,'hu');\n\n% Convert Coordinates\n[V_hex(:,1),V_hex(:,2),V_hex(:,3)]=im2cart(V_hex(:,2),V_hex(:,1),V_hex(:,3),voxelSize*ones(1,3));\nV_hex=V_hex+imOrigin(ones(size(V_hex,1),1),:);\n\n% Use element2patch to get patch data to plot the model\n[F_hex_cut1,C_hex_F]=element2patch(E_hex,C_hex);\n\n%Pass through unique_patch to reduce \"weight\" of plot\n[Fp,Vp,~,~,~,F_count]=unique_patch(F_hex_cut1,V_hex,[],5);\nlogicUni=F_count==1; %Logic for boundary faces\n\nFq=Fp(logicUni,:);\nVq=Vp;\n[Fq,Vq,~]=patchCleanUnused(Fq,Vq);\n\n[Ft,Vt]=quad2tri(Fq,Vq,'b');\n\n%%\n% Plotting the results\n\nhf1=cFigure;\ntitle('Visualizing internal voxels=hexahedral elements','FontSize',fontSize);\nxlabel('X','FontSize',fontSize);ylabel('Y','FontSize',fontSize); zlabel('Z','FontSize',fontSize);\nhold on;\n\ngpatch(Fs,Vs,0.5*ones(1,3),'none',faceAlpha2);\ngpatch(Fq,Vq,plotColors(2,:),'k');\n\ncamlight('headlight'); lighting flat;\naxis equal; view(3); axis tight; grid on; set(gca,'FontSize',fontSize);\ndrawnow;\n\n%%\n\n%Joining surface sets\nF=[Fs;Ft+size(Vs,1)];\nV=[Vs;Vt];\nC_tet=[ones(size(Fs,1),1);2*ones(size(Ft,1),1)]; %Surface marker colors\n\n%% Get hole point\n[V_hole]=getInnerPoint(Ft,Vt,searchRadius,voxelSize/2,0);\nplotV(V_hole,'r.','MarkerSize',25);\n\n%% Get region point\n\nL_in=(M==1);\n\n[indInternal]=getInnerVoxel(double(L_in),searchRadius,0);\n\n[I_in,J_in,K_in]=ind2sub(size(L_in),indInternal); %Convert to subscript coordinates\n[X_in,Y_in,Z_in]=im2cart(I_in,J_in,K_in,voxelSize*ones(1,3));\nV_in=[X_in Y_in Z_in];\nV_in=V_in+imOrigin(ones(size(V_in,1),1),:);\n\nplotV(V_in,'k.','MarkerSize',25);\n\n%%\n% DEFINE FACE BOUNDARY MARKERS\nfaceBoundaryMarker=C_tet;\n\n%%\n% Define region points\nV_regions=[V_in];\n\n%%\n% Define hole points\nV_holes=[V_hole];\n\n%% \n% Regional mesh parameters\n[edgeLengths]=patchEdgeLengths(F,V);\nedgeLengthsMean=mean(edgeLengths);\nmeanProposedVolume=edgeLengthsMean^3./(6*sqrt(2)); %For regular tetrahedron\nregionA=meanProposedVolume;\n\n%% \n% CREATING THE SMESH STRUCTURE, meshing without the surface constraints\n% imposed by the -Y this time. \n\nstringOpt='-pq1.2AaY';\n\nmodelName='tetGenModel';\n\nmeshStruct.stringOpt=stringOpt;\nmeshStruct.Faces=F;\nmeshStruct.Nodes=V;\nmeshStruct.holePoints=V_holes;\nmeshStruct.faceBoundaryMarker=faceBoundaryMarker; %Face boundary markers\nmeshStruct.regionPoints=V_regions; %region points\nmeshStruct.regionA=regionA;\nmeshStruct.minRegionMarker=2; %Minimum region marker\nmeshStruct.modelName=modelName;\n\n%% \n% Mesh model using tetrahedral elements using tetGen (see:\n% )\n\n[meshOutput]=runTetGen(meshStruct); %Run tetGen \n\n%% \n% Access model element and patch data\nF_tet_cut1=meshOutput.faces;\nV_tet=meshOutput.nodes;\nC_tet=meshOutput.faceMaterialID;\nE_tet=meshOutput.elements;\n\nindBoundary=meshOutput.facesBoundary(meshOutput.boundaryMarker==1,:);\nindBoundary=unique(indBoundary(:));\n\n%% MERGING NODE SETS\n\nV=[V_tet;V_hex];\nE_hex=E_hex+size(V_tet,1);\n\n[~,V,ind1,ind2]=mergeVertices(F_tet_cut1,V);\n\nE_tet=ind2(E_tet);\nE_hex=ind2(E_hex);\nindBoundary=ind2(indBoundary);\n\nE={E_tet, E_hex};\n\n%% \n% Visualizing mesh\n\ncFigure;\ntitle('Mixed TET/HEX mesh','FontSize',fontSize);\n\n%Selecting half of the model to see interior\nX=V(:,2); XE=mean(X(E{1}),2);\nL=XE>mean(X);\n[F_tet_cut1,~]=element2patch(E{1}(L,:),C_tet(L));\n\n%Selecting half of the model to see interior\nX=V(:,2); XE=mean(X(E{2}),2);\nL=XE>mean(X);\n[F_hex_cut1,~]=element2patch(E{2}(L,:),C_hex(L));\n\ngpatch(F_tet_cut1,V,plotColors(1,:),'k');\ngpatch(F_hex_cut1,V,plotColors(2,:),'k');\ngpatch(Fs,Vs,0.5*ones(1,3),'none',faceAlpha2);\n\naxisGeom(gca,fontSize);\ncamlight headlight;\nset(gca,'FontSize',fontSize);\ndrawnow; \n\n%%\n% Smoothing meshes \n\ncPar.Method='LAP';\ncPar.n=25;\ncPar.RigidConstraints=indBoundary;\n\n[F1,~]=element2patch(E{1},[]);\n[F1,~,~]=uniqueIntegerRow(F1);\n[F2,~]=element2patch(E{2},[]);\n[F2,~,~]=uniqueIntegerRow(F2);\n[~,IND_V1,~]=tesIND(F1,V,0);\n[~,IND_V2,~]=tesIND(F2,V,0);\nIND_V=[IND_V1 IND_V2];\n\n[VS]=tesSmooth([],V,IND_V,cPar);\n\n%% \n% Visualizing mesh\n\nhf=cFigure;\ntitle('Mixed TET/HEX mesh','FontSize',fontSize);\n\n%Selecting half of the model to see interior\nX=V(:,2); XE=mean(X(E{1}),2);\nL=XE>mean(X);\n[F_tet_cut1,~]=element2patch(E{1}(L,:),C_tet(L));\n\n%Selecting half of the model to see interior\nX=V(:,2); XE=mean(X(E{2}),2);\nL=XE>mean(X);\n[F_hex_cut1,~]=element2patch(E{2}(L,:),C_hex(L));\n\nhp1=gpatch(F_tet_cut1,VS,plotColors(1,:),'k');\nhp2=gpatch(F_hex_cut1,VS,plotColors(2,:),'k');\ngpatch(Fs,Vs,0.5*ones(1,3),'none',faceAlpha2);\n\naxisGeom(gca,fontSize);\ncamlight headlight;\nset(gca,'FontSize',fontSize);\ndrawnow; \n\n\n%%\n% Set up animation\nnSteps=25; %Number of animation steps\nX=V(:,2);\nXE1=mean(X(E{1}),2);\nXE2=mean(X(E{2}),2);\n\nanimStruct.Time=linspace(0,1,nSteps); %Time vector\ncutLevel=linspace(min(X(:)),max(X(:)),nSteps); %Property to set\n\nfor q=1:1:nSteps %Step through time \n cutLevelNow=cutLevel(q); %The current cut level \n \n L1=XE1>cutLevelNow;\n [F_tet_cut1,~]=element2patch(E{1}(L1,:));\n\n L2=XE2>cutLevelNow;\n [F_hex_cut1,~]=element2patch(E{2}(L2,:));\n \n %Set entries in animation structure\n animStruct.Handles{q}=[hp1 hp2]; %Handles of objects to animate\n animStruct.Props{q}={'Faces','Faces'}; %Properties of objects to animate\n animStruct.Set{q}={F_tet_cut1,F_hex_cut1}; %Property values for to set in order to animate\nend\n\n%Add animation layer\nanim8(hf,animStruct);\n\n%% \n%\n% <>\n% \n% GIBBON \n% \n% Kevin M. Moerman (kevinmoerman@hotmail.com)\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/docs/DEMO_MixedTetHexMeshing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.6907040833546588}} {"text": "\n%% Author: epokh\n%% Website: www.epokh.org/drupy\n%% This software is under GPL\n\n%%This example show the use of DH parameters, omogeneous transformations\n%%jacobian,static force analysis and plot functions.\n\n%%An example of a 6 degree of freedom robot: 6 revolute joints\n%% Solve a DH problem for forward kinematics\n%%Joint variables\nclf\ntheta1=-30;\ntheta2=-25;\ntheta3=-50;\ntheta4=-45;\ntheta5=-20;\ntheta6=95;\n\n%%link length\na3=2.5;\na4=2.1;\na5=1.8;\n\n%%First way to calculate the forward kinematics\nT01=DHmatrix(theta1,0,0,0);\nT12=DHmatrix(0,0,0,-90);\nT23=DHmatrix(theta2,0,a3,0);\nT34=DHmatrix(theta3,0,a4,0);\nT45=DHmatrix(theta4,0,a5,0);\nT56=RotZ(theta5)*RotX(theta6);\n\nTuh1=T01*T12*T23*T34*T45*T56;\n\n\n%%A second fast way to calculate it\nT01=RotZ(theta1);\nT12=RotX(-90);\nT23=RotZ(theta2)*Tras(a3,0,0);\nT34=RotZ(theta3)*Tras(a4,0,0);\nT45=RotZ(theta4)*Tras(a5,0,0);\nT56=RotZ(theta5)*RotX(theta6);\n\n% %%This shows how to use the plot system\n% plotT(T01);\n% pause(2);\n% plotT(T01*T12);\n% pause(2);\n% plotT2(T01*T12,T01*T12*T23);\n% pause(2);\n% plotT2(T01*T12*T23,T01*T12*T23*T34);\n% pause(2);\n% plotT2(T01*T12*T23*T34,T01*T12*T23*T34*T45);\n% pause(2);\n% plotT2(T01*T12*T23*T34*T45,T01*T12*T23*T34*T45*T56);\n\nTuh2=T01*T12*T23*T34*T45*T56;\n\n%%now calculate the jacobian\nJ6=jacobianT6([T01,T12,T23,T34,T45,T56],['R','R','R','R','R','R']);\n\n\nF=[2.1;3.2;4.5;10.1;0.5;0.07];\nT=staticForce(J6,F);\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/14886-robotic-toolbox/sixDOFmanipulator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6906859962598044}} {"text": "close all;\nclear all;\nclc;\nrng('default');\n% Create the directory for storing images\n[status_code,message,message_id] = mkdir('bin');\n\n% Signal space \nN = 1000;\n% Number of measurements\nM = 200;\n% Sparsity levels\nKs = 4:120;\n\n% Number of dictionaries to be created\nnum_dict_trials = 100;\n% Number of signals to be created for each dictionary\nnum_signal_trials = 20;\n\n% Number of trials for each K\nnum_trials = num_dict_trials * num_signal_trials;\n\nomp_success_rates_with_k = zeros(numel(Ks), 1);\nomp_average_iterations_with_k = zeros(numel(Ks), 1);\nomp_maximum_iterations_with_k = zeros(numel(Ks), 1);\n\nLs = [2, 4, 6, 8]\nnum_ls = numel(Ls)\ngomp_success_rates_with_k = zeros(numel(Ks), num_ls);\ngomp_average_iterations_with_k = zeros(numel(Ks), num_ls);\ngomp_maximum_iterations_with_k = zeros(numel(Ks), num_ls);\n\nfor K=Ks\n % Trial number\n nt = 0;\n omp_num_successes = 0;\n omp_num_iterations = 0;\n omp_max_iterations = 0;\n\n gomp_num_successes = zeros(num_ls, 1);\n gomp_num_iterations = zeros(num_ls, 1);\n gomp_max_iterations = zeros(num_ls, 1);\n\n for ndt=1:num_dict_trials\n % Sensing matrix\n Phi = spx.dict.simple.gaussian_dict(M, N);\n for nst=1:num_signal_trials\n nt = nt + 1;\n % Construct the signal generator.\n gen = spx.data.synthetic.SparseSignalGenerator(N, K);\n % Generate bi-uniform signals\n x = gen.gaussian;\n % Measurement vectors\n y = Phi.apply(x);\n\n\n % OMP solver instance\n solver = spx.pursuit.single.OrthogonalMatchingPursuit(Phi, K);\n % Solve the sparse recovery problem\n omp_result = solver.solve(y);\n % Solution vector\n z = omp_result.z;\n omp_stats = spx.commons.sparse.recovery_performance(Phi, K, y, x, z);\n omp_num_iterations = omp_num_iterations + omp_result.iterations;\n if omp_max_iterations < omp_result.iterations\n omp_max_iterations = omp_result.iterations;\n end\n omp_num_successes = omp_num_successes + omp_stats.success;\n fprintf('K=%d, Trial: %d, OMP: %s, ', ...\n K, nt, spx.io.true_false_short(omp_stats.success));\n for nl=1:num_ls\n L = Ls(nl);\n % GOMP solver instance\n solver = spx.pursuit.single.GOMP(Phi, K);\n % Set the number of atoms to be selected in each iteration\n solver.L = L;\n % Solve the sparse recovery problem\n gomp_result = solver.solve(y);\n % Solution vector\n z = gomp_result.z;\n gomp_stats = spx.commons.sparse.recovery_performance(Phi, K, y, x, z);\n gomp_num_iterations(nl) = gomp_num_iterations(nl) + gomp_result.iterations;\n if gomp_max_iterations(nl) < gomp_result.iterations\n gomp_max_iterations(nl) = gomp_result.iterations;\n end\n gomp_num_successes(nl) = gomp_num_successes(nl) + gomp_stats.success;\n fprintf(' GOMP-%d:%s', ...\n L, spx.io.true_false_short(gomp_stats.success));\n end\n fprintf('\\n')\n end\n end\n omp_success_rate = omp_num_successes / num_trials;\n omp_average_iterations = omp_num_iterations / num_trials;\n omp_success_rates_with_k(K) = omp_success_rate;\n omp_average_iterations_with_k (K) = omp_average_iterations;\n omp_maximum_iterations_with_k(K) = omp_max_iterations;\n\n for nl=1:num_ls\n gomp_success_rate = gomp_num_successes(nl) / num_trials;\n gomp_average_iterations = gomp_num_iterations(nl) / num_trials;\n gomp_success_rates_with_k(K, nl) = gomp_success_rate;\n gomp_average_iterations_with_k (K, nl) = gomp_average_iterations;\n gomp_maximum_iterations_with_k(K, nl) = gomp_max_iterations(nl);\n end\nend\n\nsave('bin/omp_vs_gomp_comparison.mat');\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/experiments/gomp/ex_compare_algorithms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6906859933540206}} {"text": "% Fig. 8.10 Feedback Control of Dynamic Systems, 5e \n% Franklin, Powell, Emami\n%\n\nclear all;\nclose all;\n\nnumG=1;\ndenG=[1 0 0];\n\nnumD=[1 .2];\ndenD=[1 2];\n\nnum=conv(numG,numD);\nden=conv(denG,denD);\npoles=roots(den);\nzeros=roots(num);\n\n\nK1=0:.05:1.22;\nK2=[1.25 1.28]; % K for break-in and break-away points\nK3=1.5:5:100;\nK=[K1 K2 K3];\nKo=.81;\n\nr=rlocus(num,den,K);\nro=rlocus(num,den,Ko);\n\nplot(r,'-'),grid\naxis('square')\naxis([-2.5 .5 -1.5 1.5])\nhold on\nplot(ro,'k*')\nplot(-.2,0,'o')\nplot(-2,0,'x')\nplot(0,.01,'x')\nplot(0,-.01,'x')\ntitle('Fig. 8.10 s-plane locus vs. K')\nxlabel('Re(s)')\nylabel('Im(s)')\ntext(-2.3,-.7,'* K_c = 0.81') \nhold off\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/9907-feedback-control-of-dynamic-systems-fifth-ed/fig8_10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6906859873895206}} {"text": "function [x, infos] = recursive_nmu(V, rank, in_options)\n% Recursive non-negative matrix underapproximation (Recursive-NMU).\n%\n% The problem of interest is defined as\n%\n% min || V - WH ||_F^2,\n% where \n% {V, W, H} > 0 and WH <= V.\n%\n% Inputs:\n% matrix V\n% rank rank\n% options options\n% Cnorm Choice of the norm 1 or 2, default = 2.\n% Output:\n% w solution of w\n% infos information\n%\n% References:\n% N. Gillis and F. Glineur,\n% \"Using Underapproximations for Sparse Nonnegative Matrix Factorization,\"\n% Pattern Recognition 43 (4), pp. 1676-1687, \n% 2010.\n%\n% N. Gillis and R.J. Plemmons,\n% \"Dimensionality Reduction, Classification, and Spectral Mixture Analysis \n% using Nonnegative Underapproximationm,\"\n% Optical Engineering 50, 027001, \n% 2011.\n% \n%\n% This file is part of NMFLibrary.\n%\n% This file has been ported from \n% recursiveNMU.m at https://gitlab.com/ngillis/nmfbook/-/tree/master/algorithms\n% by Nicolas Gillis (nicolas.gillis@umons.ac.be)\n%\n% Ported by T.Fukunaga and H.Kasai on June 24, 2022 for NMFLibrary\n%\n% Change log: \n%\n%\n\n\n % set dimensions and samples\n [m, n] = size(V);\n % set local options\n local_options = [];\n local_options.Cnorm = 2;\n local_options.inner_max_epoch = 200;\n \n % check input options\n if ~exist('in_options', 'var') || isempty(in_options)\n in_options = struct();\n end \n % merge options\n options = mergeOptions(get_nmf_default_options(), local_options); \n options = mergeOptions(options, in_options);\n\n % initialize factors\n init_options = options;\n [init_factors, ~] = generate_init_factors(V, rank, init_options); \n W = init_factors.W;\n H = init_factors.H; \n M = V;\n\n % initialize\n method_name = 'Recursive-NMU';\n epoch = 0; \n grad_calc_count = 0;\n \n if options.verbose > 0\n fprintf('# %s: started ...\\n', method_name); \n end \n \n % select disp_freq \n disp_freq = set_disp_frequency(options); \n \n % initialize for this algorithm\n % (here)\n \n % store initial info\n clear infos;\n [infos, f_val, optgap] = store_nmf_info(V, W, H, [], options, [], epoch, grad_calc_count, 0);\n \n if options.verbose > 1\n fprintf('%s: k = 00, Epoch = 0000, cost = %.16e, optgap = %.4e\\n', method_name, f_val, optgap); \n end \n \n % set start time\n start_time = tic();\n prev_time = start_time;\n \n % main loop\n for k = 1 : rank\n \n % initialize epoch\n epoch = 0;\n \n % initialize (x,y) with an optimal rank-one NMF of M\n [w, s, h] = svds(M, 1);\n ws = abs(w) * sqrt(s);\n hs = abs(h) * sqrt(s);\n W(:, k) = ws;\n H(k, :) = hs'; \n \n % initialize Lagrangian variable lambda\n R = M - ws * hs';\n lambda = max(zeros(size(R)), -R);\n \n % inner loop\n while (optgap > options.tol_optgap) && (epoch < options.inner_max_epoch) \n\n % update ws and hs\n A = M - lambda;\n \n if options.Cnorm == 1\n % l_1 norm minimization\n ws = max(0, (wmedian(A, hs)));\n hs = max(0, (wmedian(A', ws)));\n \n elseif options.Cnorm == 2 \n % l_2 norm minimization \n ws = max(0, A * hs);\n ws = ws / (max(ws) + 1e-16);\n hs = max(0, (A' * ws) / (ws' * ws));\n end\n \n % update lambda\n if sum(ws) ~= 0 && sum(hs) ~= 0\n R = M - ws * hs';\n W(:, k) = ws;\n H(k, :) = hs'; \n lambda = max(0, lambda - R / ((epoch + 1) + 1));\n else\n lambda = lambda / 2;\n ws = W(:, k);\n hs = H(k, :)'; \n end\n\n\n % measure elapsed time\n elapsed_time = toc(start_time); \n \n % measure gradient calc count\n grad_calc_count = grad_calc_count + m*n; \n\n % update epoch\n epoch = epoch + 1;\n\n % store info\n % total iteration is computed as (k - 1) * options.inner_max_epoch + epoch\n W_rec = W(:, 1:k);\n H_rec = H(1:k, :); \n [infos, f_val, optgap] = store_nmf_info(V, W_rec, H_rec, [], options, infos, (k - 1) * options.inner_max_epoch + epoch, grad_calc_count, elapsed_time); \n \n % display infos\n if options.verbose > 2\n if ~mod(epoch, disp_freq)\n fprintf('%s: k = %02d, Epoch = %04d, cost = %.16e, optgap = %.4e, time = %e\\n', method_name, k, (k - 1) * options.inner_max_epoch + epoch, f_val, optgap, elapsed_time - prev_time);\n end\n end \n\n end\n\n M = max(0, M - ws * hs');\n\n % store info\n % total iteration is computed as (k - 1) * options.inner_max_epoch + epoch\n W_rec = W(:, 1:k);\n H_rec = H(1:k, :); \n [infos, f_val, optgap] = store_nmf_info(V, W_rec, H_rec, [], options, infos, (k - 1) * options.inner_max_epoch + epoch, grad_calc_count, elapsed_time); \n\n % display infos\n if options.verbose > 1\n if ~mod(epoch, disp_freq)\n fprintf('%s: k = %02d, Epoch = %04d, cost = %.16e, optgap = %.4e, time = %e\\n', method_name, k, (k - 1) * options.inner_max_epoch + epoch, f_val, optgap, elapsed_time - prev_time);\n end\n end \n\n prev_time = elapsed_time;\n\n end\n\n if options.verbose > 0\n if optgap < options.tol_optgap\n fprintf('# Recursive-NMU: Optimality gap tolerance reached: f_val = %.4e < f_opt = %.4e (%.4e)\\n', f_val, options.f_opt, options.tol_optgap);\n elseif (k - 1) * options.inner_max_epoch + epoch == rank * options.inner_max_epoch\n fprintf('# Recursive-NMU: Max epoch reached (%g).\\n', rank * options.inner_max_epoch);\n end \n end\n \n x.W = W;\n x.H = H; \n \nend\n\n% WMEDIAN computes an optimal solution of\n%\n% min_x || A - xy^T ||_1, y >= 0\n%\n% where A has dimension (m x n), x (m) and y (n),\n% in O(mn log(n)) operations. Should be done in O(mn)...\n\nfunction x = wmedian(A,y)\n\n % Reduce the problem for positive entries of y\n indi = y > 1e-16;\n A = A(:, indi);\n y = y(indi); \n [m, n] = size(A);\n A = A ./ repmat(y', m, 1);\n y = y / sum(y);\n\n % Sort rows of A, m*O(n log(n)) operations\n [As, Inds] = sort(A, 2);\n\n % Construct matrix of ordered weigths\n Y = y(Inds);\n\n % Extract the median\n actind = 1 : m;\n i = 1; \n sumY = zeros(m, 1);\n x = zeros(m, 1);\n while ~isempty(actind) % O(n) steps... * O(m) operations\n % sum the weitghs\n sumY(actind, :) = sumY(actind, :) + Y(actind, i);\n % check which weitgh >= 0\n supind = (sumY(actind, :) >= 0.5);\n % update corresponding x\n x(actind(supind)) = As(actind(supind), i);\n % only look reminding x to update\n actind = actind(~supind);\n i = i + 1;\n end\nend\n", "meta": {"author": "hiroyuki-kasai", "repo": "NMFLibrary", "sha": "ed44132dfe1b5495df685006b42259f0bd16bea3", "save_path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary/NMFLibrary-ed44132dfe1b5495df685006b42259f0bd16bea3/solver/nn_under_approx/recursive_nmu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6906859844837374}} {"text": "% Fig. 6.10 Feedback Control of Dynamic Systems, 6e \n% Franklin, Powell, Emami\n%\n\nclear all;\n%close all;\nclf\n\nnum=10;\nden=conv([1 0],[1 0.4 4]);\nw=logspace(-1,2,100);\n[m,p]=bode(num,den,w);\n\nfigure(1)\nloglog(w,m);\nxlabel('\\omega (rad/sec)');\nylabel('Magnitude');\ntitle('Fig. 6.10 Bode plot for a TF with a complex pole :(a) magnitude');\nbodegrid;\n%pause;\nfigure(2)\nsemilogx(w,p);\ngrid;\nxlabel('\\omega (rad/sec)');\nylabel('Phase');\ntitle('Fig. 6.10 (b) phase');\nbodegrid;", "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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig6_10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6906724560164872}} {"text": "function [ft2] = mm22ft2(mm2)\n% Convert area from square millimeters to square feet.\n% Chad A. Greene 2012\nft2 = mm2*0.00001076391041671;", "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/35258-unit-converters/unit_converters/mm22ft2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6906724455065967}} {"text": "function dst_scalars=nsst_scalars(L,shear_f,lpfilt)\n% Since the nonsubsampled descrite shearlet transform is not orthogonal\n% this function computes the noise level scalars of the transform with\n% assigned parameters. \n%\n% Inputs:\n% \n% L - size of image decomposition\n%\n% shear_f - the cell array containing the shearing filters \n%\n%\n% lpfilt - lpfilt is the filter to be used for the Laplacian\n% Pyramid/ATrous decomposition using the codes\n% written by Arthur Cunha\n%\n% Output:\n%\n% dst_scalars - the cell array containing the scalars of \n% estimated noise levels for a white Gaussian noise\n% of standard deviation 1 transform coefficients\n% using Monte Carlo method with one iteration. \n%\n% Code contributors: Glenn R. Easley, Demetrio Labate, and Wang-Q Lim.\n% Copyright 2011 by Glenn R. Easley. All Rights Reserved.\n%\n\nnoise=randn(L,L);\nlevel=length(shear_f);\n\n% LP decomposition\ny_noise = atrousdec(noise,lpfilt,level);\n\ndst_scalars=cell(1,level+1);\ndst_noise=y_noise{1}; \ndst_scalars{1}=median(abs(dst_noise(:) - median(dst_noise(:))))/.6745;\n\n\nfor i=1:level, \n l=size(shear_f{i},3);\n for k=1:l, \n dst_noise=conv2p(shear_f{i}(:,:,k),y_noise{i+1});\n dst_scalars{i+1}(k)=median(abs(dst_noise(:) - median(dst_noise(:))))/.6745; \n end\nend\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/Shearlet/Toolbox/nsst_scalars.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6906724424237061}} {"text": "function [inv_A, r, PR, PL] = invertProjection(A, epsilon)\n% Inverts a general matrix A using the pseudoinverse\n%\n% USAGE:\n%\n% [inv_A, r, PR, PL] = invertProjection(A, epsilon)\n% INPUTS:\n% A: general matrix\n% epsilon: default = 1e-10\n%\n% OUTPUTS:\n% inv_A: the pseudoinverse of `A`\n% r: the rank of `A`\n% PR: the projection matrix onto the `range(A)`\n% PL: the projection matrix onto the `null(A')`\n\nif nargin < 2\n epsilon = 1e-10;\nend\n[m, n] = size(A);\n\nif 1\n %[U, S, V] = svd(A); % not working, uncommented line below - Lemmer\n %[U, S, V] = svds(A,min(size(A))); % Bugfix due to svd convergence problems\n [U, S, V] = svd(full(A),'econ'); %from Michael Saunders code\n r = sum(sum(abs(S) > epsilon));\n inv_S = diag(1 ./ S(abs(S) > epsilon));\n inv_A = V(:, 1:r) * inv_S(1:r, 1:r) * U(:, 1:r)';\n PR = U(:, 1:r) * U(:, 1:r)';\n PL = U(:, (r+1):end) * U(:, (r+1):end)';\n \nelse\n %Michael Saunders code -TODO integrate this properly\n [U1,D1,V1,r] = subspaceSVD(A);\n PR=U1*U1';%projection matrix onto the range(A)\n PL=eye(m) - U1*U1';%projection matrix onto null(A')\n inv_A=pinv(A,1e-12);\nend\n % Michael Saunders code\n % [U1,D1,V1,r] = subspaceSVD(A);\n % PR=U1*U1';%projection matrix onto the range(A)\n % PL=eye(m) - U1*U1';%projection matrix onto the null(A')\n % inv_A=pinv(A,1e-12);", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/thermo/componentContribution/new/invertProjection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.690643186662856}} {"text": "function noise = noisevector(vlength,xcfunction,noisevariance)\n% function noise = noisevector(vlength,xcfunction,noisevariance)\n%\n% returns a noise vector of 'vlength' samples \n% with characteristics of the autocorrelation function that you specify\n% (must be same sampling rate as timeseries!)\n%\n% the vector is normalized such that the variance is what you specify\n% and the mean is zero\n%\n% vlength: vector length\n% xcfunction: any cross-correlation (i.e., noise autocorrelation) function\n% - also called a periodogram\n% - a 1/f function is generally good for fMRI data\n% noisevariance: desired variance of noise\n%\n% 2/11/01 Tor Wager\n\nif isempty(xcfunction), xcfunction = [1 0];,end\n\n% define series of random \"shocks\". Last one is time 1, paramount one is time 2, etc.\n% pad with zeros, because 1st shock has no history to influence it.\nxclength = size(xcfunction,2);\na = randn(1,vlength); a(end + 1:end + xclength) = 0;\n% the noise is the series of shocks multiplied by the autocorrelation function\n% so the current value of the system = weighted sum of past shocks, up to size of autocorr function\nfor i = 1:vlength\n noise(i) = dot(a(end-i-xclength+1:end-i),xcfunction');\nend\n\n\n% make sure that the variance is one and the mean is zero\n\nnoise = noise - mean(noise);\n\nnoise = noise / sqrt(var(noise));\n\n% now make the variance match your estimate of the variance\n\nnoise = noise * sqrt(noisevariance);\n\n%disp(['Noise variance is ' num2str(var(noise))])\n%figure;plot(noise)\n\nreturn\n\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/OptimizeDesign11/other_functions/noisevector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427860270573, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6906431810899113}} {"text": "function h=demirel(im,thr,T)\n%h=demirel(im,thr);\n%im is an input image, thr is a threshold between 0-1, T is the thickness \n%of the line to indicate the edge.\n%h is an uint8 balck and white image with values of 0 and 255.\n%This programme has been written by me, G. Anbarjafari (Shahab) months ago\n%but finalized today 17-11-2008.\n%(c) Demirel and Anbarjafari - 2008\n\n[sx,sy,sz]=size(im);\n\nif sz~=1\n im1=not(im2bw(rgb2gray(im),thr));\nelse\n im1=not(im2bw(im,thr));\nend\n\nSZ=2*T+1;\nX=zeros(SZ,SZ);\nX((SZ+1)/2,:)=ones(1,SZ);\nX(:,(SZ+1)/2)=ones(SZ,1);\nX((SZ+1)/2,(SZ+1)/2)=2;\nQ = filter2(X,im1);\nQ([find(Q<1)])=0;\nQ([find(Q>0)])=1;\n\nh=uint8(abs(double(Q)-double(im1))*255);\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/22233-demirel-edge-detector/DemirelEgde/demirel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6906431762499906}} {"text": "function g = p03_g ( n, x )\n\n%*****************************************************************************80\n%\n%% P03_G evaluates the gradient for problem 3.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 October 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the values of the variables.\n%\n% Output, real G(N), the gradient of the objective function.\n%\n y = p03_yvec ( );\n\n g = zeros ( n, 1 );\n\n for i = 1 : 15\n\n d1 = 0.5 * ( i - 1 );\n d2 = 3.5 - d1 - x(3);\n arg = - 0.5 * x(2) * d2 * d2;\n t = x(1) * exp ( arg ) - y(i);\n\n g(1) = g(1) + 2.0 * exp ( arg ) * t;\n g(2) = g(2) - x(1) * exp ( arg ) * t * d2 * d2;\n g(3) = g(3) + 2.0 * x(1) * x(2) * exp ( arg ) * t * d2;\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/test_opt/p03_g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6906431721430948}} {"text": "function kern = matern32KernParamInit(kern)\n\n% MATERN32KERNPARAMINIT MATERN32 kernel parameter initialisation.\n% The Matern class of kernels is a wide class with different\n% degrees of freedom parameters. This is the specific case where nu\n% = 3/2.\n%\n% Given \n% r = sqrt((x_i - x_j)'*(x_i - x_j))\n% \n% We have\n% k(x_i, x_j) = sigma2*(1+sqrt(3)*r/l)*exp(-sqrt(3)*r/l)\n%\n% The parameters are sigma2, the process variance (kern.variance),\n% and l, the length scale (kern.lengthScale).\n% FORMAT\n% DESC initialises the matern kernel with nu=3/2\n% kernel structure with some default parameters.\n% ARG kern : the kernel structure which requires initialisation.\n% RETURN kern : the kernel structure with the default parameters placed in.\n%\n% SEEALSO : kernCreate, kernParamInit\n%\n% COPYRIGHT : Neil D. Lawrence, 2006\n\n% KERN\n\nkern.variance = 1;\nkern.lengthScale = 1;\nkern.nParams = 2;\n\nkern.transforms.index = [1 2];\nkern.transforms.type = optimiDefaultConstraint('positive');\n\nkern.isStationary = true;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/matern32KernParamInit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.7718435030872967, "lm_q1q2_score": 0.6906374382077045}} {"text": "%% Author: epokh\n%% Website: www.epokh.org/drupy\n%% This software is under GPL\n\nclc;\nclose all;\n%%This example shows a trajectory planning example for the \n%%antropomorphic arm\n\n%%Link length\na2=1;\na3=1;\n\n%%End effector initial point\n%% by inverse kinematics we have the joint starting variables\n[theta1s,theta2s,theta3s]=inverseAntro(1,0.5,0.3,a2,a3);\n\n%%End effector final point\n%% by inverse kinematics we have the joint ends variables\n[theta1e,theta2e,theta3e]=inverseAntro(0.1,0.5,0.3,a2,a3);\n\n%%3 joint variables: 3 trajectories\n%% We want the movement be completed in 6 seconds\ntstart=0;\ntend=6;\ntime=[tstart tend];\n\n\n% \n% %%Check the forward kinematics and the multiple inverse solutions\nfigure(1);\nT01=DHmatrix(theta1s(1),0,0,45);\nT12=DHmatrix(theta2s(1),0,a2,0);\nT23=DHmatrix(theta3s(1),0,a3,0);\nTuh1=T01*T12*T23;\nfigure(1);\nhold on;\nplotT(Tuh1);\nT01=DHmatrix(theta1s(2),0,0,45);\nT12=DHmatrix(theta2s(2),0,a2,0);\nT23=DHmatrix(theta3s(2),0,a3,0);\nTuh2=T01*T12*T23;\nplotT(Tuh2);\n\n\n%%Once we have the kinematics and paths we can plot the movements!\n%%Use a spline interpolation\n\npp1 = spline(time,[0 theta1s(1) theta1e(1) 0]);\npp2 = spline(time,[0 theta2s(1) theta2e(1) 0]);\npp3 = spline(time,[0 theta3s(1) theta3e(1) 0]);\ntime=linspace(tstart,tend);\nfigure(2);\nsubplot(3,1,1);\ntitle('Position Theta1');\nplot(time,fnval(pp1,time),'b');\nxlabel('Time');\nylabel('Theta1');\nsubplot(3,1,2);\ntitle('Position Theta2');\nplot(time,fnval(pp2,time),'b');\nxlabel('Time');\nylabel('Theta2');\nsubplot(3,1,3);\ntitle('Position Theta3');\nplot(time,fnval(pp3,time),'b');\nxlabel('Time');\nylabel('Theta3');\n\nfigure(3);\nfor k=1:1:length(time)\nclf;\ntheta1=fnval(pp1,time(k));\ntheta2=fnval(pp2,time(k));\ntheta3=fnval(pp3,time(k));\nT01=DHmatrix(theta1,0,0,45);\nT12=DHmatrix(theta2,0,a2,0);\nT23=DHmatrix(theta3,0,a3,0);\nTuh1=T01*T12*T23;\nplotT(T01);\nplotT2(T01,T01*T12);\nplotT2(T01*T12,T01*T12*T23);\npause(0.1);\ntitle('Arm trajectory');\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/14886-robotic-toolbox/testJointSpaceTrajectory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025423, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6906374360421982}} {"text": "% fastregress - perform fast regression and return p-value\n%\n% Usage:\n% [ypred, alpha, rsq, B] = myregress(x, y, plotflag);\n%\n% Inputs\n% y - y values\n% x - x values\n% plotflag - [0|1] plot regression\n%\n% Outputs\n% ypred - y prediction\n% alpha - significance level\n% R^2 - r square\n% slope - slope of the fit\n%\n% Arnaud Delorme, 25 Feb 2003\n\nfunction [ypred, alpha, rsq, B, BINT] = fastregress(x, y, plotflag)\n \n if nargin < 1\n help fastregress; return;\n end;\n \n % this part is useless but still works\n %B=polyfit(x, y, 1); % B is the slope\n %ypred = polyval(B,x); % predictions\n %dev = y - mean(y); % deviations - measure of spread\n %SST = sum(dev.^2); % total variation to be accounted for\n %resid = y - ypred; % residuals - measure of mismatch\n %SSE = sum(resid.^2); % variation NOT accounted for\n %rsq = 1 - SSE/SST; % percent of error explained\n % see the page http://www.facstaff.bucknell.edu/maneval/help211/fitting.html\n\n [B,BINT,R,RINT,STATS] = regress(y(:), [ones(length(x),1) x(:)]);\n alpha = STATS(3);\n rsq = STATS(1);\n \n %note that we also have \n %ypred = [ones(size(x,2),1) x(:)]*B;\n ypred = x*B(2) + B(1);\n\n % B(1) contain the offset, B(2) the slope\n B = B(2);\n\n if nargin > 2\n hold on;\n [ynew tmp] = sort(ypred);\n xnew = x(tmp);\n plot(xnew, ynew, 'r');\n legend(sprintf('R^2=%f', rsq), sprintf('p =%f', alpha));\n end;", "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/miscfunc/fastregress.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.690637433876692}} {"text": "clear; clc;\n%% desired signal\n% n = (1:1000)';\n%#codegen\n% s = sin(0.075*pi*n);\n\n%% noise signal\n% v = 0.8*randn(1000,1); % Random noise part.\n% ar = [1,1/2]; % Autoregression coefficients.\n% v1 = filter(1,ar,v); % Noise signal. Applies a 1-D digital filter.\n\n%% primary input (noise corrupted signal)\n% x = s + v1;\n[x,fs1] = audioread('x14.wav');\n\n%% reference input \n% ma = [1, -0.8, 0.4 , -0.2];\n% v2 = filter(ma,1,v);\n[v2,fs1] = audioread('x15.wav');\n\n%% adaptive filter\n% initialization\nL = 512;\n% lms = dsp.LMSFilter(L,'Method','LMS');\nnlms = dsp.LMSFilter(L,'Method','Normalized LMS','LeakageFactor',1,'AdaptInputPort',false,...\n'WeightsResetInputPort',false,'WeightsOutput','Last');\n% filter step size\n% [mumaxlms,mumaxmselms] = maxstep(lms,x);\n[mumaxnlms,mumaxmsenlms] = maxstep(nlms,x); % maxstep function of dsp.LMSFilter\n% lms.StepSize = mumaxmselms/30; \nnlms.StepSize = mumaxmsenlms/6; \n\n%% filter with the adaptive filter\n% [ylms,elms,wlms] = lms(v2,x);\n[ynlms,enlms,wnlms] = nlms(v2,x);\n\n%% compute the optimal solution (FIR Wiener filter)\n% bw = firwiener(L-1,v2,x); % Optimal FIR Wiener filter\n% yw = filter(bw,1,v2); % Estimate of x using Wiener filter\n% ew = x - yw; % Estimate of actual sinusoid\n\n%% plot\n% primary input\n% plot(n(900:end),x(900:end),'k:')\n% xlabel('Time index (n)');\n% ylabel('Amplitude');\nplot([1:length(x)], x, 'm:')\nxlabel('Time index (n)');\nylabel('Amplitude');\n\n% denoised result\nhold on;\n% plot(n(900:end),[ew(900:end), elms(900:end),enlms(900:end)]);\n% legend('Wiener filter denoised sinusoid',...\n% 'LMS denoised sinusoid','NLMS denoised sinusoid');\n% xlabel('Time index (n)');\n% ylabel('Amplitude');\nplot([1:length(x)], enlms);\nxlabel('Time index (n)');\nylabel('Amplitude');\nlegend('primary input','denoised result');\nhold off;\n\n%% reset nlms\nreset(nlms);\n\n%% convergence investigation through learning curve\n% M = 10; % Decimation factor\n% msenlms = msesim(nlms,v2,x,M);\n% figure;\n% plot(1:M:x(end),msenlms)\n% legend('LMS learning curve','NLMS learning curve')\n% xlabel('Time index (n)');\n% ylabel('MSE');\n\n%% theorectical learning curves\n% reset(nlms);\n% figure;\n% [mmselms,emselms,meanwlms,pmselms] = msepred(nlms,v2,x,M);\n% plot(1:M:x(end),[mmselms*ones(500,1),emselms*ones(500,1),...\n% pmselms,mselms])\n% legend('MMSE','EMSE','predicted LMS learning curve',...\n% 'LMS learning curve')\n% xlabel('Time index (n)');\n% ylabel('MSE');", "meta": {"author": "CharlesThaCat", "repo": "acoustic-interference-cancellation", "sha": "edb394499ea6f9c96445a3e9613bd64a854c289e", "save_path": "github-repos/MATLAB/CharlesThaCat-acoustic-interference-cancellation", "path": "github-repos/MATLAB/CharlesThaCat-acoustic-interference-cancellation/acoustic-interference-cancellation-edb394499ea6f9c96445a3e9613bd64a854c289e/Fullband processing/NLMS_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.690637433876692}} {"text": "function traj = simulateCannon(init,param)\n\nv0 = init.speed;\nth0 = init.angle;\n\nc = param.c; %Quadratic drag coefficient\nnGrid = param.nGrid;\n\n% Set up initial conditions for ode45\nx0 = 0; y0 = 0; %Start at the origin\ndx0 = v0*cos(th0);\ndy0 = v0*sin(th0);\nif dy0 < 0, error('Cannot point cannon through ground! sin(th0) > 0 required.'); end;\n\n% Set up arguments for ode45\nuserFun = @(t,z)cannonDynamics(t,z,c); %Dynamics function\ntSpan = [0,100]; %Never plan on reaching final time\nz0 = [x0;y0;dx0;dy0]; %Initial condition\noptions = odeset('Events',@groundEvent,'Vectorized','on');\n\n% Run a simulation\nsol = ode45(userFun, tSpan, z0, options);\n\n% Extract the solution on uniform grid:\ntraj.t = linspace(sol.x(1), sol.x(end), nGrid);\nz = deval(sol,traj.t);\ntraj.x = z(1,:); \ntraj.y = z(2,:); \ntraj.dx = z(3,:); \ntraj.dy = z(4,:); \n\nend", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/TrajectoryOptimization/Example_1_Cannon/simulateCannon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6906374197885302}} {"text": "function [cvx_optval,P,q,r,X,lambda] = cheb(A,b,Sigma) %#ok\n\n% Computes Chebyshev lower bounds on probability vectors\n%\n% Calculates a lower bound on the probability that a random vector\n% x with mean zero and covariance Sigma satisfies A x <= b\n%\n% Sigma must be positive definite\n%\n% output arguments:\n% - prob: lower bound on probability\n% - P,q,r: x'*P*x + 2*q'*x + r is a quadratic function\n% that majorizes the 0-1 indicator function of the complement\n% of the polyhedron,\n% - X, lambda: a discrete distribution with mean zero, covariance\n% Sigma and Prob(X not in C) >= 1-prob\n\n%\n% maximize 1 - Tr Sigma*P - r\n% s.t. [ P q ] [ 0 a_i/2 ]\n% [ q' r - 1 ] >= tau(i) * [ a_i'/2 -b_i ], i=1,...,m\n% taui >= 0\n% [ P q ]\n% [ q' r ] >= 0\n%\n% variables P in Sn, q in Rn, r in R\n%\n\n[ m, n ] = size( A ); %#ok\ncvx_begin sdp quiet\n variable P(n,n) symmetric\n variables q(n) r tau(m)\n dual variables Z{m}\n maximize( 1 - trace( Sigma * P ) - r )\n subject to\n for i = 1 : m,\n qadj = q - 0.5 * tau(i) * A(i,:)';\n radj = r - 1 + tau(i) * b(i);\n [ P, qadj ; qadj', radj ] >= 0 : Z{i}; %#ok\n end\n [ P, q ; q', r ] >= 0; %#ok\n tau >= 0; %#ok\ncvx_end\n\nif nargout < 4,\n return\nend\n\nX = [];\nlambda = [];\nfor i=1:m\n Zi = Z{i};\n if (abs(Zi(3,3)) > 1e-4)\n lambda = [lambda; Zi(3,3)]; %#ok\n X = [X Zi(1:2,3)/Zi(3,3)]; %#ok\n end;\nend;\nmu = 1-sum(lambda);\nif (mu>1e-5)\n w = (-X*lambda)/mu;\n W = (Sigma - X*diag(lambda)*X')/mu;\n [v,d] = eig(W-w*w');\n d = diag(d);\n s = sum(d>1e-5);\n if (d(1) > 1e-5)\n X = [X w+sqrt(s)*sqrt(d(1))*v(:,1) ...\n w-sqrt(s)*sqrt(d(1))*v(:,1)];\n lambda = [lambda; mu/(2*s); mu/(2*s)];\n elseif (d(2) > 1e-5)\n X = [X w+sqrt(s)*sqrt(d(2))*v(:,2) ...\n w-sqrt(s)*sqrt(d(2))*v(:,2)];\n lambda = [lambda; mu/(2*s); mu/(2*s)];\n else\n X = [X w];\n lambda = [lambda; mu];\n end;\nend;\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/Ch07_statistical_estim/cheb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6906374111265047}} {"text": "function [tfr,t,f] = tfrbud(x,t,N,g,h,sigma,trace);\n%TFRBUD\tButterworth time-frequency distribution.\n%\t[TFR,T,F]=TFRBUD(X,T,N,G,H,SIGMA,TRACE) computes the Butterworth \n%\tdistribution of a discrete-time signal X, or the\n%\tcross Butterworth representation between two signals. \n% \n%\tX : signal if auto-BUD, or [X1,X2] if cross-BUD.\n%\tT : time instant(s) (default : 1:length(X)).\n%\tN : number of frequency bins (default : length(X)).\n%\tG : time smoothing window, G(0) being forced to 1. \n%\t (default : Hamming(N/4)). \n%\tH : frequency smoothing window, H(0) being forced to 1.\n%\t (default : Hamming(N/4)). \n%\tSIGMA : kernel width (default : 1).\n%\tTRACE : if nonzero, the progression of the algorithm is shown\n% (default : 0).\n%\tTFR : time-frequency representation. When called without \n% output arguments, TFRBUD runs TFRQVIEW.\n%\tF : vector of normalized frequencies.\n% \n%\tExample :\n%\t sig=fmlin(128,0.05,0.3)+fmlin(128,0.15,0.4); \n%\t g=tftb_window(9,'Kaiser'); h=tftb_window(27,'Kaiser'); \n%\t t=1:128; tfrbud(sig,t,128,g,h,3.6,1);\n% \n%\tSee also all the time-frequency representations listed in\n%\t the file CONTENTS (TFR*)\n\n%\tF. Auger, May-August 1994, July 1995.\n%\tCopyright (c) 1996 by CNRS (France).\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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nif (nargin == 0),\n error('At least 1 parameter required');\nend;\n[xrow,xcol] = size(x);\nif (xcol==0)|(xcol>2),\n error('X must have one or two columns');\nend\n\nif (nargin <= 2),\n N=xrow;\nelseif (N<0),\n error('N must be greater than zero');\nelseif (2^nextpow2(N)~=N),\n fprintf('For a faster computation, N should be a power of two\\n');\nend;\n\nhlength=floor(N/4); hlength=hlength+1-rem(hlength,2); \nglength=floor(N/10);glength=glength+1-rem(glength,2);\n\nif (nargin == 1),\n t=1:xrow; g = tftb_window(glength); h = tftb_window(hlength); sigma = 1.0; trace = 0;\nelseif (nargin == 2)|(nargin == 3),\n g = tftb_window(glength); h = tftb_window(hlength); sigma = 1.0; trace = 0;\nelseif (nargin == 4),\n h = tftb_window(hlength); sigma = 1.0; trace = 0;\nelseif (nargin == 5),\n sigma = 1.0; trace = 0;\nelseif (nargin == 6),\n trace = 0;\nend;\n\n[trow,tcol] = size(t);\nif (trow~=1),\n error('t must only have one row'); \nend; \n\n[grow,gcol]=size(g); Lg=(grow-1)/2; \nif (gcol~=1)|(rem(grow,2)==0),\n error('G must be a smoothing window with odd length'); \nend;\n\n[hrow,hcol]=size(h); Lh=(hrow-1)/2; h=h/h(Lh+1);\nif (hcol~=1)|(rem(hrow,2)==0),\n error('H must be a smoothing window with odd length');\nend;\n\nif (sigma<=0.0),\n error('SIGMA must be strictly positive'); \nend;\n\ntaumax = min([round(N/2),Lh]); tau = 1:taumax; points = -Lg:Lg;\nBudKer = exp(-kron( abs(points.'), 1.0 ./ (2.0*tau/sqrt(sigma))));\nBudKer = diag(g) * BudKer;\n\ntfr= zeros (N,tcol) ; \nif trace, disp('Butterworth distribution'); end;\nfor icol=1:tcol,\n ti= t(icol); taumax=min([ti+Lg-1,xrow-ti+Lg,round(N/2)-1,Lh]);\n if trace, disprog(icol,tcol,10); end;\n tfr(1,icol)= x(ti,1) .* conj(x(ti,xcol));\n\n for tau=1:taumax,\n points= -min([Lg,xrow-ti-tau]):min([Lg,ti-tau-1]);\n g2 = BudKer(Lg+1+points,tau); g2=g2/sum(g2);\n R=sum(g2 .* x(ti+tau-points,1) .* conj(x(ti-tau-points,xcol)));\n tfr( 1+tau,icol)=h(Lh+tau+1)*R;\n R=sum(g2 .* x(ti-tau-points,1) .* conj(x(ti+tau-points,xcol)));\n tfr(N+1-tau,icol)=h(Lh-tau+1)*R;\n end;\n\n tau=round(N/2); \n if (ti<=xrow-tau)&(ti>=tau+1)&(tau<=Lh),\n points= -min([Lg,xrow-ti-tau]):min([Lg,ti-tau-1]);\n g2 = BudKer(Lg+1+points,tau); g2=g2/sum(g2);\n tfr(tau+1,icol) = 0.5 * ...\n (h(Lh+tau+1)*sum(g2 .* x(ti+tau-points,1) .* conj(x(ti-tau-points,xcol)))+...\n h(Lh-tau+1)*sum(g2 .* x(ti-tau-points,1) .* conj(x(ti+tau-points,xcol))));\n end;\nend; \n\nclear BudKer;\n\nif trace, fprintf('\\n'); end;\ntfr= fft(tfr); \nif (xcol==1), tfr=real(tfr); end ;\n\nif (nargout==0),\n tfrqview(tfr,x,t,'tfrbud',g,h,sigma);\nelseif (nargout==3),\n f=(0.5*(0:N-1)/N)';\nend;\n\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/tfrbud.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6906104266630021}} {"text": "function res = SumKL(p,K,L)\n%SUMKL Summation 'as if' computed in K-fold precision and stored in L results\n%\n% res = SumKL(p,K,L)\n%\n%On return, sum(res) approximates sum(p) with accuracy as if computed \n% in K-fold precision, where res comprises of L elements. \n% Default for L is 1.\n%\n%Implements algorithm SumKL from\n% S.M. Rump: Inversion of extremely ill-conditioned matrices in floating-point,\n% Japan J. Indust. Appl. Math. (JJIAM), 26:249-277, 2009.\n%\n%Reference implementation! Slow due to interpretation!\n%\n\n% written 06/23/08 S.M. Rump\n% modified 05/09/09 S.M. Rump rounding to nearest\n%\n\n e = 1e-30;\n if 1+e==1-e % fast check for rounding to nearest\n rndold = 0;\n else\n rndold = getround;\n setround(0)\n end\n\n if nargin==2\n L = 1;\n end\n \n n = length(p);\n for i=1:K-L\n p = VecSum(p);\n end\n res = zeros(1,L);\n for k=0:L-2\n p(1:n-k) = VecSum(p(1:n-k));\n res(k+1) = p(n-k);\n end\n res(L) = sum(p(1:n-L+1));\n \n if rndold\n setround(rndold)\n end\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/accsumdot/SumKL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.6906104266485683}} {"text": "% Compute the log intensity for the inverse link function g(f) = 1/(1+exp(-f)).\n%\n% The function is used in GLM likelihoods such as likPoisson, likGamma, likBeta\n% and likInvGauss.\n%\n% Copyright (c) by Hannes Nickisch, 2013-10-16.\n\nfunction varargout = glm_invlink_logit(f)\n varargout = cell(nargout, 1); % allocate the right number of output arguments\n [varargout{:}] = glm_invlink_logistic(f);\n if nargout>0\n elg = exp(varargout{1});\n varargout{1} = f - elg;\n if nargout>1\n dlg = varargout{2};\n varargout{2} = 1 - elg.*dlg;\n if nargout>2\n d2lg = varargout{3};\n varargout{3} = -elg.*(dlg.^2+d2lg);\n if nargout>3\n d3lg = varargout{4};\n varargout{4} = -elg.*(dlg.^3+3*d2lg.*dlg+d3lg);\n end\n end\n end\n end", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/gpml/util/glm_invlink_logit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6905998631453412}} {"text": "function vCubo = homo2cubo(vHomo) \n% homochoric to cubochoric coordinates \n%\n% Transforms homochoric coordinates of quaternions into cubochoric\n% coordinates. This mpas the ball of radius (3*pi/4)^(1/3)) to the cube\n% with edge length pi^(2/3).\n% \n% Input\n% xyz - homochoric coordinates (x,y,z) of N points of the ball \n%\n% Output\n% XYZ - cubochoric coordinates (X,Y,Z) of N points of the cube \n% \n\n% the actual mapping is only defined on one pyramid Pz (z>=abs(x),z>=abs(y)) \n% map other points by: \n% 1. transform coordinates, so that we get a point of Pz\n% 2. map the point \n% 3. apply the inverse transformation \n\n% for each point find out, which pyramid it lies in (1,2,3,4,5,6)\nrId = cuboRegionId(vHomo); \n\n% define permutaions (and inverse ones) for each region (pyramid)\npermRegion = [2 3 1; 3 2 1; 1 3 2; 3 1 2; 1 2 3; 2 1 3]; \nipermRegion = [3 1 2; 3 2 1; 1 3 2; 2 3 1; 1 2 3; 2 1 3];\n\n% apply the permutation on each row\nvHomo = vHomo(sub2ind(size(vHomo), ...\n (1:size(vHomo,1)).' * [1 1 1] ,permRegion(rId,:)));\n\n% map each point \np = sqrt(sum(vHomo.^2,2));\nD = sqrt(2 ./ (1 + abs(vHomo(:,3)) ./ p));\nE = sqrt(2 * vHomo(:,1).^2 + vHomo(:,2).^2);\nF = sqrt(abs(vHomo(:,1)) + E);\nG = sign(vHomo(:,1));\nH = sqrt(pi / 12);\nI = (6 / pi)^(1/6);\nK = D .* sqrt(E) .* F .* I;\n\nvCubo(:,1) = K .* G .* H;\nvCubo(:,2) = K ./ H .* (G .* atan(vHomo(:,2)./vHomo(:,1)) - atan(vHomo(:,2)./E));\nvCubo(:,3) = sign(vHomo(:,3)) .* p ./ I^2;\n\n% overwrite points with division by zero (occurs along the axes)\nisNull = (vHomo(:,1)==0);\nvCubo(isNull,:) = vHomo(isNull,:) / (6/pi)^(1/3);\n\n% apply the inverse permutations \nvCubo = vCubo(sub2ind(size(vCubo), ...\n (1:size(vCubo,1)).' * [1 1 1] , ipermRegion(rId,:)));\n\nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/geometry_tools/homo2cubo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6905998544239925}} {"text": "function x = ncc_abscissas_ab ( a, b, n )\n\n%*****************************************************************************80\n%\n%% NCC_ABSCISSAS_AB computes the Newton Cotes Closed abscissas for [A,B].\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 July 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, the endpoints of the interval.\n%\n% Input, integer N, the order of the rule.\n%\n% Output, real X(N), the abscissas.\n%\n if ( n == 1 )\n x(1) = 0.5 * ( b + a );\n return\n end\n\n for i = 1 : n\n x(i) = ( ( n - i ) * a ...\n + ( i - 1 ) * b ) ...\n / ( n - 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/interp/ncc_abscissas_ab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.8376199694135333, "lm_q1q2_score": 0.6905857880052038}} {"text": "function [node,elem]=meshgrid6(varargin)\n%\n% [node,elem]=meshgrid6(v1,v2,v3,...)\n%\n% mesh an ND rectangular lattice by splitting \n% each hypercube into 6 tetrahedra\n%\n% author: John D'Errico\n% URL: http://www.mathworks.com/matlabcentral/newsreader/view_thread/107191\n% modified by Qianqian Fang (q.fang at neu.edu)\n%\n% input:\n% v1,v2,v3,... - numeric vectors defining the lattice in\n% each dimension.\n% Each vector must be of length >= 1\n%\n% output:\n% node - factorial lattice created from (v1,v2,v3,...)\n% Each row of this array is one node in the lattice\n% elem - integer array defining simplexes as references to\n% rows of \"node\".\n%\n% example:\n% [node,elem]=meshgrid6(0:5,0:6,0:4);\n% plotmesh(node,elem);\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\n% dimension of the lattice\nn = length(varargin);\n\n% create a single n-d hypercube\n% list of node of the cube itself\nvhc=('1'==dec2bin(0:(2^n-1)));\n% permutations of the integers 1:n\np=perms(1:n);\nnt=factorial(n);\nthc=zeros(nt,n+1);\nfor i=1:nt\n thc(i,:)=find(all(diff(vhc(:,p(i,:)),[],2)>=0,2))';\nend\n\n% build the complete lattice\nnodecount = cellfun('length',varargin);\nif any(nodecount<2)\n error 'Each dimension must be of size 2 or more.'\nend\nnode = lattice(varargin{:});\n\n% unrolled index into each hyper-rectangle in the lattice\nind = cell(1,n);\nfor i=1:n\nind{i} = 0:(nodecount(i)-2);\nend\nind = lattice(ind{:});\nk = cumprod([1,nodecount(1:(end-1))]);\nind = 1+ind*k';\nnind = length(ind);\n\noffset=vhc*k';\nelem=zeros(nt*nind,n+1);\nL=(1:nind)';\nfor i=1:nt\n elem(L,:)=repmat(ind,1,n+1)+repmat(offset(thc(i,:))',nind,1);\n L=L+nind;\nend\n\nif(n==2 || n==3)\n elem=meshreorient(node,elem);\nend\n\n% ======== subfunction ========\nfunction g = lattice(varargin)\n% generate a factorial lattice in n variables\nn=nargin;\nsizes = cellfun('length',varargin);\nc=cell(1,n);\n[c{1:n}]=ndgrid(varargin{:});\ng=zeros(prod(sizes),n);\nfor i=1:n\ng(:,i)=c{i}(:);\nend\n", "meta": {"author": "fangq", "repo": "iso2mesh", "sha": "556f4c321467a3ee042d4c559b4edc11e01dc574", "save_path": "github-repos/MATLAB/fangq-iso2mesh", "path": "github-repos/MATLAB/fangq-iso2mesh/iso2mesh-556f4c321467a3ee042d4c559b4edc11e01dc574/meshgrid6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.6905857698060028}} {"text": "function g = p01_g ( n, x )\n\n%*****************************************************************************80\n%\n%% P01_G evaluates the gradient for problem 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 October 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the values of the variables.\n%\n% Output, real G(N), the gradient of the objective function.\n%\n g = zeros ( n, 1 );\n\n th = p01_th ( x );\n\n r = sqrt ( x(1) * x(1) + x(2) * x(2) );\n t = x(3) - 10.0 * th;\n s1 = 5.0 * t / ( pi * r * r );\n\n g(1) = 200.0 * ( x(1) - x(1) / r + x(2) * s1 );\n g(2) = 200.0 * ( x(2) - x(2) / r - x(1) * s1 );\n g(3) = 2.0 * ( 100.0 * t + x(3) );\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_opt/p01_g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.6905857685412361}} {"text": "function e = boundedges ( p, t )\n\n%*****************************************************************************80\n%\n%% BOUNDEDGES finds the boundary edges in a triangular mesh.\n%\n% Discussion:\n%\n% You may need this routine if you need to enforce boundary\n% conditions in a PDE.\n%\n% The 3D version of this code is called SURFTRI.\n%\n% Licensing:\n%\n% (C) 2004 Per-Olof Persson. \n% See COPYRIGHT.TXT for details.\n%\n% Reference:\n%\n% Per-Olof Persson and Gilbert Strang,\n% A Simple Mesh Generator in MATLAB,\n% SIAM Review,\n% Volume 46, Number 2, June 2004, pages 329-345.\n%\n% Parameters:\n%\n% Input, real P(NP,2), the coordinates of a set of nodes.\n%\n% Input, integer T(NT,1:3), a list of the nodes which make up each triangle\n% of a triangulation of the nodes in P.\n%\n% Output, integer E(*,*), ?\n%\n\n%\n% Form all edges, non-duplicates are boundary edges\n%\n edges = [t(:,[1,2]);\n t(:,[1,3]);\n t(:,[2,3])];\n\n node3 = [t(:,3);t(:,2);t(:,1)];\n edges = sort(edges,2);\n [foo,ix,jx] = unique(edges,'rows');\n vec = histc(jx,1:max(jx));\n qx = find(vec==1);\n e = edges(ix(qx),:);\n node3 = node3(ix(qx));\n%\n% Orientation\n%\n v1 = p(e(:,2),:)-p(e(:,1),:);\n v2 = p(node3,:)-p(e(:,1),:);\n ix = find(v1(:,1).*v2(:,2)-v1(:,2).*v2(:,1)>0);\n e(ix,[1,2]) = e(ix,[2,1]);\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/distmesh/boundedges.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.6905857605925618}} {"text": "function c = wavecdf97(x, nlevel)\n%WAVECDF97: Multi-level discrete 2-D wavelet transform \n%with the Cohen-Daubechies-Feauveau (CDF) 9/7 wavelet. \n%\n% c = wavecdf97(x, nlevel) does the follows according to the value of \n% nlevel:\n% nlevel > 0: decomposes 2-dimension matrix x up to nlevel level;\n% nlevel < 0: does the inverse transform to nlevel level;\n% nlevel = 0: sets c equal to x;\n% omitted: does the same as nlevel=5. \n%\n% The boundary handling method is symmetric extension. \n%\n% x may be of any size; it need not have size divisible by 2^L.\n% For example, if x has length 9, one stage of decomposition\n% produces a lowpass subband of length 5 and a highpass subband\n% of length 4. Transforms of any length have perfect\n% reconstruction (exact inversion).\n% NOTE: the 5 lines above are quoted directly form [3].\n% \n% If nlevel is so large that the approximation coefficients become \n% a 1-D array, any further decomposition will be performed as for 1-D \n% decomposition until the approximation coefficients be a scale number. \n%\n% Lifting algorithm is not used here; we use subband filters directly.\n% Lifting algorithm and spline 5/3 wavelets and other jpeg2000 related \n% codes will be available soon. \n%\n% Example:\n% Y = wavecdf97(X, 5); % Decompose image X up to 5 level\n% R = wavecdf97(Y, -5); % Reconstruct from Y\n%\n% You can test wavecdf97.m with the following lines: \n% % get a 2-D uint8 image \n% x=imread('E:\\study\\jpeg2000\\images\\lena.tif');\n% % decompose\n% y=wavecdf97(x,2);\n% % show decomposed result \n% figure;imshow(mat2gray(y));\n% % reconstruct without change of anything\n% ix=wavecdf97(y,-2);\n% % show and compare the original and reconstructed images\n% figure;subplot(1,2,1);imshow(x);subplot(1,2,2);imshow(uint8(ix));\n% % look at the MSE difference \n% sum(sum((double(x)-ix).^2))/numel(x)\n%\n% Reference:\n% [1] D.S.Taubman et al., JPEC2000 Image Compression: F. S. & P.,\n% Chinese Edition, formula 10.6-10.9 in section 10.3.1 \n% and formula 10.13 in section 10.4.1.\n% [2] R.C.Gonzalez et al., Digital Image Processing Using MATLAB, \n% Chinese Edition, function wavefast in section 7.2.2.\n% [3] Pascal Getreuer, waveletcdf97.m from Matlab file Exchange website\n% [4] Matlab files: biorwavf.m, wavdec2.m, wawrec2.m, etc.\n% \n% Contact information: \n% Email/MSN messenger: wangthth@hotmail.com\n%\n% Tianhui Wang at Beijing, China, July, 2006\n% Last Revision: Aug 5, 2006\n\n%---------------------- input arguments checking ----------------------%\nerror(nargchk(1,2,nargin));\nif nargin == 1\n nlevel = 5; % default level\nend\n% check x\nif ~isreal(x) || ~isnumeric(x) || (ndims(x) > 2)\n error('WAVELIFT:InArgErr', ['The first argument must' ...\n ' be a real, numeric 2-D or 1-D matrix.']);\nend\nif isinteger(x)\n x = double(x);\nend\n% check nlevel\nif ~isreal(nlevel) || ~isnumeric(nlevel) || round(nlevel)~=nlevel\n error('WAVELIFT:InArgErr', ['The 2nd argument shall be ' ...\n 'a real and numeric integer.']);\nend\n%---------------- forming low-pass and high-pass filters ---------------%\n% CDF 9/7 filters: decomposition low-pass lp and high-pass hp\n% reconstruction low-pass lpr and high-pass hpr\n% The filter coefficients have several forms.\n% What D.S.Taubman et al. suggest in [1] are used here:\nlp = [.026748757411 -.016864118443 -.078223266529 .266864118443];\nlp = [lp .602949018236 fliplr(lp)];\nhp = [.045635881557 -.028771763114 -.295635881557];\nhp = [hp .557543526229 fliplr(hp)];\nlpr = hp .* [-1 1 -1 1 -1 1 -1] * 2;\nhpr = lp .* [1 -1 1 -1 1 -1 1 -1 1] * 2;\n% Matlab 'bior4.4' use the varied version (see Matlab's biorwavf.m):\n% lp=lp*sqrt(2);hp=hp*(-sqrt(2));lpr=lpr*(1/sqrt(2));hpr=hpr*(-1/sqrt(2));\n% P.Getreuer's waveletcdf97.m [3] alters the Taubman's version as follows:\n% lp=lp*sqrt(2);hp=hp*sqrt(2);lpr=lpr*(1/sqrt(2));hpr=hpr*(1/sqrt(2));\n% while R.C.Gonzalez et al in [2] alter the Taubman's version as follows:\n% lp=lp;hp=hp*(-2);lpr=lpr;hpr=hpr*(-1/2);\n%---------------- remain unchanged when nlevel = 0 -------------------%\nif nlevel == 0\n c = x;\n%-------------------- decomposition, if nlevel < 0 ------------------%\nelseif nlevel > 0\n c = zeros(size(x));\n x = double(x);\n for i = 1:nlevel\n % [ll, hl; lh, hh]: 1-level FWT for x \n temp = symconv2(x, hp, 'col'); % high filtering\n temp = temp(2:2:end, :); % down sampling\n hh = symconv2(temp, hp, 'row'); % high filtering \n hh = hh(:, 2:2:end); % down sampling\n lh = symconv2(temp, lp, 'row'); % low filtering\n lh = lh(:, 1:2:end); % down sampling\n \n temp = symconv2(x, lp, 'col'); % low filtering\n temp = temp(1:2:end, :); % down sampling\n hl = symconv2(temp, hp, 'row'); % high filtering\n hl = hl(:, 2:2:end); % down sampling\n ll = symconv2(temp, lp, 'row'); % low filtering\n ll = ll(:, 1:2:end); % down sampling\n % update coefficient matrix\n c(1:size(x,1), 1:size(x,2)) = [ll, hl; lh, hh];\n % replace x with ll for next level FWT\n x = ll;\n % give a warning if nlevel is too large\n if size(x,1)<=1 && size(x,2)<=1 && i~=nlevel\n warning('WAVECDF97:DegradeInput', ['Only decompose to ' ...\n num2str(i) '-level instead of ' num2str(nlevel) ...\n ', \\nas the approximation coefficients at ' num2str(i) ...\n '-level has row or/and column of length 1.']);\n break\n end\n end\n%-------------------- reconstruction, if nlevel < 0 -----------------%\nelse\n sx = size(x);\n % find reconstruction level\n nl = -nlevel;\n while sx(1)/2^nl<=1/2 && sx(2)/2^nl<=1/2, nl = nl-1; end\n if nl ~= -nlevel \n warning('WAVECDF97:DegradeInput', ['Only reconstruct to ' ...\n num2str(nl) '-level instead of ' num2str(-nlevel) ...\n ', \\nas the approximation coefficients at ' num2str(nl) ...\n '-level has row or/and column of length 1.']);\n end\n % nl-level reconstruction\n for i = 1:nl\n % find the target ll hl lh hh blocks\n sLL = ceil(sx/2^(nl-i+1));\n sConstructed = ceil(sx/2^(nl-i));\n sHH = sConstructed - sLL;\n lrow = sConstructed(1); lcol = sConstructed(2);\n\n ll = x(1:sLL(1), 1:sLL(2));\n hl = x(1:sLL(1), sLL(2)+1:sLL(2)+sHH(2));\n lh = x(sLL(1)+1:sLL(1)+sHH(1), 1:sLL(2)); \n hh = x(sLL(1)+1:sLL(1)+sHH(1), sLL(2)+1:sLL(2)+sHH(2));\n\n % upsample rows and low filter\n temp = zeros(sLL(1), lcol); temp(:, 1:2:end) = ll;\n ll = symconv2(temp, lpr, 'row'); \n % upsample rows and high filter \n temp = zeros(sLL(1), lcol); temp(:, 2:2:end) = hl;\n hl = symconv2(temp, hpr, 'row');\n % upsample columns and low filter \n temp = zeros(lrow, lcol); temp(1:2:end, :) = ll + hl;\n l = symconv2(temp, lpr, 'col'); \n\n % upsample rows and high filter \n temp = zeros(sHH(1), lcol); temp(:, 1:2:end) = lh;\n lh = symconv2(temp, lpr, 'row');\n % upsample rows and high filter \n temp = zeros(sHH(1), lcol); temp(:, 2:2:end) = hh;\n hh = symconv2(temp, hpr, 'row');\n % upsample rows and high filter \n temp = zeros(lrow, lcol); temp(2:2:end, :) = lh + hh;\n h = symconv2(temp, hpr, 'col');\n\n % update x with the new ll, ie. l+h\n x(1:lrow, 1:lcol) = l + h;\n end \n % output\n c = x;\nend\n%------------------------- internal function --------------------------%\n% 2-dimension convolution with edges symmetrically extended %\n%-----------------------------------------------------------------------%\nfunction y = symconv2(x, h, direction)\n% symmetrically extended convolution(see section 6.5.2 in [1]):\n% x[n], E<=n<=F-1, is extended to x~[n] = x[n], 0<=n<=N-1;\n% x~[E-i] = x~[E+i], for all integer i\n% x~[F-1-i] = x~[F-1+i], for all integer i\n% For odd-length h[n], to convolve x[n] and h[n], we just need extend x \n% by (length(h)-1)/2 for both left and right edges. \n% The symmetric extension handled here is not the same as in Matlab \n% wavelets toolbox nor in [2]. The last two use the following method:\n% x[n], E<=n<=F-1, is extended to x~[n] = x[n], 0<=n<=N-1;\n% x~[E-i] = x~[E+i-1], for all integer i\n% x~[F-1-i] = x~[F+i], for all integer i \n\nl = length(h); s = size(x);\nlext = (l-1)/2; % length of h is odd \nh = h(:)'; % make sure h is row vector \ny = x;\nif strcmp(direction, 'row') % convolving along rows\n if ~isempty(x) && s(2) > 1 % unit length array skip convolution stage\n for i = 1: lext\n x = [x(:, 2*i), x, x(:, s(2)-1)]; % symmetric extension\n end\n x = conv2(x, h);\n y = x(:, l:s(2)+l-1); \n end\nelseif strcmp(direction, 'col') % convolving along columns\n if ~isempty(x) && s(1) > 1 % unit length array skip convolution stage\n for i = 1: lext \n x = [x(2*i, :); x; x(s(1)-1, :)]; % symmetric extension\n end\n x = conv2(x, h');\n y = x(l:s(1)+l-1, :);\n end\nend \n% EOF", "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/11846-cdf-97-wavelet-transform/wavecdf97.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.6904897749848128}} {"text": "function R = SigmoidResponse(img, sr_n, sr_sigma, sr_B)\n%\n% R = SigmoidResponse(img, sr_n, sr_sigma, sr_B)\n%\n% This function computes sigmoid response\n%\n% input:\n% -img: an image\n% -sr_n: power \n% -sr_sigma: saturation parameter\n% -sr_B:\n%\n% output:\n% -R: is the response\n%\n% Copyright (C) 2011-14 Francesco Banterle\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%\n\nif(~exist('sr_n','var'))\n sr_n = 0.73;\nend\n\nif(~exist('sr_sigma','var'))\n sr_sigma = 1.0;\nend\n\nif(~exist('sr_B','var'))\n sr_B = 1.0;\nend\n\nimg_n = img.^sr_n;\nR = img_n ./ (img_n + sr_sigma.^sr_n);\nR = R * sr_B;\n\nend", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/Tmo/util/SigmoidResponse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6904868586229982}} {"text": "function sigma = snr2sigma(X,SNR)\n%SNR2SIGMA Summary of this function goes here\n% Detailed explanation goes here\n[N,B] = size(X);\np = mean(sum(X.^2,2));\nsigma2 = p/(B*10^(SNR/10));\nsigma = sqrt(sigma2);\n\nend\n\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/common/snr2sigma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6904868572943714}} {"text": "function I = mi_gd2(x, y, Ym, biascorrect, demeaned, class_means)\n% MI_GD Mutual information (MI) between a Gaussian and a discrete\n% variable in bits\n% I = mi_gd(x,y,Ym) returns the MI between the (possibly multidimensional)\n% Gaussian variable x and the discrete variable y.\n% Rows of x correspond to samples, columns to dimensions/variables. \n% (Samples first axis)\n% y should contain integer values in the range [0 Ym-1] (inclusive).\n%\n% biascorrect : true / false option (default true) which specifies whether\n% bias correction should be applied to the esimtated MI.\n% demeaned : false / true option (default false) which specifies whether the\n% input data already has zero mean (true if it has been copula-normalized)\n\npersistent previous_nvar previous_y bias_unc bias_cond;\n\n\n% ensure samples first axis for vectors\nif isvector(x)\n x = x(:);\nend\nif ndims(x)~=2\n error('mi_gd: input arrays should be 2d')\nend\nif isvector(y)\n y = y(:);\nelse\n% error('mi_gd: only univariate discrete variable supported');\nend\n\nNtrl = size(x,1);\nNvar = size(x,2);\n\nif isequal(previous_y, y)\n computebias = false;\nelse\n computebias = true;\nend\n\nif ~isequal(previous_nvar, Nvar)\n computebias = true;\nend\n\nif size(y,1) ~= Ntrl\n error('mi_gd: number of trials do not match');\nend\n\n% default option values\nif nargin<4\n biascorrect = true;\nend\nif nargin<5\n demeaned = false;\nend\n\nif ~demeaned\n x = bsxfun(@minus,x,sum(x,1)/Ntrl);\nend\n\n% class-conditional entropies \nNtrl_y = sum(y);\nHcond = zeros(1,Ym);\nfor yi=1:Ym\n xm = x(y(:,yi),:);\n %Ntrl_y(yi) = size(xm,1);\n %xm = bsxfun(@minus,xm,sum(xm,1)/Ntrl_y(yi));\n Cm = (xm'*xm) / (Ntrl_y(yi) - 1);\n chCm = chol(Cm);\n Hcond(yi) = sum(log(diag(chCm)));% + c*Nvar;\nend\n% class weights\nw = Ntrl_y ./ Ntrl;\n\n% input data is class-demeaned, this needs to be accounted for in the\n% unconditional entropies\nc = diag(sqrt(Ntrl_y))*class_means;%*diag(Ntrl_y);\n\n% unconditional entropy from unconditional Gaussian fit\nCx = (x'*x + c'*c) / (Ntrl-1);\nchC = chol(Cx);\nHunc = sum(log(diag(chC)));% + c*Nvar; % the commented out bit drops out in the subtraction below\n\n\n% apply bias corrections\nln2 = log(2);\nif biascorrect\n \n \n if computebias,\n vars = 1:Nvar;\n \n psiterms_unc = psi((Ntrl - vars)/2) / 2;\n dterm_unc = (ln2 - log(Ntrl-1)) / 2;\n bias_unc = Nvar*dterm_unc + sum(psiterms_unc);\n \n dterm_cond = (ln2 - log(Ntrl_y-1)) / 2;\n psiterms_cond = zeros(1,Ym);\n for vi=vars\n idx = (Ntrl_y-vi);\n psiterms_cond = psiterms_cond + psi(idx/2);\n end\n bias_cond = Nvar*dterm_cond + (psiterms_cond/2);\n end\n \n Hunc = Hunc - bias_unc;\n Hcond = Hcond - bias_cond;\nend\n\nI = Hunc - w*Hcond(:);% sum(w .* Hcond);\n% convert to bits\nI = I / ln2;\n\nprevious_y = y;\nprevious_nvar = Nvar;\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/gcmi/mi_gd2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476385, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6904868559657443}} {"text": "function [nScales, scale_step, scaleFactors, scale_filter, params] = init_scale_filter(params)\n\n% Initialize the scale filter parameters. Uses the fDSST scale filter.\n\ninit_target_sz = params.init_sz(:)';\n\nnScales = params.number_of_scales_filter;\nscale_step = params.scale_step_filter;\n\nscale_sigma = params.number_of_interp_scales * params.scale_sigma_factor;\n\nscale_exp = (-floor((nScales-1)/2):ceil((nScales-1)/2)) * params.number_of_interp_scales/nScales;\nscale_exp_shift = circshift(scale_exp, [0 -floor((nScales-1)/2)]);\n\ninterp_scale_exp = -floor((params.number_of_interp_scales-1)/2):ceil((params.number_of_interp_scales-1)/2);\ninterp_scale_exp_shift = circshift(interp_scale_exp, [0 -floor((params.number_of_interp_scales-1)/2)]);\n\nscale_filter.scaleSizeFactors = scale_step .^ scale_exp;\nscale_filter.interpScaleFactors = scale_step .^ interp_scale_exp_shift;\n\nys = exp(-0.5 * (scale_exp_shift.^2) /scale_sigma^2);\nscale_filter.yf = single(fft(ys));\nscale_filter.window = single(hann(size(ys,2)))';\n\n%make sure the scale model is not to large, to save computation time\nif params.scale_model_factor^2 * prod(init_target_sz) > params.scale_model_max_area\n params.scale_model_factor = sqrt(params.scale_model_max_area/prod(init_target_sz));\nend\n\n%set the scale model size\nparams.scale_model_sz = max(floor(init_target_sz * params.scale_model_factor), [8 8]);\n\nscale_filter.max_scale_dim = strcmp(params.s_num_compressed_dim,'MAX');\nif scale_filter.max_scale_dim\n params.s_num_compressed_dim = length(scale_filter.scaleSizeFactors);\nend\n\n% Scale factor for the translation filter\nscaleFactors = 1;\n", "meta": {"author": "martin-danelljan", "repo": "ECO", "sha": "27e8ae565cd63ec14bafcaad8b5b993bec8f3e69", "save_path": "github-repos/MATLAB/martin-danelljan-ECO", "path": "github-repos/MATLAB/martin-danelljan-ECO/ECO-27e8ae565cd63ec14bafcaad8b5b993bec8f3e69/implementation/scale_filter/init_scale_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6904868499833557}} {"text": "function z = trace_inv( Y )\n\n% TRACE_INV Trace of the inverse of a PSD matrix.\n% For square matrix X, TRACE_INV(X) is TRACE(INV(X)) if X is Hermitian\n% or symmetric and positive definite; and +Inf otherwise. \n%\n% An error results if X is not a square matrix.\n%\n% Disciplined convex programming information:\n% TRACE_INV is convex and nonmonotonic (at least with respect to\n% elementwise comparison), so its argument must be affine.\n\nerror( nargchk( 1, 1, nargin ) );\nif ndims( Y ) > 2 || size( Y, 1 ) ~= size( Y, 2 ),\n error( 'Input must be a square matrix.' );\nend\nerr = Y - Y';\nY = 0.5 * ( Y + Y' );\nif norm( err, 'fro' ) > 8 * eps * norm( Y, 'fro' ),\n z = Inf;\nelse\n z = eig( full( Y ) );\n if any( z <= 0 ),\n z = Inf;\n else\n z = sum(1.0./z);\n end\nend\n\n% Copyright 2010 Michael C. Grant and Stephen P. Boyd.\n% See the file COPYING.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/functions/trace_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.6904758884997879}} {"text": "function [xo,N]=gabglasso(ttype,xi,lambda,group);\n%GABGLASSO group lasso estimate (hard/soft) in time-frequency domain\n% Usage: xo=gabglasso(ttype,x,lambda,group);\n% [xo,N]=gabglasso(ttype,x,lambda,group));\n%\n% GABGLASSO('hard',x,lambda,'time') will perform\n% time hard group thresholding on x, i.e. all time-frequency\n% columns whose norm less than lambda will be set to zero.\n%\n% GABGLASSO('soft',x,lambda,'time') will perform\n% time soft thresholding on x, i.e. all time-frequency\n% columns whose norm less than lambda will be set to zero,\n% and those whose norm exceeds lambda will be multiplied\n% by (1-lambda/norm).\n%\n% GABGLASSO(ttype,x,lambda,'frequency') will perform\n% frequency thresholding on x, i.e. all time-frequency\n% rows whose norm less than lambda will be soft or hard thresholded\n% (see above).\n%\n% [xo,N]=GABGLASSO(ttype,x,lambda,group) additionally returns\n% a number N specifying how many numbers where kept.\n%\n% The function may meaningfully be applied to output from DGT, WMDCT or\n% from WIL2RECT(DWILT(...)).\n%\n% See also: gablasso, gabelasso\n%\n% Demos: demo_audioshrink\n\n% AUTHOR : Bruno Torresani. \n% REFERENCE: OK\n\ncomplainif_argnonotinrange(nargin,4,4,mfilename);\n \nNbFreqBands = size(xi,1);\nNbTimeSteps = size(xi,2);\n\nxo = zeros(size(xi));\n\nswitch(lower(group))\n case {'time'}\n for t=1:NbTimeSteps,\n threshold = norm(xi(:,t));\n mask = (1-lambda/threshold);\n if(strcmp(ttype,'soft'))\n mask = mask * (mask>0);\n elseif(strcmp(ttype,'hard'))\n mask = (mask>0);\n end\n xo(:,t) = xi(:,t) * mask;\n end\n case {'frequency'}\n for f=1:NbFreqBands,\n threshold = norm(xi(f,:));\n mask = (1-lambda/threshold);\n mask = mask * (mask>0);\n if(strcmp(ttype,'soft'))\n mask = mask * (mask>0);\n elseif(strcmp(ttype,'hard'))\n mask = (mask>0);\n end\n xo(f,:) = xi(f,:) * mask;\n end\n otherwise\n error('\"group\" parameter must be either \"time\" or \"frequency\".'); \nend\n\nif nargout==2\n signif_map = (abs(xo)>0);\n N = sum(signif_map(:));\nend\n \n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/reference/ref_gabglasso_onb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.6904758789167238}} {"text": "%COVM Compute covariance matrix for large datasets\n% \n% \tC = COVM(A)\n% \n% Similar to C = COV(A) this routine computes the covariance matrix \n% for the datavectors stored in the rows of A. No large intermediate \n% matrices are created. If class(A) is 'prdataset' then class(C) is \n% 'double'.\n\n% Copyright: R.P.W. Duin, duin@ph.tn.tudelft.nl\n% Faculty of Applied Physics, Delft University of Technology\n% P.O. Box 5046, 2600 GA Delft, The Netherlands\n\n% $Id: covm.m,v 1.3 2010/02/08 15:34:14 duin Exp $\n\nfunction c = covm(a,n)\n\t\t[m,k] = size(a);\nif nargin < 2, n = 0; end\nif n ~= 1 & n ~= 0\n\terror('Second parameter should be either 0 or 1')\nend\n[loops,n0,n1] = prmem(m,k);\nif loops == 1\n\tc = prcov(+a,n);\n\tc = (c+c')/2;\n\treturn\nend\nc = zeros(k,k);\nu = ones(n0,1)*mean(a);\nfor j = 1:loops\n\tif j == loops, n = n1; else n = n0; end\n\tnn = (j-1)*n0;\n\tb = +a(nn+1:nn+n,:) - u(1:n,:);\n\tc = c + b'*b;\nend\nc = (c + c')/2;\nif n\n\tc = c/m;\nelse\n\tc = c/(m-1);\nend\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/private/covm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.870597268408361, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6904758704018815}} {"text": "function g = mult_givens ( c, s, k, g )\n\n%*****************************************************************************80\n%\n%% MULT_GIVENS applies a Givens rotation to two successive entries of a vector.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n% \n% Modified:\n%\n% 25 March 2008\n%\n% Author:\n%\n% C original version by Lili Ju\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Richard Barrett, Michael Berry, Tony Chan, James Demmel,\n% June Donato, Jack Dongarra, Victor Eijkhout, Roidan Pozo,\n% Charles Romine, Henk van der Vorst,\n% Templates for the Solution of Linear Systems:\n% Building Blocks for Iterative Methods,\n% SIAM, 1994.\n% ISBN: 0898714710,\n% LC: QA297.8.T45.\n%\n% Tim Kelley,\n% Iterative Methods for Linear and Nonlinear Equations,\n% SIAM, 2004,\n% ISBN: 0898713528,\n% LC: QA297.8.K45.\n%\n% Yousef Saad,\n% Iterative Methods for Sparse Linear Systems,\n% Second Edition,\n% SIAM, 2003,\n% ISBN: 0898715342,\n% LC: QA188.S17.\n%\n% Parameters:\n%\n% Input, real C, S, the cosine and sine of a Givens\n% rotation.\n%\n% Input, integer K, indicates the location of the first vector entry.\n%\n% Input/output, real G(1:K+1), the vector to be modified. On output,\n% the Givens rotation has been applied to entries G(K) and G(K+1).\n%\n g1 = c * g(k) - s * g(k+1);\n g2 = s * g(k) + c * g(k+1);\n\n g(k) = g1;\n g(k+1) = g2;\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/mgmres/mult_givens.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.8031737940012417, "lm_q1q2_score": 0.6904594018378669}} {"text": "function M = euclideanfactory(m, n)\n% Returns a manifold struct to optimize over real matrices.\n%\n% function M = euclideanfactory(m)\n% function M = euclideanfactory(m, n)\n% function M = euclideanfactory([n1, n2, ...])\n%\n% Returns M, a structure describing the Euclidean space of real matrices,\n% equipped with the standard Frobenius distance and associated trace inner\n% product, as a manifold for Manopt.\n%\n% m and n in general can be vectors to handle multidimensional arrays.\n% If either of m or n is a vector, they are concatenated as [m, n].\n%\n% Using this simple linear manifold, Manopt can be used to solve standard\n% unconstrained optimization problems, for example in replacement of\n% Matlab's fminunc.\n%\n% See also: euclideancomplexfactory\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Dec. 30, 2012.\n% Contributors: Bamdev Mishra, May 4, 2015.\n% Change log: \n%\n% July 5, 2013 (NB):\n% Added egred2rgrad, ehess2rhess, mat, vec, tangent.\n% May 4, 2015 (BM):\n% Added functionality to handle multidimensional arrays.\n\n\n % The size can be defined using both m and n, or simply with m.\n % If m is a scalar, then n is implicitly 1.\n % This mimics the use of built-in Matlab functions such as zeros(...).\n if ~exist('n', 'var') || isempty(n)\n if numel(m) == 1\n n = 1;\n else\n n = [];\n end\n end\n \n dimensions_vec = [m(:)', n(:)']; % We have a row vector.\n \n M.size = @() dimensions_vec;\n \n M.name = @() sprintf('Euclidean space R^(%s)', num2str(dimensions_vec));\n \n M.dim = @() prod(dimensions_vec);\n \n M.inner = @(x, d1, d2) d1(:).'*d2(:);\n \n M.norm = @(x, d) norm(d(:), 'fro');\n \n M.dist = @(x, y) norm(x(:) - y(:), 'fro');\n \n M.typicaldist = @() sqrt(prod(dimensions_vec));\n \n M.proj = @(x, d) d;\n \n M.egrad2rgrad = @(x, g) g;\n \n M.ehess2rhess = @(x, eg, eh, d) eh;\n \n M.tangent = M.proj;\n \n M.exp = @exp;\n function y = exp(x, d, t)\n if nargin == 3\n y = x + t*d;\n else\n y = x + d;\n end\n end\n \n M.retr = M.exp;\n \n M.log = @(x, y) y-x;\n\n M.hash = @(x) ['z' hashmd5(x(:))];\n \n M.rand = @() randn(dimensions_vec);\n \n M.randvec = @randvec;\n function u = randvec(x) %#ok\n u = randn(dimensions_vec);\n u = u / norm(u(:), 'fro');\n end\n \n M.lincomb = @matrixlincomb;\n \n M.zerovec = @(x) zeros(dimensions_vec);\n \n M.transp = @(x1, x2, d) d;\n M.isotransp = M.transp; % the transport is isometric\n \n M.pairmean = @(x1, x2) .5*(x1+x2);\n \n M.vec = @(x, u_mat) u_mat(:);\n M.mat = @(x, u_vec) reshape(u_vec, dimensions_vec);\n M.vecmatareisometries = @() true;\n M.lie_identity = @() zeros(dimensions_vec);\n\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/euclidean/euclideanfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.6904593865365009}} {"text": "function r8gb_print ( m, n, ml, mu, a, title )\n\n%*****************************************************************************80\n%\n%% R8GB_PRINT prints a banded matrix.\n%\n% Discussion:\n%\n% An M by N banded matrix A with lower bandwidth ML and upper bandwidth MU\n% is assumed to be entirely zero, except for the main diagonal, and\n% entries in the ML nearest subdiagonals, and MU nearest superdiagonals.\n%\n% LINPACK and LAPACK \"R8GB\" storage for such a matrix generally includes\n% room for ML extra superdiagonals, which may be required to store\n% nonzero entries generated during Gaussian elimination.\n%\n% The original M by N matrix is \"collapsed\" downward, so that diagonals\n% become rows of the storage array, while columns are preserved. The\n% collapsed array is logically 2*ML+MU+1 by N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 April 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of rows of the matrix.\n% M must be positive.\n%\n% Input, integer N, the number of columns of the matrix.\n% N must be positive.\n%\n% Input, integer ML, MU, the lower and upper bandwidths.\n% ML and MU must be nonnegative, and no greater than min(M,N)-1..\n%\n% Input, real A(2*ML+MU+1,N), the M by N band matrix, stored in LINPACK\n% or LAPACK general band storage mode.\n%\n% Input, string TITLE, a title to be printed.\n%\n r8gb_print_some ( m, n, ml, mu, a, 1, 1, m, n, title );\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/r8gb_print.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.6904201389208567}} {"text": "function value = t_triple_product_integral ( i, j, k )\n\n%*****************************************************************************80\n%\n%% T_TRIPLE_PRODUCT_INTEGRAL: integral (-1<=x<=1) T(i,x)*T(j,x)*T(k,x)/sqrt(1-x^2) dx\n%\n% Discussion:\n%\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 April 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% John Mason, David Handscomb,\n% Chebyshev Polynomials,\n% CRC Press, 2002,\n% ISBN: 0-8493-035509,\n% LC: QA404.5.M37.\n%\n% Parameters:\n%\n% Input, integer I, J, K, the polynomial indices.\n% 0 <= I, J.\n%\n% Output, real VALUE, the integral.\n%\n if ( i < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'T_TRIPLE_PRODUCT_INTEGRAL - Fatal error!\\n' );\n fprintf ( 1, ' 0 <= I is required.\\n' );\n error ( 'T_TRIPLE_PRODUCT_INTEGRAL - Fatal error!' );\n end\n\n if ( j < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'T_TRIPLE_PRODUCT_INTEGRAL - Fatal error!\\n' );\n fprintf ( 1, ' 0 <= J is required.\\n' );\n error ( 'T_TRIPLE_PRODUCT_INTEGRAL - Fatal error!' );\n end\n\n if ( k < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'T_TRIPLE_PRODUCT_INTEGRAL - Fatal error!\\n' );\n fprintf ( 1, ' 0 <= K is required.\\n' );\n error ( 'T_TRIPLE_PRODUCT_INTEGRAL - Fatal error!' );\n end\n\n value = 0.5 * ( ...\n t_double_product_integral ( i + j, k ) + ...\n + t_double_product_integral ( abs ( i - j ), k ) );\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/chebyshev_polynomial/t_triple_product_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.6904201370915276}} {"text": "%NBAYESC Bayes Classifier for given normal densities\n% \n% W = NBAYESC(U,G)\n% \n% INPUT\n% U Dataset of means of classes \n% G Covariance matrices (optional; default: identity matrices)\n%\n% OUTPUT\n% \tW Bayes classifier\n%\n% DESCRIPTION\n% Computation of the Bayes normal classifier between a set of classes.\n% The means, labels and priors are defined by the dataset U of the size\n% [C x K]. The covariance matrices are stored in a matrix G of the \n% size [K x K x C], where K and C correspond to the dimensionality and \n% the number of classes, respectively. \n% \n% If C is 1, then G is treated as the common covariance matrix, yielding\n% a linear solution. For G = I, the nearest mean solution is obtained.\n% \n% This routine gives the exact solution for the given parameters, while\n% the trainable classifiers QDC and LDC give approximate solutions, based\n% on the parameter estimates from a training set. For a given dataset, U \n% and G can be computed by MEANCOV.\n%\n% EXAMPLES\n% [U,G] = MEANCOV(GENDATB(25));\n% W = NBAYESC(U,G);\n%\n% SEE ALSO (PRTools Guide)\n% MAPPINGS, DATASETS, QDC, LDC, NMC.\n\n% Copyright: R.P.W. Duin, duin@ph.tn.tudelft.nl\n% Faculty of Applied Sciences, Delft University of Technology\n% P.O. Box 5046, 2600 GA Delft, The Netherlands\n\n% $Id: nbayesc.m,v 1.4 2009/01/04 21:11:07 duin Exp $\n\nfunction W = nbayesc(U,G);\n\n\t\t[cu,ku] = size(U);\t\t% CU is the number of classes and KU - the dimensionality\n\tif nargin == 1,\n\t\tprwarning(4,'Covariance matrix is not specified, the identity matrix is assumed.'); \n\t\tG = eye(ku);\n\tend\n\n\t[k1,k2,c] = size(G);\t% C = 1, if G is the common covariance matrix.\n\n\tif (c ~= 1 & c ~= cu) | (k1 ~= k2) | (k1 ~= ku)\n\t\terror('Covariance matrix or a set of means has a wrong size.')\n\tend\n\n\tpars.mean = +U;\n\tpars.cov = G;\n\tpars.prior = getprior(U);\n\n\t%W = prmapping('normal_map','trained',pars,getlablist(U),ku,cu);\n\tW = normal_map(pars,getlablist(U),ku,cu);\n\tW = setname(W,'BayesNormal');\n\tW = setcost(W,U);\n\nreturn;", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/nbayesc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6904015003849682}} {"text": "function [y,p_avg,p_std]=multinomrnd(p,m,n)\n%Performs random sampling from a binomial distribution\n%\n% [y]=multinomrnd(p,m,n)\n% where p=1-by-k vector of probabilities of occurrence \n% n=sample size\n% and m= number of trials\n% y=samples-matrix of size k-by-m\n%\n% for picking out one of k mixture components, set n=1;\n%\nif nargin<3\n n=1;\nend\n\nk=length(p);\nx=rand(n,m);\n\nif (sum(p)-1>100*eps) \n p(k+1)=1-sum(p); \n k=k+1; \nend\np=cumsum(p);\n\n\ny(1,:)=sum(x<=p(1),1);\nfor i=2:k\n y(i,:)=sum(x>p(i-1) & x<=p(i),1);\nend\n\np_avg=mean(y'./n);\np_std=std(y'./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/multinomrnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6903997133638367}} {"text": "%% Housekeeping\nclc\nclear\nclose all\n\n%% Using the Grobner solver: constant-parameter case\nm0=rise('rbcs0');\nm1=solve(m0);\nprint_solution(m1)\n\n% Finding all solutions\n%-----------------------\nm2=solve(m0,'solver','dsge_groebner','solve_check_stability',false);\nprint_solution(m2)\nprint_solution(m1)\n\n%% Using the Grobner solver: regime switching example\nclc\n\nm00=rise('rbcs','solve_perturbation_type',{'frwz',{'mu'}});\n\n% Finding one solution\n%----------------------\nm01=solve(m00);\n\n% Finding all solutions\n%-----------------------\nm02=solve(m00,'solver','dsge_groebner','solve_check_stability',false);\nprint_solution(m01)\nprint_solution(m02)\n\n\n%% Using the dsge_udc solver: regime switching example\nclc\n\nm000=set(m00,'solve_perturbation_type','mw');\n\n% Finding one solution\n%----------------------\nm001=solve(m000);\n\n% Finding all solutions Groebner\n%-------------------------------\nm002=solve(m000,'solver','dsge_groebner','solve_check_stability',false);\n\n% Finding all solutions UDC\n%--------------------------\nrefine=false;checkStab=false;allSols=true;msvOnly=true;\nxplosRoots=false;debug=false;\nsolver={'dsge_udc',refine,checkStab,allSols,msvOnly,xplosRoots,debug};\nm003=solve(m000,'solver',solver,'solve_check_stability',false);\n\n% Finding all solutions UDC with refinement\n%------------------------------------------\nrefine=true;checkStab=false;allSols=true;msvOnly=true;\nxplosRoots=false;debug=false;\nsolver={'dsge_udc',refine,checkStab,allSols,msvOnly,xplosRoots,debug};\n\nm004=solve(m000,'solver',solver,'solve_check_stability',false);\n\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/examples/MarkovSwitching/FoersterRubioRamirezWaggonerZha/wp1301/driver_rbcs_multipe_solutions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6903997128224879}} {"text": "function d = fd03 ( p )\n\n%*****************************************************************************80\n%\n%% FD03 is a signed distance function for problem 3.\n%\n% Discussion:\n%\n% The formula used here is not quite correct. In particular, it is wrong\n% for points exterior to the cube whose nearest point on the cube is at a corner.\n%\n% For DISTMESH_3D's purposes, though, this computation is accurate enough.\n%\n% Modified:\n%\n% 12 September 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real P(N,3), one or more points.\n%\n% Output, real D(N), the signed distance of each point to the boundary of the region.\n%\n d = - min ( min ( min ( min ( min ( -0.0+p(:,3), 1.0-p(:,3) ), ...\n -0.0+p(:,2) ), ...\n 1.0-p(:,2) ), ...\n -0.0+p(:,1) ), ...\n 1.0-p(:,1) );\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/distmesh_3d/fd03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6903997069884964}} {"text": "classdef SymbolicVoigtRotationMatrixGenerator < handle\n \n properties (Access = public)\n VoigtRotationMatrix\n end\n \n \n properties (Access = private)\n RotationMatrix\n Stress\n RotatedStress\n end\n \n methods (Access = public)\n \n function obj = SymbolicVoigtRotationMatrixGenerator()\n obj.createRotationMatrix();\n obj.createStressTensor();\n obj.computeRotatedStressTensor();\n obj.obtainVoigtRotationMatrix()\n end\n \n end\n \n methods (Access = private)\n \n function obj = createRotationMatrix(obj)\n theta = obj.createRotationAngle();\n vect = obj.createNormalVector(); \n rotator = VectorRotator(theta,vect);\n obj.RotationMatrix = rotator.getRotationMatrix();\n end\n \n function u = createNormalVector(obj)\n u = sym('u',[3 1],'real');\n end\n \n function theta = createRotationAngle(obj)\n theta = sym('theta','real');\n end\n \n function createStressTensor(obj)\n obj.Stress = StressTensor();\n obj.Stress.tensor = sym('s',[3 3],'real');\n Tens = obj.Stress.tensor;\n Tens = obj.Stress.symmetrizeWithUpperDiagonal(Tens);\n obj.Stress.tensor = Tens; \n obj.Stress.transformTensor2Voigt();\n end\n \n function computeRotatedStressTensor(obj)\n R = obj.RotationMatrix;\n S = obj.Stress.tensor;\n RotS = R'*S*R;\n obj.RotatedStress = StressTensor();\n obj.RotatedStress.tensor = simplify(RotS);\n obj.RotatedStress.transformTensor2Voigt();\n end\n \n function obtainVoigtRotationMatrix(obj)\n RotStre = obj.RotatedStress.tensorVoigt;\n Stre = obj.Stress.tensorVoigt;\n DimVoigt = length(RotStre);\n RotMatrix = sym(zeros(DimVoigt,DimVoigt));\n for iStress = 1:DimVoigt\n RS = RotStre(iStress);\n for jStress = 1:DimVoigt\n S = Stre(jStress);\n [TensorValue,~] = coeffs(RS,S);\n TensorValue = obj.takeApropiateComponent(TensorValue);\n RotMatrix(iStress,jStress) = TensorValue;\n end\n end\n obj.VoigtRotationMatrix = simplify(RotMatrix);\n end\n \n function value = takeApropiateComponent(obj,value)\n if isempty(value)\n value = [];\n else\n Dim = length(value);\n if Dim == 1\n value = 0;\n else\n value = value(1);\n end\n end\n end\n \n end\n \nend\n\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Homogenization/Sources/Rotator/SymbolicVoigtRotationMatrixGenerator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6903997065075715}} {"text": "function v = integral2(F, S)\n%INTEGRAL2 Flux integral of a Chebfun3v object through a 2D-surface.\n% INTEGRAL2(F, S) computes the flux integral of the Chebfun3v object F \n% through the parametric surface S defined as a Chebfun2v object (with 3 \n% components):\n% /\n% INTEGRAL2(F, S) = | < F, dS >\n% /S\n% //\n% = || < F(S(x,y)), cross(S_x(x,y), S_y(x,y)) > dxdy.\n% //D\n% \n% See also CHEBFUN3V/INTEGRAL, CHEBFUN3/INTEGRAL, CHEBFUN3/INTEGRAL2,\n% CHEBFUN3/INTEGRAL3, CHEBFUN3/SUM, CHEBFUN3/SUM2 and CHEBFUN3/SUM3.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Check that F is a chebfun3v object with 3 components:\nif ( F.nComponents ~= 3 )\n error('CHEBFUN:CHEBFUN3V:integral2:dimChebfun3v', ...\n 'The chebfun3v object must have 3 components.')\nend\n\n% Check that S is a chebfun2v object with 3 components:\nif ( isa(S, 'chebfun2v') )\n if ( S.nComponents ~= 3 )\n error('CHEBFUN:CHEBFUN3V:integral2:dimChebfun2v', ...\n 'The parametrisation must have 3 components.')\n end\nelse\n error('CHEBFUN:CHEBFUN3V:integral2:notaChebfun2v', ...\n 'The parametrisation must be a chebfun2v object.')\nend\n\n% Get components of F:\nF1 = F.components{1};\nF2 = F.components{2};\nF3 = F.components{3};\n\n% Get components of the surface S:\nS1 = S(1);\nS2 = S(2);\nS3 = S(3);\n\n% Build the composition F(S):\nFS1_handle = @(x,y) feval(F1, feval(S1, x, y), feval(S2, x, y), ...\n feval(S3, x, y));\n\nFS2_handle = @(x,y) feval(F2, feval(S1, x, y), feval(S2, x, y), ...\n feval(S3, x, y));\n\nFS3_handle = @(x,y) feval(F3, feval(S1, x, y), feval(S2, x, y), ...\n feval(S3, x, y));\n\nFS = chebfun2v(FS1_handle, FS2_handle, FS3_handle, S1.domain);\n\n% Normal vector to the surface:\ndS = normal(S);\n\n% By definition:\nv = sum2(dot(FS, dS));\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun3v/integral2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6903996970049857}} {"text": "function y = logWishart(Sigma, W, v)\n% Compute log pdf of a Wishart distribution.\n% Input:\n% Sigma: d x d covariance matrix\n% W: d x d covariance parameter\n% v: degree of freedom\n% Output:\n% y: probability density in logrithm scale y=log p(Sigma)\n% Written by Mo Chen (sth4nth@gmail.com).\nd = length(Sigma);\nB = -0.5*v*logdet(W)-0.5*v*d*log(2)-logmvgamma(0.5*v,d);\ny = B+0.5*(v-d-1)*logdet(Sigma)-0.5*trace(W\\Sigma);", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter02/logWishart.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242018339898, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.690383887587061}} {"text": "function dUpsilonS = lfmvvGradientSigmaUpsilonMatrix(gamma, sigma2, ...\n t1, t2, mode)\n\n% LFMVVGRADIENTSIGMAUPSILONMATRIX Gradient of upsilon matrix vv wrt sigma\n% FORMAT\n% DESC computes the gradient wrt sigma of a portion of the LFMVV kernel.\n% ARG gamma : Gamma value for system.\n% ARG sigma2 : length scale of latent process.\n% ARG t1 : first time input (number of time points x 1).\n% ARG t2 : second time input (number of time points x 1).\n% ARG mode : operation mode, according to the derivative (mode 0,\n% derivative wrt t1, mode 1 derivative wrt t2)\n% RETURN upsilon : result of this subcomponent of the kernel for the given values.\n%\n% COPYRIGHT : Mauricio Alvarez, 2010\n%\n% SEEALSO : lfmvvComputeUpsilonMatrix.m\n\n% KERN\n\ngridt1 = repmat(t1, 1, length(t2));\ngridt2 = repmat(t2', length(t1), 1);\ntimeGrid = gridt1 - gridt2;\n\ndUpsilon = lfmvpGradientSigmaUpsilonMatrix(gamma, sigma2, t1, t2, mode);\n\nif mode == 0\n dUpsilonS = gamma*dUpsilon - 4*timeGrid/(sqrt(pi)*sigma2^2).* ...\n exp(-(timeGrid.^2)./sigma2).*(3 - 2*(timeGrid.^2)/sigma2) ...\n + 2*gamma/(sqrt(pi)*sigma2)*exp(-gamma*t1)*((1-2*t2.^2/sigma2).* ...\n exp(-(t2.^2)/sigma2)).';\nelse\n dUpsilonS = -gamma*dUpsilon - 4*timeGrid/(sqrt(pi)*sigma2^2).* ...\n exp(-(timeGrid.^2)./sigma2).*(3 - 2*(timeGrid.^2)/sigma2);\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/lfmvvGradientSigmaUpsilonMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6903501432835928}} {"text": "function Cbn = att2Cbn(att);\n%--------------------------------------------------------------------------\n% calculate the direct cosine matrix c_nb from b => n-frame given att (h,p,r)\n% assume 1 row or col input \n% c_nb = r3(-h)*r2(-p)*r1(-r);\n% Author: Yudan Yi\n% Aug. 2004\n% Feb. 2005\n%--------------------------------------------------------------------------\nif (nargin<1) error('error in data'); end;\natt = att(:);\nif (length(att)<3) error('error in data'); end;\n%H = att(1); P = att(2); R = att(3);\nR = att(1); P = att(2); H = att(3);\nCbn(1,1)\t= cos(H)*cos(P);\nCbn(2,1)\t= sin(H)*cos(P);\nCbn(3,1)\t=-\t sin(P);\nCbn(1,2)\t=-sin(H)*cos(R)+cos(H)*sin(P)*sin(R);\nCbn(2,2)\t= cos(H)*cos(R)+sin(H)*sin(P)*sin(R);\nCbn(3,2)\t= cos(P)*sin(R);\nCbn(1,3)\t= sin(H)*sin(R)+cos(H)*sin(P)*cos(R);\nCbn(2,3)\t=-cos(H)*sin(R)+sin(H)*sin(P)*cos(R);\nCbn(3,3)\t= cos(P)*cos(R);\n%--------------------------------------------------------------------------", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/ekfmonoslam/geodetic/att2Cbn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6902485845883977}} {"text": "function cheby_u_poly_coef_test ( )\n\n%*****************************************************************************80\n%\n%% CHEBY_U_POLY_COEF_TEST tests CHEBY_U_POLY_COEF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 October 2008\n%\n% Author:\n%\n% John Burkardt\n%\n n = 5;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHEBY_U_POLY_COEF_TEST\\n' );\n fprintf ( 1, ' CHEBY_U_POLY_COEF determines the Chebyshev U \\n' );\n fprintf ( 1, ' polynomial coefficients.\\n' );\n\n c = cheby_u_poly_coef ( n );\n \n for i = 0 : n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' U(%d)\\n', i );\n fprintf ( 1, '\\n' );\n for j = i : -1 : 0\n if ( j == 0 )\n fprintf ( 1, ' %f\\n', c(i+1,j+1) );\n elseif ( j == 1 )\n fprintf ( 1, ' %f * x\\n', c(i+1,j+1) );\n else\n fprintf ( 1, ' %f * x^%d\\n', c(i+1,j+1), j );\n end\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/polpak/cheby_u_poly_coef_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.6902072423385568}} {"text": "function [e1,e2,E1_l,E2_l,E1_s1,E2_s2] = pluckerEndpoints(L,s1,s2)\n\n% PLUCKERENDPOINTS Plucker line and abscissas to endpoints conversion.\n% [E1,E2] = PLUCKERENDPOINTS(L,S1,S2) are the endpoints of the Plucker\n% line L at abscissas S1 and S2.\n%\n% [E1,E2,E1_l,E2_l,E1_s1,E2_s2] = PLUCKERENDPOINTS(L,S1,S2) returns the\n% Jacobians wrt the line L and the abscissas S1 and S2.\n%\n% See also LS2E, LS2SEG.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nv = L(4:6);\n\nif nargout == 1\n\n vn = normvec(v);\n p0 = pluckerOrigin(L);\n e1 = p0 + s1*vn;\n e2 = p0 + s2*vn;\n\nelse % Jac\n \n [vn,VN_v] = normvec(v,0);\n [p0,P0_l] = pluckerOrigin(L);\n\n P0_n = P0_l(:,1:3);\n P0_v = P0_l(:,4:6);\n \n e1 = p0 + s1*vn;\n E1_s1 = vn;\n\n E1_n = P0_n;\n E1_v = P0_v + s1*VN_v;\n\n E1_l = [E1_n E1_v];\n\n e2 = p0 + s2*vn;\n E2_s2 = vn;\n\n E2_n = P0_n;\n E2_v = P0_v + s2*VN_v;\n\n E2_l = [E2_n E2_v];\n\nend\n\nreturn\n\n%% jac\n\nsyms n1 n2 n3 v1 v2 v3 s1 s2 real\nL = [n1;n2;n3;v1;v2;v3];\n\n[e1,e2,E1_l,E2_l,E1_s1,E2_s2] = pluckerEndpoints(L,s1,s2);\n\nsimplify(E1_l - jacobian(e1,L))\nsimplify(E2_l - jacobian(e2,L))\nsimplify(E1_s1 - jacobian(e1,s1))\nsimplify(E2_s2 - jacobian(e2,s2))\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/Lines/pluckerEndpoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.6902072307731514}} {"text": "function value = index0n ( n, i_min, i, i_max )\n\n%*****************************************************************************80\n%\n%% INDEX0N indexes an N-dimensional array by columns, with zero base.\n%\n% Discussion:\n%\n% Entries of the array are indexed starting at entry\n% ( I_MIN(1), I_MIN(2),...,I_MIN(N) ),\n% and increasing the first index up to I_MAX(1),\n% then the second and so on.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 November 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of indices.\n%\n% Input, integer I_MIN(N), the minimum indices.\n%\n% Input, integer I(N), the indices.\n%\n% Input, integer I_MAX(N), for maximum indices.\n%\n% Output, integer VALUE, the index of element I.\n%\n index_min = 0;\n\n value = ( i(n) - i_min(n) );\n\n for j = n - 1 : -1 : 1\n value = value * ( i_max(j) + 1 - i_min(j) ) + ( i(j) - i_min(j) );\n end\n value = value + index_min;\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/index/index0n.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.6902072242659285}} {"text": "function ray = createRay(varargin)\n%CREATERAY Create a ray (half-line), from various inputs.\n%\n% RAY = createRay(POINT, ANGLE)\n% POINT is a N*2 array giving starting point of the ray, and ANGLE is the\n% orientation of the ray.\n%\n% RAY = createRay(X0, Y0, ANGLE)\n% Specify ray origin with 2 input arguments.\n%\n% RAY = createRay(P1, P2)\n% Create a ray starting from point P1 and going in the direction of point\n% P2.\n%\n% Ray is represented in a parametric form: [x0 y0 dx dy]\n% x = x0 + t*dx\n% y = y0 + t*dy;\n% for all t>0\n%\n% Example\n% origin = [3 4];\n% theta = pi/6;\n% ray = createRay(origin, theta);\n% figure(1); clf; hold on;\n% axis([0 10 0 10]);\n% drawRay(ray);\n%\n% See also \n% rays2d, createLine, points2d\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2007-10-18\n% Copyright 2007-2022 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas\n\nif length(varargin)==2\n p0 = varargin{1};\n arg = varargin{2};\n if size(arg, 2)==1\n % second input is the ray angle\n ray = [p0 cos(arg) sin(arg)];\n else\n % second input is another point\n ray = [p0 arg-p0];\n end\n \nelseif length(varargin)==3 \n x = varargin{1};\n y = varargin{2};\n theta = varargin{3};\n ray = [x y cos(theta) sin(theta)]; \n\nelse\n error('Wrong number of arguments in ''createRay'' ');\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/geom2d/createRay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.6902072196110824}} {"text": "function PDP=ieee802_11_model(sigma_tau,Ts)\n% IEEE 802.11 channel model PDP generator\n% Input:\n% sigma_tau : RMS delay spread\n% Ts : Sampling time\n% Output:\n% PDP : Power delay profile\n \nlmax = ceil(10*sigma_tau/Ts);\nsigma02=(1-exp(-Ts/sigma_tau))/(1-exp(-(lmax+1)*Ts/sigma_tau)); % (2.9)\nl=0:lmax;\nPDP = sigma02*exp(-l*Ts/sigma_tau); % (2.8)", "meta": {"author": "LyricYang", "repo": "MIMO_OFDM", "sha": "df25e1837bc4019f2bbcd946bc49b0942827a847", "save_path": "github-repos/MATLAB/LyricYang-MIMO_OFDM", "path": "github-repos/MATLAB/LyricYang-MIMO_OFDM/MIMO_OFDM-df25e1837bc4019f2bbcd946bc49b0942827a847/\u7b2c2\u7ae0 SISO\u4fe1\u9053\u6a21\u578b/IEEE802.11\u4fe1\u9053\u6a21\u578b/ieee802_11_model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6901780397505862}} {"text": "function oeprint1(mu, oev)\n\n% print six classical orbital elements\n% and orbital period in minutes\n\n% input\n\n% mu = gravitational constant (km**3/sec**2)\n% oev(1) = semimajor axis (kilometers)\n% oev(2) = orbital eccentricity (non-dimensional)\n% (0 <= eccentricity < 1)\n% oev(3) = orbital inclination (radians)\n% (0 <= inclination <= pi)\n% oev(4) = argument of perigee (radians)\n% (0 <= argument of perigee <= 2 pi)\n% oev(5) = right ascension of ascending node (radians)\n% (0 <= raan <= 2 pi)\n% oev(6) = true anomaly (radians)\n% (0 <= true anomaly <= 2 pi)\n\n% Orbital Mechanics with MATLAB\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nrtd = 180 / pi;\n\n% unload orbital elements array\n\nsma = oev(1);\necc = oev(2);\ninc = oev(3);\nargper = oev(4);\nraan = oev(5);\ntanom = oev(6);\n\narglat = mod(tanom + argper, 2.0 * pi);\n\nif (sma > 0.0)\n period = 2.0d0 * pi * sma * sqrt(sma / mu);\nelse\n period = 99999.9;\nend\n\n% print orbital elements\n\nfprintf ('\\n sma (km) eccentricity inclination (deg) argper (deg)');\n\nfprintf ('\\n %+16.14e %+16.14e %+16.14e %+16.14e \\n', sma, ecc, inc * rtd, argper * rtd);\n\nfprintf ('\\n raan (deg) true anomaly (deg) arglat (deg) period (min)');\n\nfprintf ('\\n %+16.14e %+16.14e %+16.14e %+16.14e \\n', raan * rtd, tanom * rtd, arglat * rtd, period / 60);\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/39179-two-impulse-phasing-analysis/oeprint1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.690178035582501}} {"text": "function [AB]=vectorTensorProductArray(a,b)\n\n%% \n\n%Determine multiplication order\nif size(a,2)==3 %type B*A\n B=a;\n A=b;\n multType='post';\nelse %type A*B\n B=b;\n A=a; \n multType='pre';\nend\n\n%Perform product\nswitch multType\n case 'pre' %type A*B\n % A1_1*B1 + A1_2*B2 + A1_3*B3\n % A2_1*B1 + A2_2*B2 + A2_3*B3\n % A3_1*B1 + A3_2*B2 + A3_3*B3\n AB=[A(:,1).*B(:,1)+A(:,4).*B(:,2)+A(:,7).*B(:,3) ...\n A(:,2).*B(:,1)+A(:,5).*B(:,2)+A(:,8).*B(:,3) ...\n A(:,3).*B(:,1)+A(:,6).*B(:,2)+A(:,9).*B(:,3)];\n case 'post' %type B*A\n % A1_1*B1 + A1_2*B2 + A1_3*B3\n % A2_1*B1 + A2_2*B2 + A2_3*B3\n % A3_1*B1 + A3_2*B2 + A3_3*B3\n AB=[A(:,1).*B(:,1)+A(:,2).*B(:,2)+A(:,3).*B(:,3) ...\n A(:,4).*B(:,1)+A(:,5).*B(:,2)+A(:,6).*B(:,3) ...\n A(:,7).*B(:,1)+A(:,8).*B(:,2)+A(:,9).*B(:,3)];\nend\n\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/vectorTensorProductArray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787538, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6900702512266857}} {"text": "function v = norm(F)\n%NORM Frobenius norm of a CHEBFUN3V object.\n% V = NORM(F) returns the Frobenius norm of F, i.e. \n% V = sqrt(norm(F1).^2 + norm(F2).^2),\n% or\n% V = sqrt(norm(F1).^2 + norm(F2).^2 + norm(F3).^2) .\n% where F = [F1 F2 F3]^T.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Empty check: \nif ( isempty(F) ) \n v = [];\n return\nend\n\nnF = F.nComponents; \nv = 0;\nfor jj = 1:nF\n v = v + norm(F.components{jj})^2;\nend\nv = sqrt(v);\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun3v/norm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6900702416140179}} {"text": "% By Roger Aarenstrup, roger.aarenstrup@mathworks.com\n% 2006-08-18\n%\n% This is a state-space DC motor model of a\n% Maxon RE25 10 Watt, precious metal brushes, 118743\n% \n% This model also have a weak connection to a load.\n%\n\n%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The full dc motor model %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Vin is the input voltage to the motor\n% i is the motor current\n% th_m is the rotor angle, theta\n% dth_m is the rotor angular velocity sometimes called omega\n% th_l is the load angle\n% dth_l is the load angular velocity\n\n% Controller Sample Time\nTs = 100e-6;\n\n% PARAMETERS DC MOTOR\nRm = 2.06; % Motor resistance (ohm)\nLm = 0.000238; % motor inductance (Henrys)\nKb = 1/((406*2*pi)/60); % Back EMF constant (Volt-sec/Rad)\nKt = 0.0235; % Torque constand (Nm/A)\nJm = 1.07e-6; % Rotor inertia (Kg m^2)\nbm = 12e-7; % MEchanical damping (linear model of\n % friction: bm * dth)\n% PARAMETERS LOAD\nJl = 10.07e-6; % Load inertia (10 times the rotor)\nbl = 12e-6; % Load damping (friction)\nKs = 100; % Spring constant for connection rotor/load\nb = 0.0001; % Spring damping for connection rotor/load\n\n% SYSTEM MATRICES\n%\n% States: [i dth_m th_m dth_l th_l]' \n% Input: Vin the motor voltage\n% Outputs: same as states\n%\nAfull = [-Rm/Lm -Kb/Lm 0 0 0;\n Kt/Jm -(bm+b)/Jm -Ks/Jm b/Jm Ks/Jm;\n 0 1 0 0 0;\n 0 b/Jl Ks/Jl -(b+bl)/Jl -Ks/Jl;\n 0 0 0 1 0];\n \nBfull = [1/Lm 0 0 0 0]';\n\nCfull = [0 1 0 0 0;\n 0 0 1 0 0;\n 0 0 0 1 0;\n 0 0 0 0 1];\n\nDfull = [0 0 0 0]';\n\nsys_full = ss(Afull, Bfull, Cfull, Dfull);\n\n%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The reduced dc motor model for current control %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% SYSTEM MATRICES\n%\n% States: [dth_m th_m dth_l th_l]' \n% Input: I The current to the dc motor\n% Outputs: same as states\n%\nAred = [ -(bm+b)/Jm -Ks/Jm b/Jm Ks/Jm;\n 1 0 0 0;\n b/Jl Ks/Jl -(b+bl)/Jl -Ks/Jl;\n 0 0 1 0];\n \nBred = [Kt/Jm 0 0 0]';\n\nCred = eye(4);\n\nDred = [0 0 0 0]';\n\nsys_red = ss(Ared, Bred, Cred, Dred);\n\n% Discrete version of the model (as seen from the controller)\nsys_red_d = c2d(sys_red, Ts, 'zoh');\n\n%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Scaling of reduced state-space model %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% u = Nu * un\n% x = Nx * xn\n% y = Ny * yn\n% u, x, y are real inputs, states and outputs\n% un, xn, yn are normalized \n\nmax_current = 0.01; % 10 mA as input\nmax_pos = 4.1;\nmax_v = 4.1;\n\n\nNu = max_current;\nNx = [max_v 0 0 0; 0 max_pos 0 0; 0 0 max_v 0; 0 0 0 max_pos];\nNy = Nx;\n\nAn = inv(Nx)*Ared*Nx;\nBn = inv(Nx)*Bred*Nu;\nCn = inv(Ny)*Cred*Nx;\nDn = 0;\n\nsys_red_n = ss(An, Bn, Cn, Dn);\n\nsys_red_d_n = c2d(sys_red_n, Ts, 'zoh');\n\n%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% State-space controller design attempt 1 %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% The discrete poles of the closed loop system\ndpole1 = exp(-2*pi*Ts*[20 22 24 26]);\n\n% Calculate the control parameters\nL1 = place(sys_red_d_n.a, sys_red_d_n.b, dpole1);\n\n% Keep the static gain of the closed loop system to 1\nF=feedback(sys_red_d_n, L1); % The closed loop system, F.\nKstatic = freqresp(F, 0); % Get the static gain of F.\nKstat = 1/Kstatic(4); % It is the fourth output (load position)\n\n% The above commands requires toolboxes, incase you don't have them\n% you can simulate the system with a unit step is see the output static\n% gain. Kstat will be the inverse of that.\n\n% to verify the pole placement\n%pzmap(F);\n\n%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% State-space controller design attempt 2 - Integrator %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% The discrete poles of the closed loop system\ndpole2 = exp(-2*pi*Ts*[20 22 24 26 5]); \n\n% We only consider one output here\nCred_one = [0 1 0 0];\n\n% Calculate the control parameters\nAint = [sys_red_d_n.a [0 0 0 0]';\n -Cred_one 1];\n \nBint= [sys_red_d_n.b' 0]';\n\nCint = [Cred_one 0];\n\nDint = [0]';\n\nsys_int_d2 = ss(Aint, Bint, Cint, Dint, Ts);\n\n% Controllability VS Observability analysis\n%ob = obsv(sys_int_d2.a, sys_int_d2.c);\n%cr = ctrb(sys_int_d2.a, sys_int_d2.b);\n%rank(ob)\n%rank(cr)\n\n[L2, a, m] = place(sys_int_d2.a, sys_int_d2.b, dpole2);\n\n% Feed Forward gain\nKff = L2(5)/(dpole2(5) - 1);\n\n%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% State-space controller design attempt 3 - Observer %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% These should be about twice as fast as the state feedback\n% for the controller.\ndpole3 = exp(-2*pi*Ts*[1400 1450 1500 1550]);\n%dpole3 = [-0.3 -0.33 -0.35 -0.37];\n\n% Recalculate the reduced model with one ouput\n\nAred2 = inv(Nx)*Ared*Nx; % Scaling\nBred2 = inv(Nx)*Bred*Nu; % Scaling\nCred2 = [0 1 0 0];\nDred2 = 0;\n\nsys_red2 = ss(Ared2, Bred2, Cred2, Dred2);\n\n% Discrete version of the model (as seen from the controller)\nsys_red_d2 = c2d(sys_red2, Ts, 'zoh');\n\nset(sys_red_d2, 'inputname', {'Um'}, ...\n 'outputname', {'Enc_out'});\n\n% Calculate the observer state feedback\nK = place(sys_red_d2.a', sys_red_d2.c', dpole3);\n\n% Put the observer together\nAobs = [sys_red_d2.a-K'*sys_red_d2.c];\nBobs = [sys_red_d2.b K'];\nCobs = eye(4);\nDobs = [0 0 0 0; 0 0 0 0]';\n\nobserver = ss(Aobs, Bobs, Cobs, Dobs, Ts, 'inputname', {'Ue', 'Enc_in'}, ...\n 'outputname', {'dth_m', 'th_m', 'dth_l', 'th_l'});\n\n%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% State-space controller design attempt 4 - The Servo Case %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nKinv = (Jl+Jm)/Kt;\n\ndpole4 = exp(-2*pi*Ts*[200 204 220 224 300]);\n[L3, a, m] = place(sys_int_d2.a, sys_int_d2.b, dpole4);\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/12137-pid-and-state-feedback-control-of-dc-motors/dc_motor_demo/3_mbd_project/e_fixed_point/matlab_control_design/ctrl_params.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6900598958189375}} {"text": "%% This function will calculate the prediction error between the discovered system and actual test data\n% There are two methods to calculate the prediction error.\n%\n% Method one: This method suits for the one dimensional system only. The idea is\n% using ODE45 to drive each point k-steps forward in time and calculate the\n% prediction error between the system estimation and actual states. Here,\n% the system's estimate is the value of derivative at k-steps.\n%\n% Method two: This method suits for one dimensional system and\n% multi-dimensional system. We use immediate prediction of the system's\n% derivative and calculate the prediction error of the system model's\n% derivative output and actual derivative.\n%\n% Last Updated: 2019/06/04\n% Coded By: K\n%%\nfunction [Score]=Get_Score(dData_test,Data_test,u,Control,tspan,Shuffle,name,Prediction_Steps,dt,size1,size2,method)\n% Get the ODE simulation result\nNoise=0;\n\n% Start calculate\nif method ==1\n % If the method one is selected, then we use the multi step prediction\n \n % Generate the function handel\n if u==0\n ODE_func=str2func(strcat('@(t,z)',name,'(t,z)'));\n end\n \n % Pass the test data as dummy variable\n Dummy=Data_test;\n \n if Prediction_Steps==0\n % This will result immediate prediction\n dData_Es=ODE_func(0,Dummy);\n Error=norm(dData_test-dData_Es);\n Dem=norm(dData_test);\n Score=Error/Dem;\n else\n dData_Es=ODE_func(0,Dummy);\n % Get the function estimation using RK45\n for pinpin=1:Prediction_Steps\n RK_k1=dt*dData_Es;\n RK_k2=dt*ODE_func(0,Dummy+0.5*RK_k1);\n RK_k3=dt*ODE_func(0,Dummy+0.5*RK_k2);\n RK_k4=dt*ODE_func(0,Dummy+RK_k3);\n Dummy=Dummy+(1/6)*(RK_k1+2*RK_k2+2*RK_k3+RK_k4);\n dData_Es=ODE_func(0,Dummy);\n end\n \n % Reshape\n Dum1=reshape(dData_Es,size1,size2);\n Dum2=reshape(dData_test,size1,size2);\n \n % Arrange all the data to the same time \n Dum3=Dum1(1:end-Prediction_Steps,:);\n Dum4=Dum2(1+Prediction_Steps:end,:);\n \n % Calculate the prediction error\n Error=norm(reshape((Dum4-Dum3),[],1));\n Dem=norm(reshape(Dum4,[],1));\n \n % Calculate the norm\n Score=Error/Dem;\n end\nelse\n % Generate the function handel\n if u==0\n ODE_func=str2func(strcat('@(t,z)',name,'(t,z)'));\n end\n \n % Get the function estimation\n dData_Es=ODE_func(0,Data_test);\n Error=norm(dData_test-dData_Es);\n Dem=norm(dData_test);\n Score=Error/Dem;\nend\n\n\n\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/Comparison/NoiseSensitivity/Michaelis-Menten kinetics/Functions/Get_Score.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6900598907099601}} {"text": "%GAUSS Generation of a multivariate Gaussian dataset\n% \n% \tA = GAUSS(N,U,G,LABTYPE) \n%\n% INPUT (in case of generation a 1-class dataset in K dimensions)\n% N\t\t Number of objects to be generated (default 50).\n% U\t\t Desired mean (vector of length K).\n% G K x K covariance matrix. Default eye(K).\n% LABTYPE Label type (default 'crisp')\n%\n% INPUT (in case of generation a C-class dataset in K dimensions)\n% N Vector of length C with numbers of objects per class.\n% U C x K matrix with class means, or\n% Dataset with means, labels and priors of classes \n% (default: zeros(C,K))\n% G K x K x C covariance matrix of right size.\n% Default eye(K);\n% LABTYPE\tLabel type (default 'crisp')\n%\n% OUTPUT\n% A Dataset containing multivariate Gaussian data\n%\n% DESCRIPTION\n% Generation of N K-dimensional Gaussian distributed samples for C classes.\n% The covariance matrices should be specified in G (size K*K*C) and the\n% means, labels and prior probabilities can be defined by the dataset U with\n% size (C*K). If U is not a dataset, it should be a C*K matrix and A will\n% be a dataset with C classes.\n%\n% If N is a vector, exactly N(I) objects are generated for class I, I = 1..C.\n% \n% EXAMPLES\n% 1. Generation of 100 points in 2D with mean [1 1] and default covariance\n% matrix: \n%\n% GAUSS(100,[1 1])\n%\n% 2. Generation of 50 points for each of two 1-dimensional distributions with\n% mean -1 and 1 and with variances 1 and 2:\n%\n%\t GAUSS([50 50],[-1;1],CAT(3,1,2))\n%\n% Note that the two 1-dimensional class means should be given as a column\n% vector [1;-1], as [1 -1] defines a single 2-dimensional mean. Note that\n% the 1-dimensional covariance matrices degenerate to scalar variances,\n% but have still to be combined into a collection of square matrices using\n% the CAT(3,....) function.\n%\n% 3. Generation of 300 points for 3 classes with means [0 0], [0 1] and \n% [1 1] and covariance matrices [2 1; 1 4], EYE(2) and EYE(2):\n%\n% GAUSS(300,[0 0; 0 1; 1 1]*3,CAT(3,[2 1; 1 4],EYE(2),EYE(2)))\n%\n% SEE ALSO (PRTools Guide) \n% DATASETS, PRDATASETS\n\n% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com\n% Faculty EWI, Delft University of Technology\n% P.O. Box 5031, 2600 GA Delft, The Netherlands\n\nfunction a = gauss(n,u,g,labtype)\n\n\t\tif (nargin < 1)\n\t\tprwarning (2,'number of samples not specified, assuming N = 50'); \t\n\t\tn = 50;\n\t\tend\n\t\tcn = length(n);\n\tif (nargin < 2)\n\t\tprwarning (2,'means not specified; assuming one dimension, mean zero');\n\t\tu = zeros(cn,1); \n\tend;\n\tif (nargin < 3)\n\t\tprwarning (2,'covariances not specified, assuming unity');\n\t \tg = eye(size(u,2)); \n\tend\n\tif (nargin < 4)\n\t\tprwarning (3,'label type not specified, assuming crisp');\n\t\tlabtype = 'crisp'; \n\tend\n\n\t% Return an empty dataset if the number of samples requested is 0.\n\n\tif (length(n) == 1) & (n == 0)\n\t\ta = prdataset([]); \n\t\treturn\n\tend\n\n\t% Find C, desired number of classes based on U and K, the number of \n\t% dimensions. Make sure U is a dataset containing the means.\n\n\tif (isa(u,'prdataset'))\n\t\t[m,k,c] = getsize(u);\n\t\tlablist = getlablist(u);\n\t\tp = getprior(u);\n\t\tif c == 0\n\t\t\tu = double(u);\n\t\tend\n\tend\n\tif isa(u,'double')\n\t\t[m,k] = size(u); \t\t\n\t\tc = m;\n\t\tlablist = genlab(ones(c,1));\n\t\tu = prdataset(u,lablist);\n\t\tp = ones(1,c)/c;\n\tend\n\n\tif (cn ~= c) & (cn ~= 1)\n\t\terror('The number of classes specified by N and U does not match');\n\tend\n\n \t% Generate a class frequency distribution according to the desired priors.\n\tn = genclass(n,p);\n\n\t% Find CG, the number of classes according to G. \n\t% Make sure G is not a dataset.\n\n\tif (isempty(g))\n\t\tg = eye(k); \n\t\tcg = 1;\n\telse\n\t\tg = real(+g); [k1,k2,cg] = size(g);\n\t\tif (k1 ~= k) | (k2 ~= k)\n\t\t\terror('The number of dimensions of the means U and covariance matrices G do not match');\n\t\tend\n\t\tif (cg ~= m & cg ~= 1)\n\t\t\terror('The number of classes specified by the means U and covariance matrices G do not match');\n\t\tend\n\tend\n\n\t% Create the data A by rotating and scaling standard normal distributions \n\t% using the eigenvectors of the specified covariance matrices, and adding\n\t% the means.\n\n\t%a = [];\n a = zeros(sum(n),k);\n nn = 0;\n\tfor i = 1:m\n\t\tj = min(i,cg);\t\t\t\t\t\t% Just in case CG = 1 (if G was not specified).\n\n\t\t% Sanity check: user can pass non-positive definite G.\t\t\n\t\t[V,D] = preig(g(:,:,j)); V = real(V); D = real(D); D = max(D,0);\n a(nn+1:nn+n(i),:) = randn(n(i),k)*sqrt(D)*V' + repmat(+u(i,:),n(i),1);\n\t\t%a = [a; randn(n(i),k)*sqrt(D)*V' + repmat(+u(i,:),n(i),1)];\n nn = nn+n(i);\n\tend\n\n\t% Convert A to dataset by adding labels and priors.\n\n\tlabels = genlab(n,lablist);\n\ta = prdataset(a,labels,'lablist',lablist,'prior',p);\n\n\t% If non-crisp labels are requested, use output of Bayes classifier.\n\tswitch (labtype)\n\t\tcase 'crisp'\n\t\t\t;\n\t\tcase 'soft'\n\t\t\tw = nbayesc(u,g); \t\t\n\t\t\ttargets = a*w*classc;\n\t\t\ta = setlabtype(a,'soft',targets);\n\t\totherwise\n\t\t\terror(['Label type ' labtype ' not supported'])\n\tend\n\n\ta = setname(a,'Gaussian Data');\n\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/gauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757870013740061, "lm_q2_score": 0.787931185683219, "lm_q1q2_score": 0.6900598903985715}} {"text": "function dag = sample_dag(P)\n% SAMPLE_DAG Create a random directed acyclic graph with edge probabilities P(i,j)\n% dag = sample_dag(P)\n%\n% This uses rejection sampling to reject graphs with directed cycles.\n\ndone = 0;\ndirected = 1;\niter = 1;\nwhile ~done\n dag = binornd(1, P); % each edge is an indep Bernoulli (0/1) random variable\n dag = setdiag(dag, 0);\n done = acyclic(dag, directed);\n iter = iter + 1\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/graph/mk_rnd_dag_given_edge_prob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6900598812397054}} {"text": "function jed = ymdf_to_jed_hindu_solar ( y, m, d, f )\n\n%*****************************************************************************80\n%\n%% YMDF_TO_JED_HINDU_SOLAR converts a Hindu solar YMDF date to a JED.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 March 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Edward Reingold, Nachum Dershowitz, Stewart Clamen,\n% Calendrical Calculations, II: Three Historical Calendars,\n% Software - Practice and Experience,\n% Volume 23, Number 4, pages 383-404, April 1993.\n%\n% Parameters:\n%\n% Input, integer Y, M, D, real F, the YMDF date.\n%\n% Output, real JED, the Julian Ephemeris Date.\n%\n jed_epoch = epoch_to_jed_hindu_solar ( );\n\n jed = jed_epoch + ...\n ( d - 1 ) ...\n + ( m - 1 ) * month_length_hindu_solar ( ) ...\n + y * year_length_hindu_solar ( ) ...\n + f;\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/calpak/ymdf_to_jed_hindu_solar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6900189029297086}} {"text": "\nfunction a = gauss(i1,i2,i3) \n\n%==================================================================== \n% GAUSS gauss/gaussian density estimation object\n%==================================================================== \n% A=GAUSS([M],[S],H) returns a gauss object initialized with mean M,\n% std S and hyperparameters H. Can also be called with GAUSS(H)\n%\n% Training will try to fit a single Gaussian to the data.\n% Testing will return the probability estimate, or if passed\n% an empty dataset will generate new data according to the \n% density learnt.\n%\n% Hyperparameters:\n% l=50 -- number of data points to generate if asked to generate \n% assume=[] -- can make assumptions: {'diag_cov','equal_cov'}\n% where the matrix is diagonal ('diag_cov'), \n% or diagonal with all elements equal ('equal_cov')\n% \n% Model:\n% mean=0 -- centre of gauss distbn\n% cov=1 -- cov matrix, if single value assumes diagonal\n% of matrix all has same values, if vector assumes it\n% is the diagonal of the matrix, with 0s everywhere else\n%\n% Methods:\n% train, test, generate\n%\n% Examples:\n% gen(gauss) % generate data\n% gen(gauss('l=5;mean=[1 1];cov=0.01;')) % generate data\n%\n% d=test(gauss([1 5],[1 -0.4 ; -0.4 1],'l=300')); \n% [d2 a]=train(gauss('l=200'),d);\n% d2=test(a); %% train a gauss on some (gauss) data and then\n% %% try to generate similar data\n% hold off; plot(d.X(:,1),d.X(:,2),'o')\n% hold on; plot(d2.X(:,1),d2.X(:,2),'rx')\n%====================================================================\n% Reference : chapter 2 (Richard O. Duda and Peter E. Hart) Bayesian Decision Theory\n% Author : Richard O. Duda , Peter E. Hart\n% Link : http://www.amazon.com/exec/obidos/tg/detail/-/0471056693/002-6279399-2828812?v=glance\n%==================================================================== \n \n a.l=50;\n a.mean=0;\n a.cov=1;\n a.assume=[];\n \n p=algorithm('gauss');\n a= class(a,'gauss',p);\n \n \n if nargin==1 \n if ischar(i1)\n hyper=i1; eval_hyper; return;\n else\n a.mean=i1; \n end\n end;\n \n if nargin==2 \n a.mean=i1; \n if ischar(i2)\n hyper=i2; eval_hyper; return;\n else\n a.cov=i2;\n end\n end;\n \n if nargin==3 \n a.mean=i1;\n a.cov=i2;\n hyper=i3; eval_hyper; \n end;\n \n\n\n\n\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/spider/density/@gauss/gauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8080672112416736, "lm_q1q2_score": 0.6900188909130591}} {"text": "% Figure 7.16 Feedback Control of Dynamic Systems, 6e\n% Franklin, Powell, Emami\n%\n%\n% script to generate Fig. 7.16\n% fig7_16.m \n%\nclf;\nf=[0 1;-1 0];\ng=[0;1];\nh=[1 0];\nK=[3 4];\nfc=f-g*K;\ngc=[4*g [1;0]];\nhc=[h;[0 1]; -K/4];\njc=[0 0;0 0; 1 0];\nt=0:.1:7;\nsys=ss(fc,gc,hc,jc);\n[y,t]=step(sys,t);\nplot(t,y(:,:,1));\nxlabel('Time (sec)');\nylabel('Amplitude');\ntext(1.5,.9,'x_1');\ntext(1.6,.3,'x_2');\ntext(1.5,.05,'u/4');\ntext(6.5,.3,'u_{ss}');\ntext(6.5,.95,'x_{ss}');\ntitle('Fig. 7.16 Step response of the oscillator to a reference input');\nnicegrid;\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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig7_16.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6899637203519206}} {"text": "function out = getPolCoeffs(T,a,b,wf,N,q0)\n% -----------------------------------------------------------------------\n% The function computes coefficeints of the 5-th order polynomail\n% from a and b coefficients of the finite furier series and \n% initial position of the robot.\n% Inputes:\n% T - period of motion\n% a - sine coeffs in finite fourier series\n% b - cosine coeffs in finite fourier series\n% wf - fundamental frequency\n% N - number of harmonics\n% q0 - initial position of the robot\n% Output:\n% out - coefficients of the fifth order polynomail that guarantees\n% that initial and final constraints on position, velocities\n% and accelerations are satisfied\n% -----------------------------------------------------------------------\nqh0 = -sum(b./((1:N)*wf),2);\nqdh0 = sum(a,2);\nq2dh0 = sum(b.*(1:1:N)*wf,2);\n\n[qhT,qdhT,q2dhT] = fourier_series_traj(T,zeros(6,1),a,b,wf,N);\n\nI_6x6 = eye(6);\nO_6x6 = zeros(6);\n\nAc = [I_6x6, O_6x6, O_6x6, O_6x6, O_6x6, O_6x6;\n O_6x6, I_6x6, O_6x6, O_6x6, O_6x6, O_6x6;\n O_6x6, O_6x6, 2*I_6x6, O_6x6, O_6x6, O_6x6;\n I_6x6, T*I_6x6, T^2*I_6x6, T^3*I_6x6, T^4*I_6x6, T^5*I_6x6;\n O_6x6, I_6x6, 2*T*I_6x6, 3*T^2*I_6x6, 4*T^3*I_6x6, 5*T^4*I_6x6;\n O_6x6, O_6x6, 2*I_6x6, 6*T*I_6x6, 12*T^2*I_6x6, 20*T^3*I_6x6];\n\n% q0 = deg2rad([0 -90 0 -90 0 0 ]'); % !!!!!!!!!!!\nc = Ac\\[q0-qh0; -qdh0; -q2dh0; q0-qhT; -qdhT; -q2dhT];\nout = reshape(c,[6,6]);", "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/getPolCoeffs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979619, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6899637186222674}} {"text": "function b = frank_rhs ( m, k )\n\n%*****************************************************************************80\n%\n%% FRANK_RHS returns the FRANK right hand side.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the row dimension.\n%\n% Input, integer K, the column dimension ( should be 2).\n%\n% Output, real B(M,K), the right hand side matrix.\n%\n b = zeros ( m, k );\n\n b(1:m,1) = 1.0;\n\n b(1 ,2) = m * ( m + 1 ) / 2;\n for i = 2 : m\n b(i,2) = ( m + 1 - i ) * ( m + 4 - i ) / 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/test_mat/frank_rhs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.6899470918892645}} {"text": "function bsf_test ( )\n\n%*****************************************************************************80\n%\n%% BSF_TEST tests BSF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 September 2008\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BSF_TEST:\\n' );\n fprintf ( 1, ' A demonstration of the Black-Scholes formula\\n' );\n fprintf ( 1, ' for option valuation.\\n' );\n\n s0 = 2.0;\n t0 = 0.0;\n e = 1.0;\n r = 0.05;\n sigma = 0.25;\n t1 = 3.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The asset price at time T0, S0 = %f\\n', s0 );\n fprintf ( 1, ' The time T0 = %f\\n', t0 );\n fprintf ( 1, ' The exercise price E = %f\\n', e );\n fprintf ( 1, ' The interest rate R = %f\\n', r );\n fprintf ( 1, ' The asset volatility SIGMA = %f\\n', sigma );\n fprintf ( 1, ' The expiry date T1 = %f\\n', t1 );\n\n c = bsf ( s0, t0, e, r, sigma, t1 );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The option value C = %f\\n', 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/black_scholes/bsf_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.689864042567514}} {"text": "function [y,deriv] = square_distance_mv2df(w,input_data,new_dim)\n% This is an MV2DF. See MV2DF_API_DEFINITION.readme.\n%\n% The function computes the square distance of the vectors for each trial.\n% y.' = sum((W(:,1:end-1).'*input_data + W(:,end)).^2,1)\n%\n% W is the augmented matrix [M c] where M maps a score vector\n% to a lower dimensional space and c is an offset vector in\n% the lower dimensional space.\n%\n% Parameters:\n% w: the vectorized version of the W matrix\n% input_data: is an M-by-T matrix of input vectors of length M, for each of T\n% trials.\n% new_dim: the dimension of vectors in the lower dimensional space.\n%\n\nif nargin==0\n test_this();\n return;\nend\n\nif isempty(w) \n [dim, num_trials] = size(input_data);\n map = @(w) map_this(w,input_data,dim,new_dim);\n transmap = @(w) transmap_this(w,input_data,num_trials,new_dim);\n delta = linTrans(w,map,transmap);\n y = sums_of_squares(delta,new_dim);\n return;\nend\n\nif isa(w,'function_handle')\n f = square_distance_mv2df([],input_data,new_dim);\n y = compose_mv(f,w,[]);\n return;\nend\n\nf = square_distance_mv2df([],input_data,new_dim);\nif nargout==1\n y = f(w);\nelse\n [y,deriv] = f(w);\nend\n\n\n\n\nfunction y = map_this(w,input_data,dim,new_dim)\n% V = [input_data; ones(1,num_trials)];\nW = reshape(w,new_dim,dim+1);\ny = bsxfun(@minus,W(:,1:end-1)*input_data,W(:,end));\ny = y(:);\n\nfunction dx = transmap_this(dy,input_data,num_trials,new_dim)\ndY = reshape(dy,new_dim,num_trials);\n% V = [input_data; ones(1,num_trials)];\n% Vt = V.';\n% dX = dY*Vt;\ndYt = dY.';\ndYtSum = sum(dYt,1);\ndX = [input_data*dYt;-dYtSum].';\ndx = dX(:);\n\n\nfunction test_this()\nK = 5;\nN = 10;\nP = 3;\nM = randn(P,N);\nc = randn(P,1);\nW = [M c];\nw = W(:);\ninput_data = randn(N,K);\n\nf = square_distance_mv2df([],input_data,P);\ntest_MV2DF(f,w);\n", "meta": {"author": "nesl", "repo": "asvspoof2019", "sha": "8b780369f7273345c22d979192119198bbf3db13", "save_path": "github-repos/MATLAB/nesl-asvspoof2019", "path": "github-repos/MATLAB/nesl-asvspoof2019/asvspoof2019-8b780369f7273345c22d979192119198bbf3db13/baseline/tDCF_v1/bosaris_toolkit.1.06/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/mv2df_function_library/square_distance_mv2df.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6898640349995558}} {"text": "% ------------------------------------------------------------------------\n% Copyright (C) 2013 University of Southern California, SAIL, U.S.\n% Author: Maarten Van Segbroeck\n% Mail: maarten@sipi.usc.edu\n% Date: 2013-28-10\n% ------------------------------------------------------------------------\n% ltsv = FE_LTSV(sam,fs,R,M,ltsvThr,ltsvSlope);\n% Generates a Long-Term Spectral Variability (LTSV) stream of speech compute on the \n% Gammatone filtered time-frequency representation of speech (different from original\n% LTSV stream in [1]). The LTSV is also processed by a sigmoid function to assure\n% a probability value between 0 and 1 on the current signal \n%\n% --IN--\n% sam: sample file\n% fs: sampling frequency\n% R: context window parameter [default:50 \n% M: smoothing parameter [default:M]\n% ltsvThr: threshold of sigmoid function [default:0.5]\n% ltsvSlope: slope of sigmoid function [default:0.2]\n%\n% --OUT--\n% ltsv: LTSV stream of the signal\n\nfunction ltsv=FE_LTSV(sam,fs,R,M,gt,ltsvThr,ltsvSlope);\n\nFrameLen=0.032*fs;\nFrameShift=0.01*fs;\nNfft=2^ceil(log(FrameLen)/log(2));\nNfft=128;\nS=FE_GT(sam,fs,Nfft,FrameLen);\n\nif ~exist('R', 'var')\n R=50; \nend\nif ~exist('M', 'var')\n M=10; \nend\nif ~exist('ltsvThr', 'var')\n ltsvThr=0.5;\nend\nif ~exist('ltsvSlope', 'var')\n ltsvSlope=0.2;\nend\n\nappend_ndx=size(S,2):-1:max(size(S,2)-20,1);\nS=[S S(:,append_ndx)];\n\n% frequency smoothing\nS_M=[];\nfor k=1:size(S,1)\n\tS_M(k,:)=(smooth(S(k,:),M,'moving'));\nend\n% normalized spectrogram\nS_R=[];\nfor t=1:size(S,2)\n\tndx=[ones(1,R/2-t) max(1,t-R/2+1):min(size(S,2),t+R/2) ones(1,R/2+t-size(S,2))];\n%\tndx=[t:min(size(S,2),t+R) ones(1,R+t-size(S,2))];\n\tS_R(:,t)=S_M(:,t)./sum(S_M(:,ndx),2);\nend\n\n% entropy measure of normalized spectrogram over R consecutive frames, ending at current frame\nE_R=-100*S_R.*log(100*S_R);\nL=var(E_R);\n\nL=[];\nN=[1];\nskip=0;\nfor n=1:length(N)\n for i=1:N(n)\n fndx=round([Nfft*(i-1)/(2*N(n))+1:Nfft*i/(2*N(n))]);\n\tfndx=unique(min(max(fndx,1),Nfft));\n\tL(i+skip,:)=var(E_R(fndx,:));\n end\n skip=skip+N(n);\nend\n\nS=S(:,1:end-length(append_ndx));\nL=L(:,1:end-length(append_ndx));\nif exist('ltsvThr', 'var') && exist('ltsvSlope', 'var')\n L=sigmoid(2*L-ltsvThr,ltsvSlope);\nend\nltsv=L;\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/refVAD/vad-master/mfiles/FE_LTSV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.6898640299639814}} {"text": "function [ball, labels] = imInscribedBall(lbl, varargin)\n% Maximal ball inscribed in a 3D region.\n%\n% BALL = imInscribedBall(IMG)\n% Computes the maximal ball inscribed in a given 3D particle, or\n% around each labeled particle in the input image.\n%\n% BALL = imInscribedBall(IMG, LABELS)\n% Specify the labels for which the inscribed ball needs to be computed.\n% The result is a N-by-3 array with as many rows as the number of labels.\n%\n% Examples\n% % Test with a discretized ball\n% img = discreteBall(1:100, 1:100, 1:100, [40 50 60 35]);\n% ball = imInscribedBall(img)\n% ball =\n% 40 50 60 35\n%\n% % Check with a an octant of ball\n% img = discreteBall(1:100, 1:100, 1:100, [90 90 90 80]);\n% img(91:end, :,:) = 0;\n% img(:, 91:end, :) = 0;\n% img(:, :, 91:end) = 0;\n% ball = imInscribedBall(img)\n% ball =\n% 61 61 61 30\n% \n% See also\n% drawSphere, imInscribedCircle, imInertiaEllipsoid\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% Created: 2013-07-05, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2013 INRA - Cepia Software Platform.\n\n% check if labels are specified\nlabels = [];\nif ~isempty(varargin) && size(varargin{1}, 2) == 1\n labels = varargin{1};\nend\n\n% extract the set of labels, without the background\nif isempty(labels)\n labels = imFindLabels(img);\nend\nnLabels = length(labels);\n\n% allocate memory for result (3 coords + 1 radius)\nball = zeros(nLabels, 4);\n\nfor i = 1:nLabels\n % compute distance map from background\n distMap = bwdist(lbl ~= labels(i));\n \n % find value and position of the maximum\n [maxi, inds] = max(distMap(:));\n [yb, xb, zb] = ind2sub(size(distMap), inds);\n \n ball(i,:) = [xb yb zb maxi];\nend\n\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imMeasures/imInscribedBall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7956581097540518, "lm_q1q2_score": 0.6898640282659931}} {"text": "function img = discretePolygon(varargin)\n%DISCRETEPOLYGON Discretize a planar polygon\n%\n% IMG = discretePolygon(DIM, POINTS)\n% DIM is the size of image, with the format [x0 dx x1;y0 dy y1]\n% POINTS is a N-by-2 array containing coordinate of polygon vertices.\n% Returns an image containing a discrete approximation of the polygon.\n%\n% IMG = discretePolygon(LX, LY, ...);\n% Specifes the pixels coordinates with the two row vectors LX and LY.\n%\n% See Also\n% imShapes, discretePolyline\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2006-05-16\n% Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).\n\n% HISTORY\n% 04/03/2009: use meshgrid\n% 29/05/2009: use more possibilities for specifying grid\n\n% compute coordinate of image voxels\n[lx, ly, varargin] = parseGridArgs(varargin{:});\n[x, y] = meshgrid(lx, ly);\n\n% process input parameters\nif length(varargin)==1\n var = varargin{1};\n px = var(:,1);\n py = var(:,2);\n \nelseif length(varargin)==2\n px = varargin{1};\n py = varargin{2};\nend\n\n% compute discrete version of the polygon\nimg = inpolygon(x, y, px, py);\n\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imShapes/discretePolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6898640206980342}} {"text": "function prob_test101 ( )\n\n%*****************************************************************************80\n%\n%% TEST101 tests LOG_SERIES_CDF, LOG_SERIES_CDF_INV, LOG_SERIES_PDF.\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 fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST101\\n' );\n fprintf ( 1, ' For the Logseries PDF,\\n' );\n fprintf ( 1, ' LOG_SERIES_CDF evaluates the CDF;\\n' );\n fprintf ( 1, ' LOG_SERIES_CDF_INV inverts the CDF.\\n' );\n fprintf ( 1, ' LOG_SERIES_PDF evaluates the PDF;\\n' );\n\n a = 0.25;\n\n check = log_series_check ( a );\n\n if ( ~check );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST101 - Fatal error!\\n' );\n fprintf ( 1, ' The parameters are not legal.\\n' );\n return\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' PDF parameter A = %14f\\n', a );\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X PDF CDF CDF_INV\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : 10\n\n [ x, seed ] = log_series_sample ( a, seed );\n\n pdf = log_series_pdf ( x, a );\n\n cdf = log_series_cdf ( x, a );\n\n x2 = log_series_cdf_inv ( cdf, a );\n\n fprintf ( 1, ' %14d %14f %14f %14d\\n', x, pdf, cdf, x2 );\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/prob_test101.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.6898640080945019}} {"text": "function chi = imEuler3dDensity(img, varargin)\n% Compute Euler density in a 3D image.\n%\n% CHI_V = imEuler3dDensity(IMG)\n% Compute Euler number estimate in a 3D image, and normalize by the\n% observed volume. This function is well suited for estimating\n% topological properties of a random material observed through a sampling\n% window.\n%\n% CHI_V = imEuler3dDensity(IMG, CONN)\n% Specifies the connectivity to use to define whether two voxels are\n% neihbors or not. Can be either 6 (the default) or 26. \n%\n% Example\n% imEuler3dDensity\n%\n% See also\n% imEuler3d, imEuler3dEstimate, imSurfaceAreaDensity, imMeanBreadthDensity\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% Created: 2010-07-26, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRAE - Cepia Software Platform.\n\n\n% check image dimension\nif ndims(img) ~= 3\n error('first argument should be a 3D image');\nend\n\n% in case of a label image, return a vector with a set of results\nif ~islogical(img)\n labels = unique(img);\n labels(labels==0) = [];\n epcd = zeros(length(labels), 1);\n for i = 1:length(labels)\n epcd(i) = imEuler3dDensity(img==labels(i), varargin{:});\n end\n return;\nend\n\n% Process user input arguments\ndelta = [1 1 1];\nconn = 6;\nwhile ~isempty(varargin)\n var = varargin{1};\n if ~isnumeric(var)\n error('option should be numeric');\n end\n \n % option is either connectivity or resolution\n if isscalar(var)\n conn = var;\n else\n delta = var;\n end\n varargin(1) = [];\nend\n\n% Euler-Poincare Characteristic of each component in image\nchi = imEuler3dEstimate(img, conn);\n\n% total volume of image\nobsVolume = prod(size(img) - 1) * prod(delta);\n\n% compute area density\nchi = chi / obsVolume;\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imMinkowski/imEuler3dDensity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6898267537914996}} {"text": "% function w = phase_cwt(Wx, dWx, opt)\n%\n% Calculate the phase transform at each (scale,time) pair:\n% w(a,b) = Im( (1/2pi) * d/db [ Wx(a,b) ] / Wx(a,b) )\n% Uses direct differentiation by calculating dWx/db in frequency\n% domain (the secondary output of cwt_fw, see help cwt_fw)\n%\n% This is the analytic implementation of Eq. (7) of [1].\n%\n% 1. G. Thakur, E. Brevdo, N.-S. Fu\u010dkar, and H.-T. Wu,\n% \"The Synchrosqueezing algorithm for time-varying spectral analysis: robustness\n% properties and new paleoclimate applications,\" Signal Processing, 93:1079-1094, 2013.\n%\n% % 2. I. Daubechies, J. Lu, H.T. Wu, \"Synchrosqueezed Wavelet Transforms: an\n% empricial mode decomposition-like tool\", Applied and Computational Harmonic Analysis\n% 30(2):243-261, 2011.\n%\n% Input:\n% Wx: wavelet transform of x (see help cwt_fw)\n% dWx: samples of time derivative of wavelet transform of x (see help cwt_fw)\n% opt: options struct,\n% opt.gamma: wavelet threshold (default: sqrt(machine epsilon))\n%\n% Output:\n% w: phase transform, size(w) = size(Wx)\n%\n%---------------------------------------------------------------------------------\n% Synchrosqueezing Toolbox\n% Authors: Eugene Brevdo, Gaurav Thakur\n%---------------------------------------------------------------------------------\nfunction w = phase_cwt(Wx, dWx, opt)\n if nargin<3, opt = struct(); end\n % epsilon, gamma from [1]\n if ~isfield(opt, 'gamma'); opt.gamma = sqrt(eps); end\n\n % Calculate phase transform for each ai, normalize by (2*pi)\n\tif strcmpi(opt.dtype,'phase')\n\t\tu = unwrap(angle(Wx)).';\n\t\tw = [diff(u);u(end,:)-u(1,:)].'/(2*pi);\n\telse\n\t\tw = abs(imag(dWx./Wx/(2*pi)));\n\tend\n w(abs(Wx)= 1, N >= K >= 0\n%\n% Examples:\n%\n% % To use each permutation one at a time, put it in a loop.\n% N = 4; % Length of the set.\n% K = 3; % Number of samples taken for each sampling.\n% H = nextperm(N,K);\n% for ii = 1:((prod(1:N)/(prod(1:(N-K)))))\n% A = H();\n% % Do stuff with A: use it as an index, etc.\n% end\n%\n%\n% % To build all of the permutations, do this (See note below):\n% ROWS = (prod(1:N)/(prod(1:(N-K))));\n% C = ones(ROWS,K);\n% for ii = 1:ROWS\n% C(ii,:) = H();\n% end\n% %Note this is a lot slower than using combinator(N,K,'p')\n%\n% The function handle will cycle through when the final permutation is\n% returned.\n%\n% See also, nchoosek, perms, combinator, npermutek (both on the FEX)\n%\n% Author: Matt Fig\n% Contact: popkenai@yahoo.com\n% Date: 6/9/2009\n% Reference: http://mathworld.wolfram.com/BallPicking.html \n\n% Arg checking.\nif K>N \n error('K must be less than or equal to N.')\nend\n\nif isempty(N) || K == 0\n C = []; \n return\nelseif numel(N)~=1 || N<=0 || ~isreal(N) || floor(N) ~= N \n error('N should be one real, positive integer. See help.')\nelseif numel(K)~=1 || K<0 || ~isreal(K) || floor(K) ~= K\n error('K should be one real non-negative integer. See help.')\nend\n\nCNT = 0; % Initializations for the nested function.\nG = [];\nTMP = [];\nop = 1; % These are the variables which are passed to subfunc.\nblk = 1; % Keeps track of the permutation blocks in the subfunc.\nidx = 1:N/2; % Index vectors for subfunc.\nidx2 = idx;\nWV = 1:K; % Initial WV.\nlim = 0; % Sets the limit for working index.\ninc = K; % Controls which element of WV is being worked on.\ncnt = 1; % Keeps track of which block we are in. See loop below.\nBC = prod(1:N)/(prod(1:(N-K))); % Number of permutations.\nL = prod(1:K); % Size of the blocks.\nCNT = 0; % Counter for blocks.\nFloop = BC - prod(1:K); % Length of blocks.\nA2 = (N-K+1):N; % Seed for the final block.\nB2 = 1:K;\nii = 1;\n\nif K==1\n C = @nestfunc2; % Return argument is a func handle.\nelse\n C = @nestfunc;\nend\n\n function B = nestfunc2 \n % A handle to this function is passed back from the main func if K=1. \n if WV > N\n B = 1;\n WV = 2;\n return\n end\n B = WV(1);\n WV = WV + 1;\n end\n\n function B = nestfunc\n % A handle to this function is passed back from the main func.\n if ii<=Floop\n if CNT == 0\n for jj = 1:inc\n WV(K + jj - inc) = lim + jj;\n end\n % This is the first combination. We will permute it\n % below for the rest of the calls in this block.\n B = WV;\n cnt = cnt + L;\n\n if lim<(N-inc)\n inc = 0; % Reset this guy.\n end\n\n TMP = WV; % This serves as seed for perm index.\n inc = inc+1; % Increment the counter.\n lim = WV(K+1-inc); % Limit for working index.\n CNT = 1;\n G = 1:K; % Seed for nextp subfunc\n op = 1;\n blk = 1;\n idx = 1:N/2;\n idx2 = idx;\n ii = ii + 1; % \"Loop\" index.\n else\n % Permute the seed.\n [G,op,blk,idx,idx2] = nextp(G,op,blk,idx,idx2,K);\n B = TMP(G); % Index into current combination.\n CNT = CNT + 1;\n\n if CNT==(L) % Goes back to if for next seed (combin).\n CNT = 0;\n end\n \n ii = ii + 1;\n end\n else\n if ii == Floop+1 % We are at the last block\n op = 1; % Re-initialize for subfunc.\n blk = 1;\n idx = 1:N/2;\n idx2 = idx;\n B = A2; % Seed for this last block.\n cnt = cnt + 1;\n ii = ii + 1;\n return\n elseif ii == BC + 1 % Time to start over.\n WV = 1:K; % Seed for first block.\n op = 1; % Re-initialize for subfunc.\n blk = 1;\n idx = 1:N/2;\n idx2 = idx;\n inc = 1; % Reset the incrementer. \n lim = WV(K+1-inc); % And the lim.\n cnt = L + 1; % Reset block counter.\n CNT = 1;\n ii = 2; % Reset \"Loop\" index.\n B = WV;\n TMP = WV;\n B2 = 1:K;\n G = 1:K;\n return\n end\n % Permute seed the seed.\n [B2,op,blk,idx,idx2] = nextp(B2,op,blk,idx,idx2,K);\n B = A2(B2);\n cnt = cnt + 1;\n ii = ii + 1;\n end \n end\nend\n\n\n\n\n\nfunction [x,op,blk,idx,idx2] = nextp(x,op,blk,idx,idx2,K) \n% Delivers one permutation at a time. This is a modification of an\n% algorithm attributed to H. F. Trotter.\n% x = 1:4; \n% op = 1; \n% blk = 1; \n% idx = 1:length(x)/2; \n% idx2 = idx; \n% C(1,:) = x;\n% for jj = 2:factorial(length(x))\n% [x,op,blk,idx,idx2] = nextp(x,op,blk,idx,idx2,length(x));\n% C(jj,:) = x;\n% end\n\nif op0)\n% e = eccentricity [-] (e>=0)\n% i = inclinaion [rad]\n% o = raan [rad]\n% w = argument of perifocus [rad]\n% t0(k) = time of periapsis [T]\n% t(j) = time [T]\n% mi = gravitational parameter [L^3*T^-2] (mi>0)\n% X(j,:,k) = position [L]\n\nfunction X = t2x(orbits,t0,t,mi)\n\n if ~(nargin == 4)\n error('Wrong number of input arguments.')\n end\n \n [K,D] = check(orbits,2);\n check(t0,1)\n J = check(t,1);\n check(mi,0)\n \n if D < 3\n error('Wrong size of input arguments.')\n end\n \n p = orbits(:,1);\n e = orbits(:,2);\n c = sqrt(mi./p.^3);\n f = t2f(t0,c,e,t);\n \n d3 = (D==5);\n X = zeros(J,2+d3,K);\n for k = 1:K\n X(:,:,k) = f2x(orbits(k,:),f(:,k));\n end\n\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/27308-astrotik-1-0/orbits/t2x.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6897480920871979}} {"text": "function [ x, error_norm, iter, flag ] = gmres ( A, x, b, ...\n M, restart, max_it, tol, n )\n\n%*****************************************************************************80\n%\n%% GMRES solves a linear system Ax=b using the Generalized Minimal residual.\n%\n% Discussion:\n%\n% The routine uses restarts; it does NOT include preconditioning.\n%\n% Modified:\n%\n% 19 July 2004\n%\n% Reference:\n%\n% Richard Barrett, Michael Berry, Tony Chan, James Demmel,\n% June Donato, Jack Dongarra, Victor Eijkhout, Roidan Pozo,\n% Charles Romine, Henk van der Vorst\n% Templates for the Solution of Linear Systems: Building Blocks for \n% Iterative Methods, \n% SIAM Publications, 1993.\n%\n% Parameters:\n%\n% Input, real A(N,N), the nonsymmetric positive definite matrix.\n%\n% Input, real X(N), the initial guess vector.\n%\n% Input, real B(N), the right hand side vector.\n%\n% Input, real M, not used.\n%\n% Input, integer RESTART, the number of iterations between restarts.\n%\n% Input, integer MAX_IT, the maximum number of iterations.\n%\n% Input, real TOL, an error tolerance.\n%\n% Input, integer N, the order of the matrix A.\n%\n% Output, real X(N), the solution.\n%\n% Output, real ERROR_NORM, the norm of the error.\n%\n% Output, integer ITER, the number of iterations performed.\n%\n% Output, integer FLAG, the return flag.\n% 0 = the solution was found to within the specified tolerance.\n% 1 = a satisfactory solution was not found. The iteration limit\n% was exceeded.\n%\n iter = 0;\n flag = 0;\n bnrm2 = norm ( b );\n\n if ( bnrm2 == 0.0 )\n bnrm2 = 1.0\n end\n\n r = ( b - A * x );\n error_norm = norm ( r ) / bnrm2;\n errorhist = [ ];\n errorhist(1) = error_norm;\n\n if ( error_norm < tol ) \n return\n end\n\n m = restart;\n V = sparse(n,m+1);\n H = sparse(m+1,m);\n cs(1:m) = zeros(m,1);\n sn(1:m) = zeros(m,1);\n e1 = zeros(n,1);\n e1(1) = 1.0;\n\n iter2 = 0;\n\n for iter = 1: ceil(max_it / m) ; % changed by L. Foster, this change\n % will correspond to one iteration\n % for every matrix-vector mult.\n%% r = M \\ ( b-A*x ); % changed by L. Foster, done before\n % each loop repetition\n V(:,1) = r / norm( r );\n s = norm ( r ) * e1;\n%\n% Construct an orthonormal basis using Gram-Schmidt orthogonalization.\n%\n for i = 1 : m\n\n w = A * V(:,i);\n\n for k = 1 : i\n H(k,i)= w' * V(:,k);\n w = w - H(k,i) * V(:,k);\n end\n\n H(i+1,i) = norm ( w );\n V(:,i+1) = w / H(i+1,i);\n%\n% Apply the Givens rotation.\n%\n for k = 1 : i-1\n temp = cs(k) * H(k,i) + sn(k) * H(k+1,i);\n H(k+1,i) = -sn(k) * H(k,i) + cs(k) * H(k+1,i);\n H(k,i) = temp;\n end\n%\n% Form the I-th rotation matrix.\n%\n aa = H(i,i);\n bb = H(i+1,i);\n\n if ( bb == 0.0 )\n cs(i) = 1.0;\n sn(i) = 0.0;\n elseif ( abs ( aa ) < abs ( bb ) )\n temp = aa / bb;\n sn(i) = 1.0 / sqrt( 1.0 + temp^2 );\n cs(i) = temp * sn(i);\n else\n temp = bb / aa;\n cs(i) = 1.0 / sqrt( 1.0 + temp^2 );\n sn(i) = temp * cs(i);\n end\n%\n% Approximate the residual norm.\n% \n temp = cs(i) * s(i);\n s(i+1) = -sn(i) * s(i);\n s(i) = temp;\n H(i,i) = cs(i) * H(i,i) + sn(i) * H(i+1,i);\n H(i+1,i) = 0.0;\n error_norm = abs ( s(i+1) ) / bnrm2;\n iter2 = iter2 + 1;\n errorhist(iter2+1) = error_norm;\n%\n% Update the approximate solution.\n%\n if ( error_norm <= tol | max_it <= iter2 )\n y = H(1:i,1:i) \\ s(1:i);\n x = x + V(:,1:i) * y;\n break;\n end\n\n end\n\n if ( error_norm <= tol | max_it <= iter2 )\n break;\n end\n\n y = H(1:m,1:m) \\ s(1:m);\n%\n% Update the approximation.\n%\n x = x + V(:,1:m) * y;\n%\n% Compute the residual.\n%\n r = ( b-A*x );\n \n s(i+1) = norm ( r );\n error_norm = s(i+1) / bnrm2;\n iter2 = iter2 + 1;\n errorhist(iter2+1) = error_norm;\n\n if ( error_norm <= tol | max_it <= iter2 )\n break;\n end\n\n end\n\n if ( tol < error_norm ) \n flag = 1;\n end;\n\n error_norm = errorhist;\n iter = iter2;\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/templates/gmres.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6896504556699039}} {"text": "clc; clear all; close all;\n\n% prepare the input mesh\n[V,F] = readOBJ('../data/spot.obj');\n[V,F,S] = loop(V,F);\n\n% specify handles and handle displacement\nhandles = [1837; 2274; 1144; 1454]; \nhandles_disp = [0.2,0,0;0.2,0,0;0.2,0,0;-0.8,0,0]; \n\n% solve for deformation\nA = cotmatrix(V,F);\nB = zeros(size(V,1),3);\ntic;\npreF = [];\n[d1, preF] = ...\n min_quad_with_fixed(...\n A,B,handles,handles_disp,[],[],preF);\ntoc;\n\nfigure(1)\nsubplot(1,2,1)\ntsurf(F,V)\nhold on\nsct(V(handles,:),'filled', 'r')\nqvr(V(handles,:), handles_disp, 'b')\naxis equal\ntitle('initial')\nsubplot(1,2,2)\ntsurf(F,V+d1)\naxis equal\ntitle('deformation')\n\n% solve for new deformation\nhandles_disp_new = [0.2,0.2,0;0.2,0.2,0;0.2,-0.2,0;-1,0.3,0];\n\ntic;\n[d2, preF] = ...\n min_quad_with_fixed(...\n A,B,handles,handles_disp_new,[],[],preF);\ntoc;\n\nfigure(2)\nsubplot(1,2,1)\ntsurf(F,V)\nhold on\nsct(V(handles,:),'filled', 'r')\nqvr(V(handles,:), handles_disp_new, 'g')\naxis equal\ntitle('initial')\nsubplot(1,2,2)\ntsurf(F,V+d2)\naxis equal\ntitle('deformation')\n\n", "meta": {"author": "odedstein", "repo": "sgi-introduction-course", "sha": "52278fc3b3dab52febb110a1a09d770f46b5e417", "save_path": "github-repos/MATLAB/odedstein-sgi-introduction-course", "path": "github-repos/MATLAB/odedstein-sgi-introduction-course/sgi-introduction-course-52278fc3b3dab52febb110a1a09d770f46b5e417/102_min_quad_with_fixed/exercise/demo_min_quad_with_fixed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6896423382727891}} {"text": "%% Hit-or-Miss Morphological Operation\n%\n% In this tutorial you will learn how to find a given configuration or pattern\n% in a binary image by using the Hit-or-Miss transform (also known as\n% Hit-and-Miss transform).\n%\n% This transform is also the basis of more advanced morphological operations\n% such as thinning or pruning.\n%\n% We will use the OpenCV function |cv.morphologyEx|.\n%\n% Sources:\n%\n% * \n% * \n%\n\n%% Theory\n%\n% Morphological operators process images based on their shape. These operators\n% apply one or more _structuring elements_ to an input image to obtain the\n% output image. The two basic morphological operations are the _erosion_ and\n% the _dilation_. The combination of these two operations generate advanced\n% morphological transformations such as _opening_, _closing_, or _top-hat_\n% transform. To know more about these and other basic morphological operations\n% refer to previous demos.\n%\n% The Hit-or-Miss transformation is useful to find patterns in binary images.\n% In particular, it finds those pixels whose neighbourhood matches the shape\n% of a first structuring element $B_1$ while not matching the shape of a\n% second structuring element $B_2$ at the same time. Mathematically, the\n% operation applied to an image $A$ can be expressed as follows:\n%\n% $$A \\otimes B = (A \\ominus B_1) \\cap (A^c \\ominus B_2)$$\n%\n% Therefore, the hit-or-miss operation comprises three steps:\n%\n% *# Erode image $A$ with structuring element $B_1$.\n% *# Erode the complement of image $A$ ($A^c$) with structuring element $B_2$.\n% *# AND results from step 1 and step 2.\n%\n% The structuring elements $B_1$ and $B_2$ can be combined into a single\n% element $B$. Let's see an example:\n%\n% <>\n%\n% *Structuring elements (kernels). Left: kernel to 'hit'. Middle: kernel to\n% 'miss'. Right: final combined kernel*\n%\n% In this case, we are looking for a pattern in which the central pixel\n% belongs to the background while the north, south, east, and west pixels\n% belong to the foreground. The rest of pixels in the neighbourhood can be of\n% any kind, we don't care about them. Now, let's apply this kernel to an input\n% image:\n%\n% <>\n%\n% You can see that the pattern is found in just one location within the image.\n%\n% <>\n%\n%% Other examples\n%\n% Here you can find the output results of applying different kernels to the\n% same input image used before:\n%\n% * Kernel and output result for finding top-right corners\n%\n% <>\n%\n% * Kernel and output result for finding left end points\n%\n% <>\n%\n% Now try your own patterns!\n%\n\n%% Code\n\nfunction hitmiss_demo()\n %%\n % input image\n img = 255 * uint8([\n 0 0 0 0 0 0 0 0; ...\n 0 1 1 1 0 0 0 1; ...\n 0 1 1 1 0 0 0 0; ...\n 0 1 1 1 0 1 0 0; ...\n 0 0 1 0 0 0 0 0; ...\n 0 0 1 0 0 1 1 0; ...\n 0 1 0 1 0 0 1 0; ...\n 0 1 1 0 0 0 0 0\n ]);\n figure, show_image(img), title('Original')\n\n %%\n % structuring element\n kernel = int32([0 1 0; 1 -1 1; 0 1 0]);\n figure, show_image(kernel), colorbar, title('Kernel')\n\n %%\n % hit-or-mess operation\n out = cv.morphologyEx(img, 'HitMiss', 'Element',kernel);\n figure, show_image(out), title('Hit or Miss')\nend\n\n%%\nfunction show_image(img)\n % pad because PCOLOR chops off last row and column\n img = cv.copyMakeBorder(img, [0 1 0 1], 'BorderType','Constant');\n if mexopencv.isOctave()\n img = double(img);\n end\n h = pcolor(img);\n set(h, 'EdgeColor','b');\n set(gca, 'XAxisLocation','top')\n axis image ij, colormap(gray(3))\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/samples/hitmiss_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.689639771680816}} {"text": "function p = predict(theta, X)\n%PREDICT Predict whether the label is 0 or 1 using learned logistic\n%regression parameters theta\n% p = PREDICT(theta, X) computes the predictions for X using a\n% threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)\n\nm = size(X, 1); % Number of training examples\n\n% You need to return the following variables correctly\np = zeros(m, 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters.\n% You should set p to a vector of 0's and 1's\n%\n\np = sigmoid(X * theta)\n\nfor i = 1:size(p)\n if (p(i) >= 0.5)\n p(i) = 1;\n else\n p(i) = 0;\n endif\nend\n\n\n\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-ex2/ex2/predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.845942452844325, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.6896397659845628}} {"text": "function b = r8ge_mxv ( m, n, a, x )\n\n%*****************************************************************************80\n%\n%% R8GE_MXV multiplies a R8GE matrix times a vector.\n%\n% Discussion:\n%\n% The R8GE storage format is used for a general M by N matrix. A storage \n% space is made for each logical entry. The two dimensional logical\n% array is mapped to a vector, in which storage is by columns.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 March 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of rows of the matrix.\n% M must be positive.\n%\n% Input, integer N, the number of columns of the matrix.\n% N must be positive.\n%\n% Input, real A(M,N), the R8GE matrix.\n%\n% Input, real X(N), the vector to be multiplied by A.\n%\n% Output, real B(M), the product A * x.\n%\n b(1:m) = a(1:m,1:n) * 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/linplus/r8ge_mxv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6896240259567622}} {"text": "%% The MAP algorithm\n%---input---------------------------------------------------------\n% X: initial 2D labels\n% Y: image\n% Z: 2D constraints\n% mu: vector of means\n% sigma: vector of standard deviations\n% k: number of labels\n% MAP_iter: maximum number of iterations of the MAP algorithm\n% show_plot: 1 for showing a plot of energy in each iteration\n% and 0 for not showing\n%---output--------------------------------------------------------\n% X: final 2D labels\n% sum_U: final energy\n\n% Copyright by Quan Wang, 2012/04/25\n% Please cite: Quan Wang. HMRF-EM-image: Implementation of the \n% Hidden Markov Random Field Model and its Expectation-Maximization \n% Algorithm. arXiv:1207.3510 [cs.CV], 2012.\n\nfunction [X sum_U]=MRF_MAP(X,Y,Z,mu,sigma,k,MAP_iter,show_plot)\n\n[m n]=size(Y);\nx=X(:);\ny=Y(:);\nU=zeros(m*n,k);\nsum_U_MAP=zeros(1,MAP_iter);\nfor it=1:MAP_iter % iterations\n fprintf(' Inner iteration: %d\\n',it);\n U1=U;\n U2=U;\n \n for l=1:k % all labels\n yi=y-mu(l);\n temp1=yi.*yi/sigma(l)^2/2;\n temp1=temp1+log(sigma(l));\n U1(:,l)=U1(:,l)+temp1;\n \n \n for ind=1:m*n % all pixels\n [i j]=ind2ij(ind,m);\n u2=0;\n if i-1>=1 && Z(i-1,j)==0\n u2=u2+(l ~= X(i-1,j))/2;\n end\n if i+1<=m && Z(i+1,j)==0\n u2=u2+(l ~= X(i+1,j))/2;\n end\n if j-1>=1 && Z(i,j-1)==0\n u2=u2+(l ~= X(i,j-1))/2;\n end\n if j+1<=n && Z(i,j+1)==0\n u2=u2+(l ~= X(i,j+1))/2;\n end\n U2(ind,l)=u2;\n end\n end\n U=U1+U2;\n [temp x]=min(U,[],2);\n sum_U_MAP(it)=sum(temp(:));\n \n X=reshape(x,[m n]);\n if it>=3 && std(sum_U_MAP(it-2:it))/sum_U_MAP(it)<0.0001\n break;\n end\nend\n\nsum_U=0;\nfor ind=1:m*n % all pixels\n sum_U=sum_U+U(ind,x(ind));\nend\nif show_plot==1\n figure;\n plot(1:it,sum_U_MAP(1:it),'r');\n title('sum U MAP');\n xlabel('MAP iteration');\n ylabel('sum U MAP');\n drawnow;\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/37530-hmrf-em-image/HMRF-EM-image_v2.0/code/MRF_MAP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6896240166838986}} {"text": "% funJn calculates and returns the In integral (eq (15) in [1])\n% Jn=funJn(Tn,betaConst,n,numbMC)\n% Jn is the J_{n,\\beta} integral (scalar) value\n% T_n is the n-based SINR threshold value (eq (17) in [1])\n% betaConstant is path-loss exponent\n% n is integer parameter\n% betaConst, n, and numbMC are scalars. T_n can be a vector\n% numbMc is number of sample (Sobol) points for quasi-MC integration\n%\n% Author: H.P. Keeler, Inria Paris/ENS, 2013\n%\n% References\n% [1] H.P. Keeler, B. B\u0142aszczyszyn and M. Karray,\n% 'SINR-based k-coverage probability in cellular networks with arbitrary\n% shadowing', accepted at ISIT, 2013 \n\n\nfunction Jn=funJn(Tn,betaConst,n,numbMC)\n% Calculates Jn with various integration methods\n% n =2 and 3 uses quad and dblquad respectively\n% n>3 uses quasi Monte Carlo based on Sobol points\n% function is called by funProbCov; see Corollary 7 in [1]\nif nargin==3\n numbMC=10^3; %set default number of qMC sample points\nend\nif n<=3\n numbMC=0; %monte carlo not used\nend\n\nJn=zeros(size(Tn));\nfor k=1:length(Tn)\n %%% Use quadrature methods for n=2 and n=3 cases\n if n==3\n fv=@(v1,v2)(1./((v1.*v2)+Tn(k))).*(1./((v1.*(1-v2))+Tn(k))).*(v1.*v2.*(1-v2).*(1-v1)).^(2/betaConst).*v1.^(2/betaConst+1);\n Jn(k)=dblquad(fv,0,1,0,1); %perform double qudarature\n elseif n==2\n \n fv=@(v1)(v1.*(1-v1)).^(2/betaConst)./(v1+Tn(k));\n Jn(k)=quad(fv,0,1); %perform single qudarature\n \n elseif n==1\n Jn=ones(size(Tn)); %return ones since J_1=1;\n else\n %%% Use QMC method\n numbMCn=(n-1)*numbMC; %scale number of points by dimension\n cubeVol=1; %hyper-cube volume\n eta_i=cell(1,n);\n %Use sobol points (can also use 'halton')\n q = qrandstream('halton',n-1,'Skip',1e3,'Leap',1e2);\n qRandAll=qrand(q,numbMCn);\n \n %create eta_i values\n eta_i{1}=prod((qRandAll(:,1:end)),2);\n for i=2:n-1\n eta_i{i}=(1-qRandAll(:,i-1)).*prod((qRandAll(:,i:end)),2);\n end\n eta_i{n}=(1-qRandAll(:,n-1));\n \n %create/sample nominator and denominator of integral kernel\n numProdv_i=ones(numbMCn,1);\n denomProdv_i=ones(numbMCn,1);\n for i=1:n-1\n viRand=qRandAll(:,i);\n numProdv_i=(viRand).^(i*(2/betaConst+1)-1).*(1-viRand).^(2/betaConst).*numProdv_i; %numerator\n denomProdv_i=(eta_i{i}+Tn(k)).*denomProdv_i; %denominator term\n end\n denomProdv_i=(eta_i{n}+Tn(k)).*denomProdv_i;\n \n %factor out one term, arbitrarily choose the j-th term\n j=n-1;\n denomProdv_i=(eta_i{j}+Tn(k))./denomProdv_i;\n \n kernelInt=numProdv_i.*denomProdv_i; %integral kernerl\n Jn(k)=mean(kernelInt)*cubeVol; % perform (q)MC step\n \n end\n \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/40087-sinr-based-k-coverage-probability-in-cellular-networks/To be uploaded/funJn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6896240099074813}} {"text": "%Implements an example MAP decoder, hard-input soft-output. Uses a\n%brute-force algorithm, which is useful for demonstration/learning\n%purposes. \n%\n% Copyright Colin O'Flynn, 2011. All rights reserved.\n% http://www.newae.com\n%\n% Redistribution and use in source and binary forms, with or without modification, are\n% permitted provided that the following conditions are met:\n% \n% 1. Redistributions of source code must retain the above copyright notice, this list of\n% conditions and the following disclaimer.\n% \n% 2. Redistributions in binary form must reproduce the above copyright notice, this list\n% of conditions and the following disclaimer in the documentation and/or other materials\n% provided with the distribution.\n% \n% THIS SOFTWARE IS PROVIDED BY COLIN O'FLYNN ''AS IS'' AND ANY EXPRESS OR IMPLIED\n% WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n% FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COLIN O'FLYNN OR\n% CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n% SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n% ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction [llrs, codeword] = brute_force_map(feedback, feedforward, input, pberr, nbits)\n \n if nbits > 16\n error('nbits too high')\n end\n \n %Generate every possible information sequence\n D = [0:2^nbits - 1];\n B = dec2bin(D);\n \n allValidInputs = zeros(2^nbits, nbits);\n \n %Convert from string to matrix\n for i=1:nbits\n allValidInputs(:,i) = str2num(B(:,i));\n end\n\n len = (nbits+3)*2;\n all_codewords = zeros(2^nbits, len);\n \n %Generate every possible codeword\n for i=1:2^nbits\n codeword = rsc_encode([feedback; feedforward], allValidInputs(i,:), 1); \n all_codewords(i,:) = reshape(codeword, 1, len);\n end \n \n pcodeword = zeros(2^nbits, 1);\n \n %For every possible codeword & ours: find out Pcodeword\n for i=1:2^nbits\n bitsInDiff = sum(abs(input - all_codewords(i,:)));\n bitsOK = len - bitsInDiff; \n %Find APP Pr{X | Y}\n % X = Codeword that was transmitted\n % Y = Codeword that was receieved\n pcodeword(i) = pberr^bitsInDiff * (1-pberr)^bitsOK;\n end\n \n %Limited valid Tx codewords, so normalize probability to add up to 1.0\n pcodeword = pcodeword ./ (sum(pcodeword));\n\n %Find resulting maximum likilhood codeword\n [Pmax, Imax] = max(pcodeword);\n \n %The suggested codeword\n codeword = all_codewords(Imax, :);\n \n %Reshape to make division between systematic & parity obvious\n %Now looks like: [systematic ; parity]\n codeword = reshape(codeword, 2, len/2);\n\n %Calculate individual probability of error\n p0Systematic = zeros(1, nbits);\n for bitindex=1:nbits\n psum = 0;\n \n %Sum over all codewords\n for i=1:2^nbits \n %Reshape codeword to easily get systematic part out\n codewords_reshaped = reshape(all_codewords(i,:), 2, len/2);\n \n %If codeword has bit n as zero, count it in summation\n if codewords_reshaped(1, bitindex) == 0\n psum = psum + pcodeword(i);\n end\n end \n \n %Save total probability of ALL codewords with bit 'n' is zero\n p0Systematic(bitindex) = psum; \n end\n \n %Find probability any given bit is ONE\n p1Systematic = 1.0 - p0Systematic; \n \n %From P1 & P0 calculate LLR\n llrs = log(p1Systematic ./ p0Systematic);", "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/34878-example-turbo-coding-with-free-distance-exit-code-and-presentation/doc/resources/brute_force_map.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6896240005752072}} {"text": "function b = r8bto_vxm ( m, l, a, x )\n\n%*****************************************************************************80\n%\n%% R8BTO_VXM multiplies a vector by a R8BTO matrix.\n%\n% Discussion:\n%\n% The R8BTO storage format is for a block Toeplitz matrix. The matrix\n% can be regarded as an L by L array of blocks, each of size M by M.\n% The full matrix has order N = M * L. The L by L matrix is Toeplitz,\n% that is, along its diagonal, the blocks repeat.\n%\n% Storage for the matrix consists of the L blocks of the first row,\n% followed by the L-1 blocks of the first column (skipping the first row).\n% These items are stored in the natural way in an (M,M,2*L-1) array.\n%\n% Example:\n%\n% M = 2, L = 3\n%\n% 1 2 | 3 4 | 5 6\n% 5 5 | 6 6 | 7 7\n% ----+-----+-----\n% 7 8 | 1 2 | 3 4\n% 8 8 | 5 5 | 6 6\n% ----+-----+-----\n% 9 0 | 7 8 | 1 2\n% 9 9 | 8 8 | 5 5\n%\n% X = (/ 1, 2, 3, 4, 5, 6 /)\n%\n% B = (/ 163, 122, 121, 130, 87, 96 /)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the order of the blocks of the matrix A.\n%\n% Input, integer L, the number of blocks in a row or column of A.\n%\n% Input, real A(M,M,2*L-1), the R8BTO matrix.\n%\n% Input, real X(M*L), the vector to be multiplied.\n%\n% Output, real B(M*L), the product X * A.\n%\n\n%\n% Construct the right hand side by blocks.\n%\n for i = 1 : l\n\n b(1:m,i) = 0.0;\n\n for j = 1 : i\n b(1:m,i) = b(1:m,i) + a(1:m,1:m,i+1-j)' * x(1:m,j);\n end\n\n for j = i+1 : l\n b(1:m,i) = b(1:m,i) + a(1:m,1:m,l+j-i)' * x(1:m,j);\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/linplus/r8bto_vxm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6896239983164016}} {"text": "function b = tmat_rot_vector ( a, angle, axis )\n\n%*****************************************************************************80\n%\n%% TMAT_ROT_VECTOR applies an arbitrary axis rotation to the geometric transformation matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Foley, van Dam, Feiner, Hughes,\n% Computer Graphics, Principles and Practice,\n% Addison Wesley, Second Edition, 1990.\n%\n% Parameters:\n%\n% Input, real A(4,4), the current geometric transformation\n% matrix.\n%\n% Input, real ANGLE, the angle, in degrees, of the rotation.\n%\n% Input, real AXIS(3), the axis vector about which \n% rotation occurs. AXIS may not be the zero vector.\n%\n% Output, real B(4,4), the modified geometric \n% transformation matrix.\n%\n dim_num = 3;\n \n norm = sqrt ( sum ( axis(1:dim_num).^2 ) );\n\n if ( norm == 0.0 )\n return\n end\n\n axis(1:dim_num) = axis(1:dim_num) / norm;\n\n angle_rad = degrees_to_radians ( angle );\n ca = cos ( angle_rad );\n sa = sin ( angle_rad );\n\n c = tmat_init ( );\n\n c(1,1) = axis(1) * axis(1) + ca * ( 1.0 - axis(1) * axis(1) );\n c(1,2) = ( 1.0 - ca ) * axis(1) * axis(2) - sa * axis(3);\n c(1,3) = ( 1.0 - ca ) * axis(1) * axis(3) + sa * axis(2);\n\n c(2,1) = ( 1.0 - ca ) * axis(2) * axis(1) + sa * axis(3);\n c(2,2) = axis(2) * axis(2) + ca * ( 1.0 - axis(2) * axis(2) );\n c(2,3) = ( 1.0 - ca ) * axis(2) * axis(3) - sa * axis(1);\n\n c(3,1) = ( 1.0 - ca ) * axis(3) * axis(1) - sa * axis(2);\n c(3,2) = ( 1.0 - ca ) * axis(3) * axis(2) + sa * axis(1);\n c(3,3) = axis(3) * axis(3) + ca * ( 1.0 - axis(3) * axis(3) );\n\n b(1:4,1:4) = c(1:4,1:4) * a(1:4,1:4);\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/tmat_rot_vector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.6896170493055278}} {"text": "function [ n_data, a, b, fx ] = arithmetic_geometric_mean_values ( n_data )\n\n%*****************************************************************************80\n%\n%% AGM_VALUES returns some values of the AGM.\n%\n% Discussion:\n%\n% The AGM is defined for nonnegative A and B.\n%\n% The AGM of numbers A and B is defined by setting\n%\n% A(0) = A,\n% B(0) = B\n%\n% A(N+1) = ( A(N) + B(N) ) / 2\n% B(N+1) = sqrt ( A(N) * B(N) )\n%\n% The two sequences both converge to AGM(A,B).\n%\n% In Mathematica, the AGM can be evaluated by\n%\n% ArithmeticGeometricMean [ a, b ]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 February 2008\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, 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_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, real A, B, the argument ofs the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 14;\n\n a_vec = [ ...\n 22.0, ...\n 83.0, ...\n 42.0, ...\n 26.0, ...\n 4.0, ...\n 6.0, ...\n 40.0, ...\n 80.0, ...\n 90.0, ...\n 9.0, ...\n 53.0, ...\n 1.0, ...\n 1.0, ...\n 1.0, ...\n 1.5 ];\n b_vec = [ ...\n 96.0, ...\n 56.0, ...\n 7.0, ...\n 11.0, ...\n 63.0, ...\n 45.0, ...\n 75.0, ...\n 0.0, ...\n 35.0, ...\n 1.0, ...\n 53.0, ...\n 2.0, ...\n 4.0, ...\n 8.0, ...\n 8.0 ];\n fx_vec = [ ...\n 52.274641198704240049, ...\n 68.836530059858524345, ...\n 20.659301196734009322, ...\n 17.696854873743648823, ...\n 23.867049721753300163, ...\n 20.717015982805991662, ...\n 56.127842255616681863, ...\n 0.000000000000000000, ...\n 59.269565081229636528, ...\n 3.9362355036495554780, ...\n 53.000000000000000000, ...\n 1.4567910310469068692, ...\n 2.2430285802876025701, ...\n 3.6157561775973627487, ...\n 4.0816924080221632670 ];\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 a = 0.0;\n b = 0.0;\n fx = 0.0;\n else\n a = a_vec(n_data);\n b = b_vec(n_data);\n fx = fx_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/polpak/agm_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7905303211371899, "lm_q1q2_score": 0.6896170450004673}} {"text": "function coordl1bregdemo\n%COORDL1BREGDEMO An example of using COORDL1BREG. \n\n% Construct A as a rand matrix.\nN = 512*2;\nM = N/2;\nA = randn(M,N);\n\n% Construct u_exact as a sparse vector. \np = floor(0.05*N);\nu_exact = zeros(N,1);\n% u_exact has spikes at uniformly random locations with amplitudes\n% distributed uniformly in [0,1]\na = randperm(N);\n% u_exact(a(1:p)) = a(p+1:2*p)*0.08+5; % 0.08 + 5\nu_exact(a(1:p)) = rand(p,1)*N; %randn is fast.\n\n% Construct f = A*u_exact.\nf = A*u_exact;\n\n% Precompute B = A'*A. This step is not necessary.\nB = A'*A;\n\n% Initialize lambda. \nlambda = 10;\n\n% Call the main function COORDL1BREG.\n[u,Energy] = coordl1breg(A,f,lambda,'B',B,'PlotFun',@myplotfun);\n\n% Plot the Energy function.\nfigure(2);\nsemilogy(Energy,'.-');\nxlabel('Iteration');\nylabel('Energy');\n\n% COORDL1BREG will call this function every iteration to plot intermediate solutions.\n% Show the comparison of the output u and u_exact.\n function myplotfun(u)\n\n figure(1);\n x = 1:length(u);\n plot(x,u,'.r',x,u_exact,'o');\n xlim([1,length(u)]);\n end\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/25680-coordinate-descent-for-compressed-sensing/coordl1bregdemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220294, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.6896071099393547}} {"text": "% ANISODIFF - Anisotropic diffusion.\n%\n% \n% diff = anisodiff(im, niter, kappa, lambda, option)\n%\n% \n% im - input image\n% niter - number of iterations.\n% kappa - conduction coefficient 20-100 ?\n% lambda - max value of .25 for stability\n% option - 1 Perona Malik diffusion equation No 1\n% 2 Perona Malik diffusion equation No 2\n%\n% Return\n% diff - diffused image.\n%\n% kappa controls conduction as a function of gradient. If kappa is low\n% then mall intensity gradients are able to block conduction and hence diffusion\n% across step edges. A large value reduces the influence of intensity\n% gradients on conduction.\n%\n% lambda controls speed of diffusion (you usually want it at a maximum of\n% 0.25)\n%\n% Diffusion equation 1 preserve high contrast edges over low contrast ones.\n% Diffusion equation 2 favours wide regions over smaller ones.\n\n% Reference: \n% P. Perona and J. Malik. \n% Scale-space and edge detection using anisotropic diffusion.\n% IEEE Transactions on Pattern Analysis and Machine Intelligence, \n% 12(7):629-639, July 1990.\n\n\nfunction diff = anisodiff(im, niter, kappa, lambda, option)\n\nif ndims(im)==3\n error('Anisodiff only operates on 2D grey-scale images');\nend\n\nim = double(im);\n[rows,cols] = size(im);\ndiff = im;\n\n%{\nvar = 2;\nx = (-4:4);\ng = exp(-x.*x/(2*var)); g = g/sum(g);\n\nblurred = conv2(im,g,'same');\nim_b = conv2(blurred,g','same'); \n\n%}\n\nfor i = 1:niter\n % fprintf('\\rIteration %d',i);\n\n % Construct diffl which is the same as diff but\n % has an extra padding of zeros around it.\n diffl = zeros(rows+2, cols+2);\n diffl(2:rows+1, 2:cols+1) = diff;\n\n % North, South, East and West differences\n deltaN = diffl(1:rows,2:cols+1) - diff;\n \n deltaS = diffl(3:rows+2,2:cols+1) - diff;\n \n deltaE = diffl(2:rows+1,3:cols+2) - diff;\n \n deltaW = diffl(2:rows+1,1:cols) - diff;\n %deltaN = diff;deltaW;\n \n\n % Conduction\n\n if option == 1\n cN = exp(-(deltaN/kappa).^2);\n \n cS = exp(-(deltaS/kappa).^2);\n cE = exp(-(deltaE/kappa).^2);\n cW = exp(-(deltaW/kappa).^2);\n \n elseif option == 2\n cN = 1./(1 + (deltaN/kappa).^2);\n cS = 1./(1 + (deltaS/kappa).^2);\n cE = 1./(1 + (deltaE/kappa).^2);\n cW = 1./(1 + (deltaW/kappa).^2);\n end\n\n % APPLYING FOUR-POINT-TEMPLETE FOR numerical solution of DIFFUSION P.D.E.\n \n diff = diff + lambda*(cN.*deltaN + cS.*deltaS + cE.*deltaE + cW.*deltaW);\nfigure();\n% Uncomment the following to see a progression of images\n subplot(ceil(sqrt(niter)),ceil(sqrt(niter)), i)\n figure();\n pause(2)\nimagesc(diff), colormap(gray), axis image\n\nend\nfprintf('\\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/31204-anisodiff-in-matlab/anisodiff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6896071031753701}} {"text": "function hx = happly (v, beta, x)\n%HAPPLY apply Householder reflection to a vector\n% Example:\n% hx = happly (v,beta,x) ; % computes hx = x - v * (beta * (v' *x)) ;\n% See also: testall\n\n% Copyright 2006-2007, Timothy A. Davis.\n% http://www.cise.ufl.edu/research/sparse\n\n\nhx = x - v * (beta * (v' *x)) ;\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/SuiteSparse/CXSparse/MATLAB/Test/happly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.6895443771159389}} {"text": "function X = Inv_SeparateAngles(R,deep,IsImageReal,MaxIts,ErrTol,X0)\n% Inv_SeparateAngles: 'Invert' Separate Angles by the method of\n% Least Squares\n% Usage:\n% X = Inv_SeparateAngles(R,deep,MaxIts,ErrTol);\n% Inputs:\n% R Array of smoothly localized Fourier samples\n% deep Depth of the angular splitting\n% MaxIts Maximum number of CG iterations. Default 10.\n% ErrTol Error tolerance. Default 1.e-9.\n% Outputs:\n% X n by n matrix \n% Description\n% Performs the inverse angular separation. This is an\n% approximate inverse which uses a conjugate gradient solver on\n% the associated Gram system. The system is mildly preconditioned. \n% See Also\n% SeparateAngles, Inv_AtA_CG, \n%\n% By Emmanuel Candes, 2003-2004\n\nif nargin < 5,\n\tErrTol = 1.e-9;\nend\nif nargin < 4,\n\tMaxIts = 10;\nend\nif nargin < 3,\n IsImageReal = 0;\nend\n\nn = size(R,3)*4;\n\nW = SetScaleToZero(n);\n\nP = Adj_SeparateAngles(R,deep,IsImageReal).*W;\nX = Inv_AtA_CG(P,deep,MaxIts,ErrTol,X0);\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/CurveLab-2.1.3/fdct_usfft_matlab/CurveCoeff/Inv_SeparateAngles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103777, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6895224199415825}} {"text": "% Figure 10.08 Feedback Control of Dynamic Systems, 5e\n% Franklin, Powell, Emami\n%\n% fig10_08.m is a script to generate Fig. 10.8 the \n% frequency response of the satellite with low-gain PD compensation\n\nnp =[0.0360 0.9100];\n\ndp =[1.0000 0.0396 1.0010 0.0000 0.0000];\n\nnc2=0.001*[30 1];\n\nnol2=conv(nc2,np);\ndol2=dp;\n\nhold off ; clf\nw=logspace(-2,.2);\nw(46)=1;\n[magol2, phol2]= bode(nol2,dol2,w);\nsubplot(211) ; loglog(w,magol2); grid; hold on;\nxlabel('\\omega (rad/sec)');\nylabel('Magnitude |D_2(s)G(s)|');\nloglog(w,ones(size(magol2)),'g');\ntitle('Fig. 10.8 Frequency response of low-gain satellite PD design')\nphol2a=[phol2, -180*ones(size(phol2))];\nsubplot(212); semilogx(w, phol2a); grid; hold on; \nxlabel('\\omega (rad/sec)');\nylabel('Phase (deg)');\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/9907-feedback-control-of-dynamic-systems-fifth-ed/fig10_08.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.7577943767446201, "lm_q1q2_score": 0.6895224088334576}} {"text": "m = 100;\nn = 1000;\nk = 12;\nA = spx.dict.simple.gaussian_dict(m, n);\ngen = spx.data.synthetic.SparseSignalGenerator(n, k);\n% create a sparse vector\nx = gen.biGaussian();\nb = A*x;\nA = double(A);\nresult = spx.fast.omp(A, b, k, 1e-12);\ncmpare = spx.commons.SparseSignalsComparison(x, result, k);\ncmpare.summarize();\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/pursuit/fast/demo_fast_omp_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6895224075589933}} {"text": "function out = EN_MS_LZcomplexity(y,n,preProc)\n% EN_MS_LZcomplexity Lempel-Ziv complexity of a n-bit encoding of a time series\n%\n%---INPUTS:\n% y, the input time series\n% n, the (integer) number of bits to encode the data into\n% preProc [opt], first apply a given preProcessing to the time series. For now,\n% just 'diff' is implemented, which zscores incremental\n% differences and then applies the complexity method.\n%\n%---OUTPUT: the normalized Lempel-Ziv complexity: i.e., the number of distinct\n% symbol sequences in the time series divided by the expected number\n% of distinct symbols for a noise sequence.\n\n% Uses Michael Small's code: 'complexity' (renamed MS_complexity here).\n%\n% cf. M. Small, Applied Nonlinear Time Series Analysis: Applications in Physics,\n% Physiology, and Finance (book) World Scientific, Nonlinear Science Series A,\n% Vol. 52 (2005)\n% Code is available at http://small.eie.polyu.edu.hk/matlab/\n%\n% The code is a wrapper for Michael Small's original code and uses the\n% associated mex file compiled from complexitybs.c (renamed MS_complexitybs.c\n% here).\n% ------------------------------------------------------------------------------\n% Copyright (C) 2020, Ben D. Fulcher ,\n% \n%\n% If you use this code for your research, please cite the following two papers:\n%\n% (1) B.D. Fulcher and N.S. Jones, \"hctsa: A Computational Framework for Automated\n% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).\n% DOI: 10.1016/j.cels.2017.10.001\n%\n% (2) B.D. Fulcher, M.A. Little, N.S. Jones, \"Highly comparative time-series\n% analysis: the empirical structure of time series and their methods\",\n% J. Roy. Soc. Interface 10(83) 20130048 (2013).\n% DOI: 10.1098/rsif.2013.0048\n%\n% This function is free software: you can redistribute it and/or modify it under\n% the terms of the GNU General Public License as published by the Free Software\n% Foundation, either version 3 of the License, or (at your option) any later\n% version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT\n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n% details.\n%\n% You should have received a copy of the GNU General Public License along with\n% this program. If not, see .\n% ------------------------------------------------------------------------------\n\nif nargin < 2 || isempty(n)\n n = 2; % n-bit encoding\nend\nif nargin < 3\n preProc = []; % no preprocessing\nend\n\n% Apply some pre-processing to the time series before performing the analysis\nif ischar(preProc)\n switch preProc\n case 'diff'\n y = zscore(diff(y));\n otherwise\n error('Unknown preprocessing setting ''%s''', preProc);\n end\nend\n\n% Run Michael Small's (mexed) code for calcaulting the Lempel-Ziv complexity:\nout = MS_complexity(y,n);\n\nend\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Operations/EN_MS_LZcomplexity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6895224050100637}} {"text": "function [B,A] = octdsgn(Fc,Fs,N); \n% OCTDSGN Design of an octave filter.\n% [B,A] = OCTDSGN(Fc,Fs,N) designs a digital octave filter with \n% center frequency Fc for sampling frequency Fs. \n% The filter are designed according to the Order-N specification \n% of the ANSI S1.1-1986 standard. Default value for N is 3. \n% Warning: for meaningful design results, center values used\n% should preferably be in range Fs/200 < Fc < Fs/5.\n% Usage of the filter: Y = FILTER(B,A,X). \n%\n% Requires the Signal Processing Toolbox. \n%\n% See also OCTSPEC, OCT3DSGN, OCT3SPEC.\n\n% Author: Christophe Couvreur, Faculte Polytechnique de Mons (Belgium)\n% couvreur@thor.fpms.ac.be\n% Last modification: Aug. 22, 1997, 9:00pm.\n\n% References: \n% [1] ANSI S1.1-1986 (ASA 65-1986): Specifications for\n% Octave-Band and Fractional-Octave-Band Analog and\n% Digital Filters, 1993.\n\nif (nargin > 3) | (nargin < 2)\n error('Invalide number of arguments.');\nend\nif (nargin == 2)\n N = 3; \nend\nif (Fc > 0.70*(Fs/2))\n error('Design not possible. Check frequencies.');\nend\n\n% Design Butterworth 2Nth-order octave filter \n% Note: BUTTER is based on a bilinear transformation, as suggested in [1]. \n%W1 = Fc/(Fs/2)*sqrt(1/2);\n%W2 = Fc/(Fs/2)*sqrt(2); \npi = 3.14159265358979;\nbeta = pi/2/N/sin(pi/2/N); \nalpha = (1+sqrt(1+8*beta^2))/4/beta;\nW1 = Fc/(Fs/2)*sqrt(1/2)/alpha; \nW2 = Fc/(Fs/2)*sqrt(2)*alpha;\n[B,A] = butter(N,[W1,W2]); \n\n\n\n\n\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/69-octave/octave/octdsgn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.689522393901939}} {"text": "function f = p02_fun ( option, n, x )\n\n%*****************************************************************************80\n%\n%% P02_FUN evaluates the integrand for problem 2.\n%\n% Discussion:\n%\n% The exact value is sqrt(pi).\n%\n% Integral ( -oo < x < +oo ) exp(-x*x) dx\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 May 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer OPTION:\n% 0, integrand is f(x).\n% 1, integrand is exp(-x*x) * f(x);\n% 2, integrand is exp(-x*x/2) * f(x);\n%\n% Input, integer N, the number of points.\n%\n% Input, real X(N), the evaluation points.\n%\n% Output, real F(N), the function values.\n%\n x = x ( : );\n f = zeros ( n, 1 );\n\n f(1:n) = 1;\n\n if ( option == 0 )\n f(1:n) = f(1:n) .* exp ( - x(1:n).^2 );\n elseif ( option == 1 )\n\n elseif ( option == 2 )\n f(1:n) = f(1:n) .* exp ( - 0.5 * x(1: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/p02_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.689501244888525}} {"text": "function [varargout] = wavefilter(wname, type)\n%WAVEFILTER Create wavelet decomposition and reconstruction filters.\n% [VARARGOUT] = WAVEFILTER(WNAME, TYPE) returns the decomposition\n% and/or reconstruction filters used in the computation of the\n% forward and inverse FWT (fast wavelet transform). \n%\n% EXAMPLES:\n% [ld, hd, lr, hr] = wavefilter('haar') Get the low and highpass \n% decomposition (ld, hd) \n% and reconstruction \n% (lr, hr) filters for \n% wavelet 'haar'.\n% [ld, hd] = wavefilter('haar','d') Get decomposition filters\n% ld and hd.\n% [lr, hr] = wavefilter('haar','r') Get reconstruction \n% filters lr and hr.\n%\n% INPUTS:\n% WNAME Wavelet Name\n% ---------------------------------------------------------\n% 'haar' or 'db1' Haar\n% 'db4' 4th order Daubechies\n% 'sym4' 4th order Symlets\n% 'bior6.8' Cohen-Daubechies-Feauveau biorthogonal\n% 'jpeg9.7' Antonini-Barlaud-Mathieu-Daubechies\n%\n% TYPE Filter Type\n% ---------------------------------------------------------\n% 'd' Decomposition filters\n% 'r' Reconstruction filters\n%\n% See also WAVEFAST and WAVEBACK.\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\n% Check the input and output arguments.\nif (nargin == 1 && nargout ~= 4) || (nargin == 2 && nargout ~= 2)\n error('Invalid number of output arguments.'); \nend\n\nif nargin == 1 && ~ischar(wname)\n error('WNAME must be a string.'); \nend\n\nif nargin == 2 && ~ischar(type)\n error('TYPE must be a string.'); \nend\n \n% Create filters for the requested wavelet.\nswitch lower(wname)\ncase {'haar', 'db1'}\n ld = [1 1]/sqrt(2); hd = [-1 1]/sqrt(2);\n lr = ld; hr = -hd;\n \ncase 'db4'\n ld = [-1.059740178499728e-002 3.288301166698295e-002 ...\n 3.084138183598697e-002 -1.870348117188811e-001 ...\n -2.798376941698385e-002 6.308807679295904e-001 ...\n 7.148465705525415e-001 2.303778133088552e-001];\n t = (0:7);\n hd = ld; hd(end:-1:1) = cos(pi * t) .* ld;\n lr = ld; lr(end:-1:1) = ld;\n hr = cos(pi * t) .* ld;\n \ncase 'sym4'\n ld = [-7.576571478927333e-002 -2.963552764599851e-002 ...\n 4.976186676320155e-001 8.037387518059161e-001 ...\n 2.978577956052774e-001 -9.921954357684722e-002 ...\n -1.260396726203783e-002 3.222310060404270e-002];\n t = (0:7);\n hd = ld; hd(end:-1:1) = cos(pi * t) .* ld;\n lr = ld; lr(end:-1:1) = ld;\n hr = cos(pi * t) .* ld;\n \ncase 'bior6.8'\n ld = [0 1.908831736481291e-003 -1.914286129088767e-003 ...\n -1.699063986760234e-002 1.193456527972926e-002 ...\n 4.973290349094079e-002 -7.726317316720414e-002 ...\n -9.405920349573646e-002 4.207962846098268e-001 ...\n 8.259229974584023e-001 4.207962846098268e-001 ...\n -9.405920349573646e-002 -7.726317316720414e-002 ...\n 4.973290349094079e-002 1.193456527972926e-002 ...\n -1.699063986760234e-002 -1.914286129088767e-003 ...\n 1.908831736481291e-003];\n hd = [0 0 0 1.442628250562444e-002 -1.446750489679015e-002 ...\n -7.872200106262882e-002 4.036797903033992e-002 ...\n 4.178491091502746e-001 -7.589077294536542e-001 ...\n 4.178491091502746e-001 4.036797903033992e-002 ...\n -7.872200106262882e-002 -1.446750489679015e-002 ...\n 1.442628250562444e-002 0 0 0 0];\n t = (0:17);\n lr = cos(pi * (t + 1)) .* hd;\n hr = cos(pi * t) .* ld;\n \ncase 'jpeg9.7'\n ld = [0 0.02674875741080976 -0.01686411844287495 ...\n -0.07822326652898785 0.2668641184428723 ...\n 0.6029490182363579 0.2668641184428723 ...\n -0.07822326652898785 -0.01686411844287495 ...\n 0.02674875741080976];\n hd = [0 0.09127176311424948 -0.05754352622849957 ...\n -0.5912717631142470 1.115087052456994 ...\n -0.5912717631142470 -0.05754352622849957 ...\n 0.09127176311424948 0 0];\n t = (0:9);\n lr = cos(pi * (t + 1)) .* hd;\n hr = cos(pi * t) .* ld;\n \notherwise\n error('Unrecognizable wavelet name (WNAME).');\nend\n\n% Output the requested filters.\nif (nargin == 1)\n varargout(1:4) = {ld, hd, lr, hr};\nelse\n switch lower(type(1))\n case 'd'\n varargout = {ld, hd};\n case 'r'\n varargout = {lr, hr};\n otherwise\n error('Unrecognizable filter TYPE.');\n end\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/wavefilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6895012309763446}} {"text": "function f = poissoncontunuos(x,lambda)\n% function f = poissoncontunuos(x,lambda)\nf = lambda.^x*exp(-lambda)./gamma(x+1);\n\n\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/aux/poissoncontunuos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6894983024852999}} {"text": "function [ c0, esterr ] = padua2 ( deg, degmax, npd, wpd, fpd )\n\n%*****************************************************************************80\n%\n%% PADUA2 computes the Padua interpolation coefficient matrix.\n%\n% Discussion:\n%\n% This subroutine computes the coefficient matrix C0, in the\n% orthonormal Chebyshev basis T_j(x)T_{k-j}(y), 0 <= j <= k <= DEG,\n% T_0(x)=1, T_j(x) = sqrt(2) * cos(j * acos(x)), of the\n% interpolation polynomial of degree DEG of the function values FPD\n% at the set of NPD Padua points (PD1,PD2) in the square [-1,1]^2.\n%\n% The interpolant may be evaluated at an arbitrary point by the\n% function PD2VAL. PD1, PD2 and WPD are the Padua points and weights\n% computed by PDPTS.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 February 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Marco Caliari, Stefano De Marchi, \n% Marco Vianello.\n% This MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Marco Caliari, Stefano de Marchi, Marco Vianello,\n% Algorithm 886:\n% Padua2D: Lagrange Interpolation at Padua Points on Bivariate Domains,\n% ACM Transactions on Mathematical Software,\n% Volume 35, Number 3, October 2008, Article 21, 11 pages.\n%\n% Parameters:\n%\n% Input, integer DEG, the degree of approximation.\n%\n% Input, integer DEGMAX, the maximum degree allowed.\n%\n% Input, integer NPD, the number of Padua points.\n%\n% Input, real WPD(NPD), the weights.\n%\n% Input, real FPD(NPD), the value at the Padua points\n% of the function to be interpolated.\n%\n% Output, real C0(0+1:DEG+1,0+1:DEG+1), the coefficient matrix.\n%\n% Output, real ESTERR, the estimated error.\n%\n BASE = 1;\n%\n% Build the matrix P_2 and store it in RAUX2.\n%\n raux2 = zeros ( deg + 1, deg + 2 );\n\n for i = 0 : deg + 1\n angle = i * pi / ( deg + 1 );\n pt = - cos ( angle );\n raux2(0+BASE:deg+BASE,i+1) = cheb ( deg, pt );\n end\n%\n% Build the matrix G(f) and store it in C0.\n%\n k = 0;\n for j = 0 : deg + 1\n for i = 0 : deg\n if ( mod ( i + j, 2 ) == 0 )\n k = k + 1;\n c0(i+BASE,j+BASE) = fpd(k) * wpd(k);\n else\n c0(i+BASE,j+BASE) = 0.0;\n end\n end\n end\n%\n% Compute the matrix-matrix product G(f)*P_2' and store it in RAUX1.\n%\n raux1 = zeros(degmax+1,deg+2);\n raux1 = dgemm ( 'n', 't', deg + 1, deg + 1, deg + 2, 1.0, ...\n c0, degmax + 2, raux2, degmax + 1, 0.0, raux1, degmax + 1 );\n%\n% Build the matrix P_1 and store it in RAUX2.\n%\n for i = 0 : deg\n angle = i * pi / deg;\n pt = - cos ( angle );\n raux2(0+BASE:deg+BASE,i+1) = cheb ( deg, pt );\n end\n%\n% Compute the matrix-matrix product C(f) = P_1 * ( G(f) * P_2' )\n% and store it in C0.\n%\n c0 = dgemm ( 'n', 'n', deg + 1, deg + 1, deg + 1, 1.0, ...\n raux2, degmax + 1, raux1, degmax + 1, 0.0, c0, degmax + 2 );\n\n c0(deg+BASE,0+BASE) = c0(deg+BASE,0+BASE) / 2.0;\n%\n% Estimate the error.\n%\n esterr = 0.0;\n for j = 0 : 2\n for i = 0 : deg - j\n esterr = esterr + abs ( c0(i+BASE,deg-i-j+BASE) );\n end\n end\n esterr = 2.0 * esterr;\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/toms886/padua2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6894950616134321}} {"text": "function r=findSubarrayWeights(T,d,a0)\n%%FINDSUBARRAYWEIGHTS Given that the elements in an array (linear, planar)\n% have been grouped into subarrays and some type of element level\n% tapering might be applied, find the subarray-level tapering\n% that best approximates a tapering desired for alll elements in\n% an array. For example, one mgiht taper all the elements with a\n% Taylor tapering to get a good sum beam, but then want to design\n% subarray weights to be able to get a good difference beam.\n%\n%INPUTS: T A numSubarraysXnumEls matrix holding that breaks the elements\n% into subarrays and includes any element-level tapering.\n% d A numElsX1 vector of the desired element-level tapering. This\n% function provides a weighting for the subarrays to approximate\n% this.\n% a0 An optional numElX1 parameter. If one wishes to place a null in\n% the direction of a0 (often one might want to place a null in the\n% look direction when approximating a difference beam), then this\n% input can be provided. Otherwise, unconsitrained optimization is\n% performed. This parameter is the array manifold in the look\n% direction. For boresight, this will usually just be a numELX1\n% vector of ones. For an isotropic model, the vector is typically \n% a0=exp(-1j*2*pi*sum(bsxfun(@times,xyPoints,u),1)).' where\n% xyPoints is a 2XnumEl matrix of the locations of the elements in\n% the array.\n%\n%OUTPUTS: r The set of (possibly complex) weights for the subarrays to\n% approximate the given desired element-level tapering.\n%\n%This function implements the equations in [1]. The unconstrained\n%optimization is just r=arg min_{r} norm(T*r-d)^2. The constrained\n%optimization with a0 just adds the constraint that a0'*T*r'=0.\n%\n%Two approaches are given in the paper. The second approach considers\n%emphasizing certain directions using a penalty function. However, when\n%considering approximating the tapering for a Bayliss-weighted difference\n%pattern, it was shown that this method was essentially the same as the\n%simpler first method. Thus, this function just implements the first\n%method.\n%\n%REFERENCES:\n%[1] U. R. O. Nickel, \"Subarray configurations for digital beamforming with\n% low sidelobes and adaptive interference suppression,\" in Record of the\n% IEEE International Radar Conference, Alexandria, VA, 8-11 May 1995,\n% pp. 714-719.\n%\n%August 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nT=T.';\n\nnumEls=size(T,1);\n\n%Note that pinv(T)=inv(T'*T)*T'\nTInv=pinv(T);\n\n%If the constraint on placing a null in the look direction is imposed:\nif(nargin>2&&~isempty(a0))\n r=TInv*(eye(numEls,numEls)-(a0*a0'*T*TInv)/(a0'*T*TInv*a0))*d;\nelse\n r=TInv*d;\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/Signal_Processing/Array_Processing/Subarrays/findSubarrayWeights.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6894950588138722}} {"text": "% plot the ROC curve with associated level set samples and true positive\n% and false positive rate calculations\n\n% Zoya Bylinskii, April 2016\n% linked to: \"What do different evaluation metrics tell us about saliency models?\"\n\nfunction visualize_AUC(salMap,fixations)\n% salMap is the saliency map\n% fixations is a binary map of fixation locations\n\nnpoints = 10; % number of points to sample on ROC curve\n\n% prepare the color map for the correctly detected and missed fixations\ncolmap = fliplr(colormap(jet(npoints)));\nG = linspace(0.5,1,20)';\ntpmap = horzcat(zeros(size(G)),G,zeros(size(G))); % green color space\nfpmap = horzcat(G,zeros(size(G)),zeros(size(G))); % red color space\n\n% compute AUC-Judd\nheatmap = im2double(salMap);\n[score,tp,fp,allthreshes] = AUC_Judd(heatmap, fixations);\n\nN = ceil(length(allthreshes)/npoints);\nallthreshes_samp = allthreshes(1:N:end);\n\nheatmap_norm = (heatmap-min(heatmap(:)))/(max(heatmap(:))-min(heatmap(:)));\n\nsalMap_col = makeLevelSets(heatmap, allthreshes_samp, colmap);\nfigure; subplot(1,2,1); imshow(salMap_col);\n\n% plot the ROC curve\ntp1 = tp(1:N:end); fp1 = fp(1:N:end);\nsubplot(1,2,2); plot(fp,tp,'b'); hold on;\nfor ii = 1:npoints\n plot(fp1(ii),tp1(ii),'.','color',colmap(ii,:),'markersize',20); hold on; axis square;\nend \ntitle(sprintf('AUC: %2.2f',score),'fontsize',14);\nxlabel('FP rate','fontsize',14); ylabel('TP rate','fontsize',14);\n\n% plot the level sets, one per subplot\nfigure('name','saliency map level sets');\nnplot = floor(npoints/2); % plot every other level set\nfor ii = 1:nplot\n %temp = heatmap_norm>=allthreshes_samp(ii); % plot every level set\n temp = heatmap_norm>=allthreshes_samp(2*ii); % plot every other level set\n temp2 = zeros(size(temp,1),size(temp,2),3);\n temp2(:,:,1) = temp*colmap(2*ii,1); temp2(:,:,2) = temp*colmap(2*ii,2); temp2(:,:,3) = temp*colmap(2*ii,3); \n subplottight(1,nplot,ii,0.05); imshow(temp2);\nend\n\n% plot the fixations falling within and outside of each level set \nfigure('name','true positives and false negatives');\nfor ii = 1:nplot\n % temp = heatmap_norm>=allthreshes_samp(ii); % plot every level set\n temp = heatmap_norm>=allthreshes_samp(2*ii); % plot every other level set\n res = fixations.*temp;\n res_neg = fixations.*(1-temp);\n subplottight(1,nplot,ii,0.05); imshow(temp); hold on; \n [J,I] = ind2sub(size(res),find(res==1));\n scatterPlotHeatmap(I,J,tpmap);\n [J,I] = ind2sub(size(res_neg),find(res_neg==1));\n scatterPlotHeatmap(I,J,fpmap);\nend", "meta": {"author": "cvzoya", "repo": "saliency", "sha": "5951cdc7c2ba73e5951d4c36bea58e8c7d41e55d", "save_path": "github-repos/MATLAB/cvzoya-saliency", "path": "github-repos/MATLAB/cvzoya-saliency/saliency-5951cdc7c2ba73e5951d4c36bea58e8c7d41e55d/code_forVisualization/visualize_AUC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6894950572287568}} {"text": "% demos for HMM in ch13\nd = 3; k = 2; n = 10000;\n[x,model] = hmmRnd(d,k,n);\n%% Viterbi algorithm\n[z, llh] = hmmViterbi(model, x);\n%% HMM filter (forward algorithm)\n[alpha, llh] = hmmFilter(model, x);\n%% HMM smoother (forward backward)\n[gamma,alpha,beta,c] = hmmSmoother(model, x);\n%% Baum-Welch algorithm\n[model, llh] = hmmEm(x,k);\nplot(llh)\n", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/demo/ch13/hmm_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933093946927838, "lm_q2_score": 0.7718435030872967, "lm_q1q2_score": 0.6894950525404708}} {"text": "%TSPOF_GA Fixed Open Traveling Salesman Problem (TSP) Genetic Algorithm (GA)\n% Finds a (near) optimal solution to a variation of the TSP by setting up\n% a GA to search for the shortest route (least distance for the salesman\n% to travel from a FIXED START to a FIXED END while visiting the other\n% cities exactly once)\n%\n% Summary:\n% 1. A single salesman starts at the first point, ends at the last\n% point, and travels to each of the remaining cities in between, but\n% does not close the loop by returning to the city he started from\n% 2. Each city is visited by the salesman exactly once\n%\n% Note: The Fixed Start is taken to be the first XY point, and the Fixed\n% End is taken to be the last XY point\n%\n% Input:\n% XY (float) is an Nx2 matrix of city locations, where N is the number of cities\n% DMAT (float) is an NxN matrix of point to point distances/costs\n% POPSIZE (scalar integer) is the size of the population (should be divisible by 4)\n% NUMITER (scalar integer) is the number of desired iterations for the algorithm to run\n% SHOWPROG (scalar logical) shows the GA progress if true\n% SHOWRESULT (scalar logical) shows the GA results if true\n%\n% Output:\n% OPTROUTE (integer array) is the best route found by the algorithm\n% MINDIST (scalar float) is the cost of the best route\n%\n% Example:\n% n = 50;\n% xy = 10*rand(n,2);\n% popSize = 60;\n% numIter = 1e4;\n% showProg = 1;\n% showResult = 1;\n% a = meshgrid(1:n);\n% dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),n,n);\n% [optRoute,minDist] = tspof_ga(xy,dmat,popSize,numIter,showProg,showResult);\n%\n% Example:\n% n = 50;\n% phi = (sqrt(5)-1)/2;\n% theta = 2*pi*phi*(0:n-1);\n% rho = (1:n).^phi;\n% [x,y] = pol2cart(theta(:),rho(:));\n% xy = 10*([x y]-min([x;y]))/(max([x;y])-min([x;y]));\n% popSize = 60;\n% numIter = 1e4;\n% showProg = 1;\n% showResult = 1;\n% a = meshgrid(1:n);\n% dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),n,n);\n% [optRoute,minDist] = tspof_ga(xy,dmat,popSize,numIter,showProg,showResult);\n%\n% Example:\n% n = 50;\n% xyz = 10*rand(n,3);\n% popSize = 60;\n% numIter = 1e4;\n% showProg = 1;\n% showResult = 1;\n% a = meshgrid(1:n);\n% dmat = reshape(sqrt(sum((xyz(a,:)-xyz(a',:)).^2,2)),n,n);\n% [optRoute,minDist] = tspof_ga(xyz,dmat,popSize,numIter,showProg,showResult);\n%\n% See also: tsp_ga, tsp_nn, tspo_ga, tspofs_ga, distmat\n%\n% Author: Joseph Kirk\n% Email: jdkirk630@gmail.com\n% Release: 1.3\n% Release Date: 11/07/11\nfunction varargout = tspof_ga(xy,dmat,popSize,numIter,showProg,showResult)\n\n% Process Inputs and Initialize Defaults\nnargs = 6;\nfor k = nargin:nargs-1\n switch k\n case 0\n xy = 10*rand(50,2);\n case 1\n N = size(xy,1);\n a = meshgrid(1:N);\n dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),N,N);\n case 2\n popSize = 100;\n case 3\n numIter = 1e4;\n case 4\n showProg = 1;\n case 5\n showResult = 1;\n otherwise\n end\nend\n\n% Verify Inputs\n[N,dims] = size(xy);\n[nr,nc] = size(dmat);\nif N ~= nr || N ~= nc\n error('Invalid XY or DMAT inputs!')\nend\nn = N - 2; % Separate Start and End Cities\n\n% Sanity Checks\npopSize = 4*ceil(popSize/4);\nnumIter = max(1,round(real(numIter(1))));\nshowProg = logical(showProg(1));\nshowResult = logical(showResult(1));\n\n% Initialize the Population\npop = zeros(popSize,n);\npop(1,:) = (1:n) + 1;\nfor k = 2:popSize\n pop(k,:) = randperm(n) + 1;\nend\n\n% Run the GA\nglobalMin = Inf;\ntotalDist = zeros(1,popSize);\ndistHistory = zeros(1,numIter);\ntmpPop = zeros(4,n);\nnewPop = zeros(popSize,n);\nif showProg\n pfig = figure('Name','TSPOF_GA | Current Best Solution','Numbertitle','off');\nend\nfor iter = 1:numIter\n % Evaluate Each Population Member (Calculate Total Distance)\n for p = 1:popSize\n d = dmat(1,pop(p,1)); % Add Start Distance\n for k = 2:n\n d = d + dmat(pop(p,k-1),pop(p,k));\n end\n d = d + dmat(pop(p,n),N); % Add End Distance\n totalDist(p) = d;\n end\n\n % Find the Best Route in the Population\n [minDist,index] = min(totalDist);\n distHistory(iter) = minDist;\n if minDist < globalMin\n globalMin = minDist;\n optRoute = pop(index,:);\n if showProg\n % Plot the Best Route\n figure(pfig);\n rte = [1 optRoute N];\n if dims > 2\n plot3(xy(rte,1),xy(rte,2),xy(rte,3),'r.-',...\n xy([1 N],1),xy([1 N],2),xy([1 N],3),'ro');\n else\n plot(xy(rte,1),xy(rte,2),'r.-',xy([1 N],1),xy([1 N],2),'ro');\n end\n title(sprintf('Total Distance = %1.4f, Iteration = %d',minDist,iter));\n end\n end\n\n % Genetic Algorithm Operators\n randomOrder = randperm(popSize);\n for p = 4:4:popSize\n rtes = pop(randomOrder(p-3:p),:);\n dists = totalDist(randomOrder(p-3:p));\n [ignore,idx] = min(dists); %#ok\n bestOf4Route = rtes(idx,:);\n routeInsertionPoints = sort(ceil(n*rand(1,2)));\n I = routeInsertionPoints(1);\n J = routeInsertionPoints(2);\n for k = 1:4 % Mutate the Best to get Three New Routes\n tmpPop(k,:) = bestOf4Route;\n switch k\n case 2 % Flip\n tmpPop(k,I:J) = tmpPop(k,J:-1:I);\n case 3 % Swap\n tmpPop(k,[I J]) = tmpPop(k,[J I]);\n case 4 % Slide\n tmpPop(k,I:J) = tmpPop(k,[I+1:J I]);\n otherwise % Do Nothing\n end\n end\n newPop(p-3:p,:) = tmpPop;\n end\n pop = newPop;\nend\n\nif showResult\n % Plots the GA Results\n figure('Name','TSPOF_GA | Results','Numbertitle','off');\n subplot(2,2,1);\n pclr = ~get(0,'DefaultAxesColor');\n if dims > 2, plot3(xy(:,1),xy(:,2),xy(:,3),'.','Color',pclr);\n else plot(xy(:,1),xy(:,2),'.','Color',pclr); end\n title('City Locations');\n subplot(2,2,2);\n imagesc(dmat([1 optRoute N],[1 optRoute N]));\n title('Distance Matrix');\n subplot(2,2,3);\n rte = [1 optRoute N];\n if dims > 2\n plot3(xy(rte,1),xy(rte,2),xy(rte,3),'r.-',...\n xy([1 N],1),xy([1 N],2),xy([1 N],3),'ro');\n else\n plot(xy(rte,1),xy(rte,2),'r.-',xy([1 N],1),xy([1 N],2),'ro');\n end\n title(sprintf('Total Distance = %1.4f',minDist));\n subplot(2,2,4);\n plot(distHistory,'b','LineWidth',2);\n title('Best Solution History');\n set(gca,'XLim',[0 numIter+1],'YLim',[0 1.1*max([1 distHistory])]);\nend\n\n% Return Outputs\nif nargout\n varargout{1} = optRoute;\n varargout{2} = minDist;\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/21197-fixed-endpoints-open-traveling-salesman-problem-genetic-algorithm/tspof_ga.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6894950519332486}} {"text": "function [x,esq,j] = v_kmeanlbg(d,k)\n%V_KMEANLBG Vector quantisation using the Linde-Buzo-Gray algorithm [X,ESQ,J]=(D,K)\n%\n%Inputs:\n% D contains data vectors (one per row)\n% K is number of centres required\n%\n%Outputs:\n% X is output row vectors (K rows)\n% ESQ is mean square error\n% J indicates which centre each data vector belongs to\n%\n% Implements LBG K-means algorithm:\n% Linde, Y., A. Buzo, and R. M. Gray,\n% \"An Algorithm for vector quantiser design,\"\n% IEEE Trans Communications, vol. 28, pp.84-95, Jan 1980.\n\n\n% Copyright (C) Mike Brookes 1998\n% Version: $Id: v_kmeanlbg.m 10865 2018-09-21 17:22:45Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\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 can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nnc=size(d,2);\n[x,esq,j]=v_kmeans(d,1);\nm=1;\nwhile m=0)\n% opts- Optimal inputs (default value: opts=[])\n%\n%% Output parameters:\n%\n% x- Solution\n% funVal- Function value during iterations\n%\n%% Copyright (C) 2010-2011 Jun Liu, and Jieping Ye\n%\n% You are suggested to first read the Manual.\n%\n% For any problem, please contact with Jun Liu via j.liu@asu.edu\n%\n% Last modified on April 21, 2010.\n%\n%% Related papers\n%\n% [1] Jun Liu and Jieping Ye, Fast Overlapping Group Lasso, \n% arXiv:1009.0306v1, 2010\n%\n%% Related functions:\n%\n% sll_opts, initFactor, pathSolutionLeast\n%\n%%\n\n%% Verify and initialize the parameters\n%%\nif (nargin <4)\n error('\\n Inputs: A, y, z, and opts (.ind) should be specified!\\n');\nend\n\n[m,n]=size(A);\n\nif (length(y) ~=m)\n error('\\n Check the length of y!\\n');\nend\n\nif (z(1)<0 || z(2)<0)\n error('\\n z should be nonnegative!\\n');\nend\n\nlambda1=z(1);\nlambda2=z(2);\n\nopts=sll_opts(opts); % run sll_opts to set default values (flags)\n\n% restart the program for better efficiency\n% this is a newly added function\nif (~isfield(opts,'rStartNum'))\n opts.rStartNum=opts.maxIter;\nelse\n if (opts.rStartNum<=0)\n opts.rStartNum=opts.maxIter;\n end\nend\n\n%% Detailed initialization\n%% Normalization\n\n% Please refer to sll_opts for the definitions of mu, nu and nFlag\n%\n% If .nFlag =1, the input matrix A is normalized to\n% A= ( A- repmat(mu, m,1) ) * diag(nu)^{-1}\n%\n% If .nFlag =2, the input matrix A is normalized to\n% A= diag(nu)^{-1} * ( A- repmat(mu, m,1) )\n%\n% Such normalization is done implicitly\n% This implicit normalization is suggested for the sparse matrix\n% but not for the dense matrix\n%\n\nif (opts.nFlag~=0)\n if (isfield(opts,'mu'))\n mu=opts.mu;\n if(size(mu,2)~=n)\n error('\\n Check the input .mu');\n end\n else\n mu=mean(A,1);\n end\n \n if (opts.nFlag==1)\n if (isfield(opts,'nu'))\n nu=opts.nu;\n if(size(nu,1)~=n)\n error('\\n Check the input .nu!');\n end\n else\n nu=(sum(A.^2,1)/m).^(0.5); nu=nu';\n end\n else % .nFlag=2\n if (isfield(opts,'nu'))\n nu=opts.nu;\n if(size(nu,1)~=m)\n error('\\n Check the input .nu!');\n end\n else\n nu=(sum(A.^2,2)/n).^(0.5);\n end\n end\n \n ind_zero=find(abs(nu)<= 1e-10); nu(ind_zero)=1;\n % If some values in nu is typically small, it might be that,\n % the entries in a given row or column in A are all close to zero.\n % For numerical stability, we set the corresponding value to 1.\nend\n\nif (~issparse(A)) && (opts.nFlag~=0)\n fprintf('\\n -----------------------------------------------------');\n fprintf('\\n The data is not sparse or not stored in sparse format');\n fprintf('\\n The code still works.');\n fprintf('\\n But we suggest you to normalize the data directly,');\n fprintf('\\n for achieving better efficiency.');\n fprintf('\\n -----------------------------------------------------');\nend\n\n%% Group & Others \n\n% Initialize maxIter2\nif (~isfield(opts,'maxIter2'))\n maxIter2=1000;\nelse\n maxIter2=opts.maxIter2; \nend\n% the maximal number of iteration for the projection\n\n\n% Initialize tol2\nif (~isfield(opts,'tol2'))\n tol2=1e-8;\nelse\n tol2=opts.tol2; \nend\n% the duality gap of the projection\n\n\n% Initialize flag2\nif (~isfield(opts,'flag2'))\n flag2=2;\nelse\n flag2=opts.flag2; \nend\n\n\n% Initialize G \nif (~isfield(opts,'G'))\n error('\\n In overlapping_LeastR, the field .G should be specified');\nelse\n G=opts.G-1; \n % we substract 1, as in C, the index begins with 0\nend\n\n% Initialize w \nif (~isfield(opts,'ind'))\n error('\\n In overlapping_LeastR, the field .ind should be specified');\nelse\n w=opts.ind;\n \n if (size(w,1)~=3)\n error('\\n w is a 3 x groupNum matrix');\n end\n \n w(1:2,:)=w(1:2,:)-1;\n % we substract 1, as in C, the index begins with 0 \nend\n\ngroupNum=size(w,2);\n% the number of groups\n\nY=zeros(length(G),1);\n% the starting point for the projection\n\n\n%% Starting point initialization\n\n% compute AT y\nif (opts.nFlag==0)\n ATy =A'*y;\nelseif (opts.nFlag==1)\n ATy= A'*y - sum(y) * mu'; ATy=ATy./nu;\nelse\n invNu=y./nu; ATy=A'*invNu-sum(invNu)*mu';\nend\n\n% process the regularization parameter\nif (opts.rFlag~=0)\n % z here is the scaling factor lying in [0,1]\n% if (lambda1<0 || lambda1>1 || lambda2<0 || lambda2>1)\n% error('\\n opts.rFlag=1, and z should be in [0,1]');\n% end\n \n % compute lambda1_max\n temp=abs(ATy);\n lambda1_max=max(temp);\n \n lambda1=lambda1*lambda1_max;\n \n % compute lambda2_max(lambda_1)\n \n % lambda_2_max to be added later\n \n lambda2_max=1;\n \n lambda2=lambda2*lambda2_max;\nend\n\n\n% initialize a starting point\nif opts.init==2\n x=zeros(n,1);\nelse\n if isfield(opts,'x0')\n x=opts.x0;\n if (length(x)~=n)\n error('\\n Check the input .x0');\n end\n else\n x=ATy; % if .x0 is not specified, we use ratio*ATy,\n % where ratio is a positive value\n end\nend\n\n% compute A x\nif (opts.nFlag==0)\n Ax=A* x;\nelseif (opts.nFlag==1)\n invNu=x./nu; mu_invNu=mu * invNu;\n Ax=A*invNu -repmat(mu_invNu, m, 1);\nelse\n Ax=A*x-repmat(mu*x, m, 1); Ax=Ax./nu;\nend\n\nif (opts.init==0) \n % ------ This function is not available\n %\n % If .init=0, we set x=ratio*x by \"initFactor\"\n % Please refer to the function initFactor for detail\n %\n \n % Here, we only support starting from zero, due to the complex\n % structure\n \n %x=zeros(n,1); \nend\n\n%% The main program\n% The Armijo Goldstein line search schemes + accelearted gradient descent\n\nbFlag=0; % this flag tests whether the gradient step only changes a little\n\nif (opts.mFlag==0 && opts.lFlag==0) \n L=1;\n % We assume that the maximum eigenvalue of A'A is over 1\n \n % assign xp with x, and Axp with Ax\n xp=x; Axp=Ax; xxp=zeros(n,1);\n \n alphap=0; alpha=1;\n \n for iterStep=1:opts.maxIter\n % --------------------------- step 1 ---------------------------\n % compute search point s based on xp and x (with beta)\n beta=(alphap-1)/alpha; s=x + beta* xxp;\n \n % --------------------------- step 2 ---------------------------\n % line search for L and compute the new approximate solution x\n \n % compute the gradient (g) at s\n As=Ax + beta* (Ax-Axp);\n \n % compute AT As\n if (opts.nFlag==0)\n ATAs=A'*As;\n elseif (opts.nFlag==1)\n ATAs=A'*As - sum(As) * mu'; ATAs=ATAs./nu;\n else\n invNu=As./nu; ATAs=A'*invNu-sum(invNu)*mu';\n end\n \n % obtain the gradient g\n g=ATAs-ATy;\n \n % copy x and Ax to xp and Axp\n xp=x; Axp=Ax;\n \n firstFlag=1; \n while (1)\n % let s walk in a step in the antigradient of s to get v\n % and then do the L1/Lq-norm regularized projection\n v=s-g/L;\n \n % projection\n [x,gap,penalty2]=overlapping(v, n, groupNum, lambda1/L, lambda2/L,...\n w, G, Y, maxIter2, flag2, tol2);\n \n \n if (nargout ==4)\n % record the number of iterations\n \n if (firstFlag)\n res.projStep(iterStep)=penalty2(4);\n else\n res.projStep(iterStep)=...\n max(res.projStep(iterStep),penalty2(4) );\n end\n end \n firstFlag=0;\n \n v=x-s; % the difference between the new approximate solution x\n % and the search point s\n \n % compute A x\n if (opts.nFlag==0)\n Ax=A* x;\n elseif (opts.nFlag==1)\n invNu=x./nu; mu_invNu=mu * invNu;\n Ax=A*invNu -repmat(mu_invNu, m, 1);\n else\n Ax=A*x-repmat(mu*x, m, 1); Ax=Ax./nu;\n end\n \n Av=Ax -As;\n r_sum=v'*v; l_sum=Av'*Av;\n \n if (r_sum <=1e-20)\n bFlag=1; % this shows that, the gradient step makes little improvement\n break;\n end\n \n % the condition is ||Av||_2^2 <= L * ||v||_2^2\n if(l_sum <= r_sum * L)\n break;\n else\n L=max(2*L, l_sum/r_sum);\n %fprintf('\\n L=%5.6f',L);\n end\n end\n \n % --------------------------- step 3 ---------------------------\n % update alpha and alphap, and check whether converge\n alphap=alpha; alpha= (1+ sqrt(4*alpha*alpha +1))/2;\n \n xxp=x-xp; Axy=Ax-y;\n \n ValueL(iterStep)=L;\n \n \n % function value = loss + regularizatioin\n funVal(iterStep)=Axy'* Axy/2 + lambda1 * sum(abs(x)) + lambda2 *penalty2 (1);\n \n if (nargout ==4)\n % record pp and gg;\n res.pp(iterStep)=penalty2 (2);\n res.qq(iterStep)=penalty2 (3);\n \n % record gap\n res.gap(iterStep)=gap;\n \n % record the number of zero group in the solution\n res.zg(iterStep)=penalty2(5);\n end\n \n if (bFlag)\n % fprintf('\\n The program terminates as the gradient step changes the solution very small.');\n break;\n end\n \n switch(opts.tFlag)\n case 0\n if iterStep>=2\n if (abs( funVal(iterStep) - funVal(iterStep-1) ) <= opts.tol)\n break;\n end\n end\n case 1\n if iterStep>=2\n if (abs( funVal(iterStep) - funVal(iterStep-1) ) <=...\n opts.tol* funVal(iterStep-1))\n break;\n end\n end\n case 2\n if ( funVal(iterStep)<= opts.tol)\n break;\n end\n case 3\n norm_xxp=sqrt(xxp'*xxp);\n if ( norm_xxp <=opts.tol)\n break;\n end\n case 4\n norm_xp=sqrt(xp'*xp); norm_xxp=sqrt(xxp'*xxp);\n if ( norm_xxp <=opts.tol * max(norm_xp,1))\n break;\n end\n case 5\n if iterStep>=opts.maxIter\n break;\n end\n end\n \n % restart the program every opts.rStartNum\n if (~mod(iterStep, opts.rStartNum))\n alphap=0; alpha=1;\n xp=x; Axp=Ax; xxp=zeros(n,1); L =L/2;\n end\n end\nelse\n error('\\n The function does not support opts.mFlag neq 0 & opts.lFlag neq 0!');\nend", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_SLEP/SLEP/functions/overlapping/overlapping_LeastR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.896251378675949, "lm_q2_score": 0.769080247656264, "lm_q1q2_score": 0.6892892322743669}} {"text": "%The spherical K-means algorithm\n%(C) 2007-2011 Nguyen Xuan Vinh \n%Contact: vinh.nguyenx at gmail.com or vinh.nguyen at monash.edu\n%Reference: \n% [1] Xuan Vinh Nguyen: Gene Clustering on the Unit Hypersphere with the \n% Spherical K-Means Algorithm: Coping with Extremely Large Number of Local Optima. BIOCOMP 2008: 226-233\n%Usage: Normalize the data set to have unit norm\n\nfunction b=normalize_norm(a)\n[n dim]=size(a);\nfor i=1:n\n a(i,:)=a(i,:)/norm(a(i,:));\nend\nb=a;", "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/32987-the-spherical-k-means-algorithm/SPKmeans/normalize_norm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6892892249183136}} {"text": "% EX_MAXWELL_SRC_CAMEMBERT: solve Maxwell source problem in three quarters of the cylinder, where the exact solution is a singular function.\n\n% 1) PHYSICAL DATA OF THE PROBLEM\nclear problem_data \n% Physical domain, defined as NURBS map given in a text file\nproblem_data.geo_name = 'geo_camembert.txt';\n\n% Type of boundary conditions\nproblem_data.nmnn_sides = [3 4 5 6];\nproblem_data.drchlt_sides = [1 2];\n\n% Physical parameters\nproblem_data.c_mass = @(x, y, z) ones(size(x));\nproblem_data.c_stiff = @(x, y, z) ones(size(x));\n\n% Source and boundary terms\nk = 1; % Constant that characterizes the singularity\nproblem_data.f = @(x, y, z) cat (1, ...\n singular_function_maxwell (x, y, k), ...\n zeros ([1, size(x)]));\nproblem_data.g = @(x, y, z, ind) zeros ([3, size(x)]);\nproblem_data.h = @(x, y, z, ind) cat (1, ...\n singular_function_maxwell (x, y, k), ...\n zeros ([1, size(x)]));\n\n% Exact solution (optional)\nproblem_data.uex = @(x, y, z) cat (1, ...\n singular_function_maxwell (x, y, k), ...\n zeros ([1, size(x)]));\nproblem_data.curluex = @(x, y, z) zeros ([3, size(x)]);\n\n% 2) CHOICE OF THE DISCRETIZATION PARAMETERS\nclear method_data\nmethod_data.degree = [2 2 2]; % Degree of the bsplines\nmethod_data.regularity = [1 1 1]; % Regularity of the splines\nmethod_data.nsub = [3 3 3]; % Number of subdivisions\nmethod_data.nquad = [3 3 3]; % Points for the Gaussian quadrature rule\n\n% 3) CALL TO THE SOLVER\n% Remove warnings for the degenerated elements\nwarning ('off', 'geopdes:jacdet_zero_at_quad_node')\nwarning ('off', 'geopdes:zero_measure_element')\n[geometry, msh, space, u] = solve_maxwell_src (problem_data, method_data);\n\n% 4) POST-PROCESSING\n% 4.1) EXPORT TO PARAVIEW\noutput_file = 'maxwell_camembert_Deg2_Reg1_Sub3';\n\nvtk_pts = {linspace(0, 1, 15), linspace(0, 0.99, 15), linspace(0, 1, 15)};\nfprintf ('The result is saved in the file %s \\n \\n', output_file);\nsp_to_vtk (u, space, geometry, vtk_pts, output_file, 'u')\n\n% 4.2) Comparison with the exact solution\n[error_hcurl, error_l2] = ...\n sp_hcurl_error (space, msh, u, problem_data.uex, problem_data.curluex)\n\n%!demo\n%! ex_maxwell_src_camembert\n\n%!test\n%! problem_data.geo_name = 'geo_camembert.txt';\n%! problem_data.nmnn_sides = [3 4 5 6];\n%! problem_data.drchlt_sides = [1 2];\n%! problem_data.c_mass = @(x, y, z) ones(size(x));\n%! problem_data.c_stiff = @(x, y, z) ones(size(x));\n%! k = 1; % Constant that characterizes the singularity\n%! problem_data.f = @(x, y, z) cat (1, ...\n%! singular_function_maxwell (x, y, k), ...\n%! zeros ([1, size(x)]));\n%! problem_data.g = @(x, y, z, ind) zeros ([3, size(x)]);\n%! problem_data.h = @(x, y, z, ind) cat (1, ...\n%! singular_function_maxwell (x, y, k), ...\n%! zeros ([1, size(x)]));\n%! problem_data.uex = @(x, y, z) cat (1, ...\n%! singular_function_maxwell (x, y, k), ...\n%! zeros ([1, size(x)]));\n%! problem_data.curluex = @(x, y, z) zeros ([3, size(x)]);\n%! method_data.degree = [2 2 2]; % Degree of the bsplines\n%! method_data.regularity = [1 1 1]; % Regularity of the splines\n%! method_data.nsub = [3 3 3]; % Number of subdivisions\n%! method_data.nquad = [3 3 3]; % Points for the Gaussian quadrature rule\n%! warning ('off', 'geopdes:jacdet_zero_at_quad_node')\n%! warning ('off', 'geopdes:zero_measure_element')\n%! [geometry, msh, space, u] = solve_maxwell_src (problem_data, method_data);\n%! [error_hcurl, error_l2] = sp_hcurl_error (space, msh, u, problem_data.uex, problem_data.curluex);\n%! assert (msh.nel, 81)\n%! assert (space.ndof, 820)\n%! assert (error_l2, 0.0436842163001183, 1e-14)\n%! assert (error_hcurl, 0.0436861291289525, 1e-14)\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/examples/maxwell/ex_maxwell_src_camembert.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6892892216181278}} {"text": "function F = FGG_3d(f,knots,N,accuracy,GridListx, GridListy, GridListz)\n%Description:\n%This code implements the 3D version of the \"accelerated\" \n%Gaussian-gridding-based NUFFT described in Greengard and Lee [1]. The \n%gridding approach is very similar to previous work by Nguyen and Liu [2]; \n%the only difference is the use of a different convolution kernel ([1] \n%claims that the Gaussian kernel has computational advantages). Both \n%algorithms allow the user to specify the numerical precision of the \n%routine, but [1] provides a nice summary that would allow one to tabulate \n%the appropriate variable values for each desired numerical precision. Code \n%for [2] is also available upon request.\n%\n%This code performs NUFFTs that form rectangular cubes of size N=[Nx,Ny,Nz] \n%(not counting frequency padding for image interpolation). The approximate \n%DFT attains errors on the order of 1e-6 (for more or less accuracy, vary \n%the optional \"accuracy\" parameter). \n%\n%Inputs:\n% f: frequency-domain data (a complex Mx1 vector) unwrapped from a\n% matrix knots: k-space locations at which the data were measured\n% (an Mx3 vector). This data must be in double format.\n% knots: the frequency locations of the data points. These locations\n% should be normalized to correspond to the grid boundaries\n% [-N/2, N/2 -1/N], N even. If the knots are not scaled\n% properly, they will be shifted and scaled into this normalized\n% form.\n% N = [Nx,Ny,Nz]: the 1x3 vector denoting the size of the spatial\n% grid in the image domain. This parameter will determine the\n% spatial extent of the image.\n% accuracy: (optional input parameter) a positive integer indicating \n% the desired number of digits of accuracy\n%Optional Inputs (highly recommended):\n% GridListx:(column vector) The x-locations of the \n% frequency grid (not yet scaled by c or 2*pi) onto which the \n% data should be interpolated\n% GridListy:(column vector) The y-locations of the \n% frequency grid (not yet scaled by c or 2*pi) onto which the \n% data should be interpolated\n% GridListz:(column vector) The z-locations of the \n% frequency grid (not yet scaled by c or 2*pi) onto which the \n% data should be interpolated\n%Outputs:\n% F: the 3D NUFFT (approximate DFT) of f, with dimension [Nx,Ny,Nz].\n%\n%\n%Usage Notes:\n%In order for this function to work, the C\n%file \"FGG_Convolution3D.c\" must be compiled into a Matlab executable \n%(cmex) with the following command in the command prompt:\n%\n%mex FGG_Convolution3D.c\n%\n%A note on the effect of M_sp on the algorithm's accuracy:\n%[R,M_sp]=[2,3] ==> 1e-3 accuracy\n%[R,M_sp]=[2,6] ==> single precision\n%[R,M_sp]=[2,9] ==> 1e-9 accuracy\n%[R,M_sp]=[2,12] ==> double precision\n%\n%References:\n%[1] L. Greengard and J. Lee, \"Accelerating the Nonuniform Fast Fourier\n%Transform,\" SIAM Review, Vol. 46, No. 3, pp. 443-454.\n%[2] N. Nguyen and Q. H. Liu, \"Nonuniform fast fourier transforms,\" SIAM J.\n%Sci. Comput., 1999.\n%\n%Please note:\n%This code is free to use, but we ask that you please reference the source,\n%as this will encourage future funding for more free AFRL products. This\n%code was developed through the AFOSR Lab Task \"Moving-Target Radar Feature\n%Extraction.\"\n%Project Manager: Arje Nachman\n%Principal Investigator: Matthew Ferrara\n%Date: November 2008\n%\n%Code by (send correspondence to):\n%Matthew Ferrara, Research Mathematician\n%AFRL Sensors Directorate Innovative Algorithms Branch (AFRL/RYAT)\n%Matthew.Ferrara@wpafb.af.mil\n\n%Explanation of variables used\n%bw The bandwidth of the input data (fmax-fmin)\n%D A [Nx,Ny,Nz] deconvolution matrix formed from the 3D \n% kronecker product of E4_x, E4_y, and E4_z \n%dgx,dgy,dgz The separation (in the frequency domain) of the\n% user-defined k-space grid onto which the data should be \n% interpolated\n%E1, E2, E3 factors of the Gaussian filter in the frequency domain\n% (the Gaussian is factored to eliminate redundant\n% exponential calculations)\n%E4 The Gaussian deconvolution filter\n%f The Mx1 vector of nonuniformly-spaced frequency data given\n% as input to the NUFFT routine\n%f_tau The [R*Nx,R*Ny] matrix of uniformly-spaced fequency-domain\n% data values after \"gridding\"\n%F_tau The FFT of f_tau\n%F The approximate DFT of f (the deconvolved FFT of f_tau)\n%fmean The average knot values of the input data (1x3 vector) \n%j Index variable that indexes the convolution loop through\n% the data points (1 <= j <= M)\n%kmin The minimum knot values of the input data (1x3 vector)\n%kmax The maximum knot values of the input data (1x3 vector)\n%knots The Mx3 vector of frequency locations given as input to\n% the NUFFT. \n%M The number of (k-space) data points (the length of the\n% input data vector f)\n%M_sp Width of the frequency-domain box used in the approximate\n% interpolation of each data point onto the frequency grid\n% (M_sp=6 for single precision and M_sp=12 for double\n% precision)\n%N The image size of the NUFFT output (N=[Nx, Ny, Nz])\n%Nx The length of the image in the x dimension\n%Ny The length of the image in the y dimension\n%Nz The length of the image in the z dimension\n%R Oversampling ratio for gridding in the frequency (data)\n% domain\n%S The [Nz,Nx*Ny]-sized kronecker product of E4z, E4_x, and \n% E4_y \n%scale 1x3 vector used to scale the input data locations into the\n% normalized form\n%shift 1x3 vector used to shift the input data locations into the\n% normalized form\n%tau The 3x1 Gaussian kernel spreading factor\n%End Explanation of variables\n\n%% Step 1: Initialize constant variables:\nM=length(f);%number of frequency-domain data points\nif nargin<4, accuracy=6; end\nif nargin<3, N=M; accuracy=6; end\nif length(N)<2, N=N(1)*[1,1,1];accuracy=6; end\n%The size parameters [Nx,Ny] determine the spatial extent of the image\nNx=N(1); Ny=N(2); Nz=N(3);\n%R is the oversampling ratio(>1) for gridding in the frequency (data)\n%domain. There are diminishing returns in accuracy after R=2 (M_sp has a\n%more direct effect on accuracy).\nR=2;\n%M_sp is the length of the convolution kernel\nM_sp=accuracy;%This gives roughly 6 digits of accuracy\n%The variance, tau, of the Gaussian filter may be different in each\n%dimension\n%tau = M_sp./(N.^2);%I was initially using this value\ntau = (pi*M_sp./(N.*N*R*(R-.5)));%Suggested value of tau by Greengard [1]\n%The length of the oversampled grid\nM_r = R*N;\n%Scale knots (data locations) to [-N/2,N/2-1] (I don't initially use \n%Greengard's [0,2*pi] convention, but instead assume users will most likely \n%be thinking in terms of fs<=f<=fe)\nkmin=min(knots);\nkmax=max(knots);\n\nif nargin <=4,%Simply choose the most convenient frequency-domain grid\n bw=kmax-kmin;\n scale=(N-1)./bw;\n shift=-N/2-kmin.*scale;\n knots=repmat(scale,[M,1]).*knots + repmat(shift,[M,1]);\nelse%we specify knot locations in terms of the user-defined grid (this\n %consequently specifies the image pixel locations)\n fmean=(kmin+kmax)/2;\n dgx=GridListx(2)-GridListx(1);\n dgy=GridListy(2)-GridListy(1);\n dgz=GridListz(2)-GridListz(1); \n %We choose to ensure that the data are perfectly centered on the grid:\n kminx=fmean(1)-(Nx/2)*dgx;\n kmaxx=kminx+(Nx-1)*dgx;\n kminy=fmean(2)-(Ny/2)*dgy;\n kmaxy=kminy+(Ny-1)*dgy;\n kminz=fmean(3)-(Nz/2)*dgz;\n kmaxz=kminz+(Nz-1)*dgz; \n kmin=[kminx, kminy, kminz];\n kmax=[kmaxx, kmaxy, kmaxz];\n %The BW that covers the whole k-space region when confined to the\n %specified grid spacing\n bw=[kmaxx-kminx, kmaxy-kminy, kmaxz-kminz];\n scale=(N-1)./bw;\n shift=-.5*[Nx,Ny,Nz]-[kminx,kminy,kminz].*scale;\n knots=repmat(scale,[M,1]).*knots + repmat(shift,[M,1]);\nend\n%Switch knot locations to [0,2*pi] convention (used by Greengard):\nknots=mod(2*pi*knots./repmat(N,[M,1]),2*pi);%Makes NUFFT implementation \n%more straightforward when notation is the same!\n\n%Precompute E_3, the constant component of the (truncated) Gaussian:\nE_3x(1,1:M_sp) = exp(-((pi*(1:M_sp)/M_r(1)).^2)/tau(1));\n%don't waste (slow) exponential calculations\nE_3x=[fliplr(E_3x(1:(M_sp-1))),1,E_3x];\nE_3y(1,1:M_sp) = exp(-((pi*(1:M_sp)/M_r(2)).^2)/tau(2));\n%don't waste (slow) exponential calculations\nE_3y=[fliplr(E_3y(1:(M_sp-1))),1,E_3y];\nE_3z(1,1:M_sp) = exp(-((pi*(1:M_sp)/M_r(3)).^2)/tau(3));\n%don't waste (slow) exponential calculations\nE_3z=[fliplr(E_3z(1:(M_sp-1))),1,E_3z];\n\n%Precompute E_4 (for devonvolution after the FFT)\nkx_vec = (-Nx/2):(Nx/2-1);\n%The Hadamard Inverse of the Fourier Transform of the truncated Gaussian\nE_4x(1:Nx,1)=sqrt(pi/tau(1))*exp(tau(1)*(kx_vec.^2));\nky_vec = (-Ny/2):(Ny/2-1);\n%The Hadamard Inverse of the Fourier Transform of the truncated Gaussian\nE_4y(1,1:Ny)=sqrt(pi/tau(2))*exp(tau(2)*(ky_vec.^2));%\nkz_vec = (-Nz/2):(Nz/2-1);\n%The Hadamard Inverse of the Fourier Transform of the truncated Gaussian\nE_4z(1:Nz,1)=sqrt(pi/tau(3))*exp(tau(3)*(kz_vec.^2));%\n%End initialization of constant variables\n\n%% Step 2: Approximate convolution for each datum location, (x_j,y_j). This\n% step is implemented in C and compiled into a Matlab-executable (cmex)\n% file.\n%Initialize convolved data matrix\nf_tau=zeros(M_r(1),M_r(2),M_r(3));\nf_taui=zeros(M_r(1)*M_r(2)*M_r(3),1);%Imaginary components of f_tau\nf_taur=zeros(M_r(1)*M_r(2)*M_r(3),1);%Real components of f_tau\n%Perform convolution onto finely-spaced grid\n\n[f_taur,f_taui]=...\n FGG_Convolution3D(double(real(f(:))),double(imag(f(:))),...\n double(knots(:)),double(E_3x), double(E_3y), double(E_3z), ...\n [double(M_sp), double(tau(1)), double(tau(2)), double(tau(3)),...\n double(M_r(1)), double(M_r(2)), double(M_r(3))]);\n\nf_tau = reshape(f_taur+sqrt(-1)*f_taui,[M_r(1), M_r(2), M_r(3)]);\n\n\n%% Step 3: Perform FFT and deconvolve the result\n%Perform FFT\nF_tau=fftshift(fftn(ifftshift(f_tau)));\n%Chop off excess pixels(the fine spacing in the frequency domain expanded\n%the image in the transform domain)\nF_tau(1:round(.5*(R-1)*Nx),:,:)=[];\nF_tau(Nx+1:end,:,:)=[];\nF_tau(:,1:round(.5*(R-1)*Ny),:)=[];\nF_tau(:,Ny+1:end,:)=[];\nF_tau(:,:,1:round(.5*(R-1)*Nz))=[];\nF_tau(:,:,Nz+1:end)=[];\n\n%Deconvolve the FFT by Hadamard multiplication with the Gaussian\n%To form the deconvolution matrix S, we could do this with a loop:\n%for i=1:Nx\n% for j=1:Ny\n% for k=1:Nz\n% S(i,j,k)=E_4x(i)*E_4y(j)*E_4z(k);\n% end\n% end\n%end\n%HOWEVER, Matlab is extremely slow with loops so we instead use the kron()\n%function and reshape the result (alternatively, we could have written \n%another mex function):\nS=kron(E_4z,E_4x*E_4y);%Scalars for 3D kronecker product (matrix must be \n %reshaped)\nD=permute(reshape(S,[Nx,Nz,Ny]),[1,3,2]);\nF=F_tau.*D/(M*R*R*R); %Note that the scaling factor is 1/M, which is \n%apparently not 1/M_r as shown in eqn (9) in [1]. This makes sense because\n%the scaling factor for the DFT we are attempting to approximate (in eqn \n%(1) of [1]) is 1/M. \n\n\n%% If desired, compare to DFT \n% F_true=zeros(Nx,Ny,Nz);\n% for m=(-Nx/2):(Nx/2 -1)\n% for n=(-Ny/2):(Ny/2 -1)\n% for o=(-Nz/2):(Nz/2 -1)\n% for k=1:M\n% F_true(m+Nx/2+1,n+Ny/2+1,o+Nz/2+1)=...\n% F_true(m+Nx/2+1,n+Ny/2+1,o+Nz/2+1)+...\n% f(k)*exp(sqrt(-1)*(m*knots(k,1) + n*knots(k,2) + ...\n% o*knots(k,3)));\n% end\n% end\n% end\n% F_true=F_true/M;\n% \n% figure\n% isosurface(abs(F))\n% title('F via NUFFT')\n% \n% figure\n% isosurface(abs(F_true))\n% title('F via DFT')\n% \n%error('done!')\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/25135-nufft-nfft-usfft/NUFFT_code/NUFFT_code/FGG_3d_type1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6891867404531553}} {"text": "%This function calculates BETA probabilities at each stage for all states,\n%using GAMMA probabilities obtained previously. Uses recursion formula for\n%BETA to calculate it for the previous stage. Each column is for states 00,10,01\n%and 11 respectively. As we move backward in the block BETA will become very\n%small, as the 1st term corresponding to gamma can be very less(of the order \n%of 10^(-15)). Hence BETA will keep on decreasing and will become very small. \n%After some stages it will become exactly 0. So to avoid that we can\n%multiply each BETA by 10^(-20) at a stage where they all become less than \n%10^(-20). As we need BETA in calculation of LAPPR. So scaling wont affect the ratio\n\nfunction [BETA]=beta_1(GAMMA,N)\n \n BETA=zeros(4,N);\n %Initialization assuming the final stage to be 00\n BETA(1,N)=1;BETA(2,N)=0;BETA(3,N)=0;BETA(4,N)=0;\n \n j=2*N-1;\n for i=N-1:-1:1\n BETA(1,i)=(GAMMA(1,j)*BETA(1,i+1))+(GAMMA(1,j+1)*BETA(2,i+1));\n BETA(2,i)=(GAMMA(2,j)*BETA(3,i+1))+(GAMMA(2,j+1)*BETA(4,i+1));\n BETA(3,i)=(GAMMA(3,j)*BETA(2,i+1))+(GAMMA(3,j+1)*BETA(1,i+1));\n BETA(4,i)=(GAMMA(4,j)*BETA(4,i+1))+(GAMMA(4,j+1)*BETA(3,i+1));\n j=j-2; \n \n if (BETA(1,i)<10^(-20) && BETA(2,i)<10^(-20) &&...\n BETA(3,i)<10^(-20) && BETA(4,i)<10^(-20) )\n BETA(:,i)=10^(20)*BETA(:,i); %Scaling beta if became very less \n end\n end\n \n \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/39423-turbo-code/turbo/beta_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317103, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6891867307022537}} {"text": "function R=Rxyz(t,flag)\n\nif flag==1\n R=[1 0 0;\n 0 cos(t) -sin(t);\n 0 sin(t) cos(t)]';\nelseif flag==2\n R=[cos(t) 0 sin(t);\n 0 1 0;\n -sin(t) 0 cos(t)]';\nelseif flag==3\n R=[ cos(t) -sin(t) 0;\n sin(t) cos(t) 0;\n 0 0 1]';\nend\n\nreturn;", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/common/Rxyz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167044, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6891867224432638}} {"text": "function arctan2_values_test ( )\n\n%*****************************************************************************80\n%\n%% ARCTAN2_VALUES_TEST demonstrates the use of ARCTAN2_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 February 2015\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ARCTAN2_VALUES_TEST:\\n' );\n fprintf ( 1, ' ARCTAN2_VALUES stores values of \\n' );\n fprintf ( 1, ' the arc tangent function.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X Y F\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, x, y, f ] = arctan2_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %12f %12f %24.16f\\n', x, y, f );\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/test_values/arctan2_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.8633916117313211, "lm_q1q2_score": 0.6891477767850033}} {"text": "function checkdiff(problem, x, d, force_gradient)\n% Checks the consistency of the cost function and directional derivatives.\n%\n% function checkdiff(problem)\n% function checkdiff(problem, x)\n% function checkdiff(problem, x, d)\n%\n% checkdiff performs a numerical test to check that the directional\n% derivatives defined in the problem structure agree up to first order with\n% the cost function at some point x, along some direction d. The test is\n% based on a truncated Taylor series (see online Manopt documentation).\n%\n% Both x and d are optional and will be sampled at random if omitted.\n%\n% See also: checkgradient checkhessian\n\n% If force_gradient = true (hidden parameter), then the function will call\n% getGradient and infer the directional derivative, rather than call\n% getDirectionalDerivative directly. This is used by checkgradient.\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Dec. 30, 2012.\n% Contributors: \n% Change log: \n%\n% March 26, 2017 (JB):\n% Detects if the approximated linear model is exact\n% and provides the user with the corresponding feedback.\n% \n% April 3, 2015 (NB):\n% Works with the new StoreDB class system.\n%\n% Aug. 2, 2018 (NB):\n% Using storedb.remove() to avoid unnecessary cache build-up.\n%\n% Sep. 6, 2018 (NB):\n% Now checks whether M.exp() is available; uses retraction otherwise.\n%\n% June 18, 2019 (NB):\n% Now issues a warning if the cost function returns complex values.\n\n if ~exist('force_gradient', 'var')\n force_gradient = false;\n end\n \n % Verify that the problem description is sufficient.\n if ~canGetCost(problem)\n error('It seems no cost was provided.');\n end\n if ~force_gradient && ~canGetDirectionalDerivative(problem)\n error('It seems no directional derivatives were provided.');\n end\n if force_gradient && ~canGetGradient(problem)\n % Would normally issue a warning, but this function should only be\n % called with force_gradient on by checkgradient, which will\n % already have issued a warning.\n end\n \n x_isprovided = exist('x', 'var') && ~isempty(x);\n d_isprovided = exist('d', 'var') && ~isempty(d);\n \n if ~x_isprovided && d_isprovided\n error('If d is provided, x must be too, since d is tangent at x.');\n end\n \n % If x and / or d are not specified, pick them at random.\n if ~x_isprovided\n x = problem.M.rand();\n end\n if ~d_isprovided\n d = problem.M.randvec(x);\n end\n\n % Compute the value f0 at f and directional derivative at x along d.\n storedb = StoreDB();\n xkey = storedb.getNewKey();\n f0 = getCost(problem, x, storedb, xkey);\n \n if ~force_gradient\n df0 = getDirectionalDerivative(problem, x, d, storedb, xkey);\n else\n grad = getGradient(problem, x, storedb, xkey);\n df0 = problem.M.inner(x, grad, d);\n end\n \n % Pick a stepping function: exponential or retraction?\n if isfield(problem.M, 'exp')\n stepper = problem.M.exp;\n else\n stepper = problem.M.retr;\n % No need to issue a warning: to check the gradient, any retraction\n % (which is first-order by definition) is appropriate.\n end\n \n % Compute the value of f at points on the geodesic (or approximation\n % of it) originating from x, along direction d, for stepsizes in a\n % large range given by h.\n h = logspace(-8, 0, 51);\n value = zeros(size(h));\n for k = 1 : length(h)\n y = stepper(x, d, h(k));\n ykey = storedb.getNewKey();\n value(k) = getCost(problem, y, storedb, ykey);\n storedb.remove(ykey); % no need to keep it in memory\n end\n \n % Compute the linear approximation of the cost function using f0 and\n % df0 at the same points.\n model = polyval([df0 f0], h);\n \n % Compute the approximation error\n err = abs(model - value);\n \n % And plot it.\n loglog(h, err);\n title(sprintf(['Directional derivative check.\\nThe slope of the '...\n 'continuous line should match that of the dashed\\n'...\n '(reference) line over at least a few orders of '...\n 'magnitude for h.']));\n xlabel('h');\n ylabel('Approximation error');\n \n line('xdata', [1e-8 1e0], 'ydata', [1e-8 1e8], ...\n 'color', 'k', 'LineStyle', '--', ...\n 'YLimInclude', 'off', 'XLimInclude', 'off');\n \n \n if ~all( err < 1e-12 )\n % In a numerically reasonable neighborhood, the error should\n % decrease as the square of the stepsize, i.e., in loglog scale,\n % the error should have a slope of 2.\n isModelExact = false;\n window_len = 10;\n [range, poly] = identify_linear_piece(log10(h), log10(err), window_len);\n else\n % The 1st order model is exact: all errors are (numerically) zero\n % Fit line from all points, use log scale only in h.\n isModelExact = true;\n range = 1:numel(h);\n poly = polyfit(log10(h), err, 1);\n % Set mean error in log scale for plot.\n poly(end) = log10(poly(end));\n % Change title to something more descriptive for this special case.\n title(sprintf(...\n ['Directional derivative check.\\n'...\n 'It seems the linear model is exact:\\n'...\n 'Model error is numerically zero for all h.']));\n end\n hold all;\n loglog(h(range), 10.^polyval(poly, log10(h(range))), 'LineWidth', 3);\n hold off;\n \n if ~isModelExact\n fprintf('The slope should be 2. It appears to be: %g.\\n', poly(1));\n fprintf(['If it is far from 2, then directional derivatives ' ...\n 'might be erroneous.\\n']);\n else\n fprintf(['The linear model appears to be exact ' ...\n '(within numerical precision),\\n'...\n 'hence the slope computation is irrelevant.\\n']);\n end\n \n if ~(isreal(value) && isreal(f0))\n fprintf(['# The cost function appears to return complex values' ...\n '.\\n# Please ensure real outputs.\\n']);\n end\n \nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/tools/checkdiff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.6891477692921465}} {"text": "function [out] = saturation_2(S,Smax,p1,In)\n%saturation_2 \n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% Flux function\n% ------------------\n% Description: Saturation excess from a store with different degrees of saturation\n% Constraints: 1-S/Smax >= 0 prevents numerical issues with complex\n% numbers\n% @(Inputs): S - current storage [mm]\n% Smax - maximum contributing storage [mm]\n% p1 - non-linear scaling parameter [-]\n% In - incoming flux [mm/d]\n\n% NOTE: When stores are very slightly below or over their maximum, the\n% exponent can push this function into regions where no feasible solutions\n% exist. The min(max()) combination prevents this from happening. \n\nout = (1- min(1,max(0,(1-S./Smax))).^p1) .*In;\n\nend\n\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Flux files/saturation_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.689141756970963}} {"text": "function M = multinomialfactory(n, m)\n% Manifold of n-by-m column-stochastic matrices with positive entries.\n%\n% function M = multinomialfactory(n, m)\n%\n% The returned structure M is a Manopt manifold structure to optimize over\n% the set of n-by-m matrices with (strictly) positive entries and such that\n% the entries of each column sum to one.\n%\n% The metric imposed on the manifold is the Fisher metric such that \n% the set of n-by-m column-stochastic matrices (aka the multinomial manifold)\n% is a Riemannian submanifold of the space of n-by-m matrices. Also it\n% should be noted that the retraction operation that we define \n% is first order and as such the checkhessian tool cannot verify \n% the slope correctly.\n% \n% The file is based on developments in the research paper\n% Y. Sun, J. Gao, X. Hong, B. Mishra, and B. Yin,\n% \"Heterogeneous tensor decomposition for clustering via manifold\n% optimization\", arXiv:1504.01777, 2015.\n%\n% Link to the paper: http://arxiv.org/abs/1504.01777.\n%\n% Please cite the Manopt paper as well as the research paper:\n% @Techreport{sun2014multinomial,\n% Title = {Heterogeneous tensor decomposition for clustering via manifold optimization},\n% Author = {Sun, Y. and Gao, J. and Hong, X. and Mishra, B. and Yin, B.},\n% Journal = {Arxiv preprint arXiv:1504.01777},\n% Year = {2014}\n% }\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Bamdev Mishra, April 06, 2015.\n% Contributors:\n% Change log:\n \n M.name = @() sprintf('%dx%d column-stochastic matrices with positive entries', n, m);\n \n M.dim = @() (n-1)*m;\n \n % We impose the Fisher metric.\n M.inner = @iproduct;\n function ip = iproduct(X, eta, zeta)\n ip = sum((eta(:).*zeta(:))./X(:));\n end\n \n M.norm = @(X, eta) sqrt(M.inner(X, eta, eta));\n \n M.dist = @(X, Y) error('multinomialfactory.dist not implemented yet.');\n \n M.typicaldist = @() m*pi/2; % This is an approximation.\n \n % Column vector of ones of length n. \n e = ones(n, 1);\n \n M.egrad2rgrad = @egrad2rgrad;\n function rgrad = egrad2rgrad(X, egrad)\n lambda = -sum(X.*egrad, 1); % Row vector of length m.\n rgrad = X.*egrad + (e*lambda).*X; % This is in the tangent space.\n end\n \n M.ehess2rhess = @ehess2rhess;\n function rhess = ehess2rhess(X, egrad, ehess, eta)\n \n % Riemannian gradient computation.\n % lambda is a row vector of length m.\n lambda = - sum(X.*egrad, 1);\n rgrad = X.*egrad + (e*lambda).*X;\n \n % Directional derivative of the Riemannian gradient.\n % lambdadot is a row vector of length m.\n lambdadot = -sum(eta.*egrad, 1) - sum(X.*ehess, 1); \n rgraddot = eta.*egrad + X.*ehess + (e*lambdadot).*X + (e*lambda).*eta;\n \n % Correction term because of the non-constant metric that we\n % impose. The computation of the correction term follows the use of\n % Koszul formula.\n correction_term = - 0.5*(eta.*rgrad)./X;\n rhess = rgraddot + correction_term;\n \n % Finally, projection onto the tangent space.\n rhess = M.proj(X, rhess);\n end\n \n % Projection of the vector eta in the ambeint space onto the tangent\n % space.\n M.proj = @projection;\n function etaproj = projection(X, eta)\n alpha = sum(eta, 1); % Row vector of length m.\n etaproj = eta - (e*alpha).*X;\n end\n \n M.tangent = M.proj;\n M.tangent2ambient = @(X, eta) eta;\n \n M.retr = @retraction;\n function Y = retraction(X, eta, t)\n if nargin < 3\n t = 1.0;\n end\n % A first-order retraction.\n Y = X.*exp(t*(eta./X)); % Based on mapping for positive scalars.\n Y = Y./(e*(sum(Y, 1))); % Projection onto the constraint set.\n % For numerical reasons, so that we avoid entries going to zero:\n Y = max(Y, eps);\n end\n \n M.exp = @exponential;\n function Y = exponential(X, eta, t)\n if nargin < 3\n t = 1.0;\n end\n Y = retraction(X, eta, t);\n warning('manopt:multinomialfactory:exp', ...\n ['Exponential for the Multinomial manifold' ...\n 'manifold not implemented yet. Used retraction instead.']);\n end\n \n M.hash = @(X) ['z' hashmd5(X(:))];\n \n M.rand = @random;\n function X = random()\n % A random point in the ambient space.\n X = rand(n, m); %\n X = X./(e*(sum(X, 1)));\n end\n \n M.randvec = @randomvec;\n function eta = randomvec(X)\n % A random vector in the tangent space\n eta = randn(n, m);\n eta = M.proj(X, eta); % Projection onto the tangent space.\n nrm = M.norm(X, eta);\n eta = eta / nrm;\n end\n \n M.lincomb = @matrixlincomb;\n \n M.zerovec = @(X) zeros(n, m);\n \n M.transp = @(X1, X2, d) projection(X2, d);\n \n % vec and mat are not isometries, because of the scaled metric.\n M.vec = @(X, U) U(:);\n M.mat = @(X, u) reshape(u, n, m);\n M.vecmatareisometries = @() false;\nend\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/manopt/manopt/manifolds/multinomial/multinomialfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367524, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6891417559167666}} {"text": "function [output_signal,output_time] = mvstat(Inputdata_signal,Inputdata_time,windowrange,reductionrange,fn)\n%------------ Introduction ----------------------\n%This file is created to calculate the mathematical operation like 'max' \n%on a pre-defined window range and with a pre-defined reduction range of an vector data.\n%This function will need the following inputs in order to calculate the\n%wished results:\n% 1- Inputdata_signal: A vector containg your Y-Values that need to be\n% filtered.\n% 2- Inputdata_time: A vector containg your x-Values that need to be\n% filtered (Normally is a time signal where the sampling rate can be\n% extracted).\n% 3- windowrange: in unit of time (s) is the range to calculate the needed\n% mathematical function (The moving range ex. mvmean(y,x,0.02,0.02) or mvrms(y,x,0.02,0.02))\n% 4- reductionrange: in unit of time (s) is the scalling reference for\n% the new data\n% 5- fn : is used to define the wished mathmatical operation (ex. @max, @min, @mean, @rms, @int)\n%The relation between the windowrange input and the reductionrange input \n%must be an integer value of 1:1.2:1..10:1. If not the reductionrange would \n%be corrected to get one of those relation. this specification give us the \n%possibility to calculate the 'mvstat_final' without using a for-Loop which will save a whole amount of time\n% for example:\n% fn = @mean\n% [output_signal,out_put_time] = mvstat_final (y,x,10,10)\n% the moving average will be calculated as a result of this function. every\n% 10 s the mean value for the last 10 s will be calculated.\n% fn = @max\n% [output_signal,out_put_time] = mvstat_final (y,x,20,10)\n% the moving max will be calculated as a result of this function. every\n% 10 s the maximum value for the last 20 s will be calculated.\n% fn = @min\n% [output_signal,out_put_time] = mvstat_final (y,x,5,10)\n% the moving min will be calculated as a result of this function. every\n% 10 s the minmum value for the last 5 s will be calculated.\n%Notice: when the input values of windowrange and reductionrange are not\n%the same then at the beginning of the calculation the fn value of the a\n%available data will be calculated.\n% Is m.file will also allows you to calculate the intgration of your input\n% data in a spesific windowrange. in this case the reductionrange input\n% should be defined as in the example:\n%fn = @int;\n%[Ua_sin,Ua_sin_time] = mvstat(Ua_sin,U1_time,(1/f_grid),delta_t,fn); Ua_sin = Ua_sin*2*f_grid;\n% in this example the integration of your input data (in this case U1_sin)\n% will be calculated ever one period (normally this mean 0.02 s or 1/50 or\n% 1/f_grid in our case). and then the reductionrange is in this case equal\n% to the sampling time of the inputdata (delta = U1_time(2)-U1_time(1)).\n% this work was done in order to bring FAMOS (IMC) software function into\n% matlab.\n%Auther: Msc.Eng. Aubai Alkhatib\n%Datum: 10.09.2013\n%-------- End of introduction ------------------\ndelta = Inputdata_time(2)-Inputdata_time(1);\nlength_window = windowrange/delta;\nlength_reduction = reductionrange/delta;\ntime = Inputdata_time(end);\nif windowrange > reductionrange\n number = windowrange/reductionrange;\n integer = floor(number);\n fract = number-integer;\n if fract >= 0.5\n A = windowrange/(integer+1);\n else\n A = windowrange/(integer);\n end\n reductionrange_new = A;\n integer_A = floor(A);\n fract_A = A-integer_A;\n [~,b] = rat(A);\n if b > 1\n length_reduction_new = round(reductionrange_new/delta);\n else\n length_reduction_new = reductionrange_new/delta;\n end\n i = length_reduction_new;\n ii = 1;\n output = zeros();\n while i < length(Inputdata_signal)\n if i >= length_window\n if fract_A == 0\n switch func2str(fn)\n case 'mean'\n output(ii) = mean(Inputdata_signal((i-length_window)+1:i));\n case 'max'\n output(ii) = max(Inputdata_signal((i-length_window)+1:i));\n case 'sum'\n output(ii) = sum(Inputdata_signal((i-length_window)+1:i));\n case 'min'\n output(ii) = min(Inputdata_signal((i-length_window)+1:i));\n case 'int'\n output(ii) = sum(Inputdata_signal((i-length_window)+1:i))*reductionrange_new;\n otherwise\n output(ii) = rms(Inputdata_signal((i-length_window)+1:i));\n end\n else\n switch func2str(fn)\n case 'mean'\n output(ii) = mean(Inputdata_signal((i-length_window):i));\n case 'max'\n output(ii) = max(Inputdata_signal((i-length_window):i));\n case 'sum'\n output(ii) = sum(Inputdata_signal((i-length_window):i));\n case 'min'\n output(ii) = min(Inputdata_signal((i-length_window):i));\n case 'int'\n output(ii) = sum(Inputdata_signal((i-length_window)+1:i))*reductionrange_new;\n otherwise\n output(ii) = rms(Inputdata_signal((i-length_window):i));\n end\n end\n else\n switch func2str(fn)\n case 'mean'\n output(ii) = mean(Inputdata_signal(1:i));\n case 'max'\n output(ii) = max(Inputdata_signal(1:i));\n case 'sum'\n output(ii) = sum(Inputdata_signal(1:i));\n case 'int'\n output(ii) = sum(Inputdata_signal(1:i))*reductionrange_new;\n case 'min'\n output(ii) = min(Inputdata_signal(1:i));\n otherwise\n output(ii) = rms(Inputdata_signal(1:i));\n end\n end\n i = i + length_reduction_new;\n ii = ii + 1;\n end\n \n if strcmp(func2str(fn),'int')\n output_signal = output(length_window:length(output));\n output_time = windowrange:reductionrange_new:(length(output)*reductionrange_new);\n elseif isinteger(reductionrange_new)\n output_signal = output;\n output_time = 0:reductionrange_new:(length(output)*reductionrange_new)-reductionrange_new;\n else\n output_signal = output;\n output_time = 0:(length_reduction_new*delta):(length(output)*(length_reduction_new*delta))-(length_reduction_new*delta);\n end\nelseif reductionrange > windowrange\n Length_Output = fix(time/windowrange);\n Length_Input_New = Length_Output*windowrange/delta;\n delta_new = length_window;\n delta_time = windowrange;\n Input_reshaped = reshape(Inputdata_signal(1:Length_Input_New),delta_new,Length_Input_New/delta_new);\n switch func2str(fn)\n case 'mean'\n output_signal = mean(Input_reshaped);\n case 'max'\n output_signal = max(Input_reshaped);\n case 'sum'\n output_signal = sum(Input_reshaped);\n case 'int'\n output = sum(Input_reshaped)*delta_time;\n case 'min'\n output_signal = min(Input_reshaped);\n otherwise\n output_signal = rms(Input_reshaped);\n end\n if strcmp(func2str(fn),'int')\n output_signal = output(length_window:length(output));\n output_time = windowrange:delta_time:(Length_Output*delta_time)-delta_time;\n else\n output_time = 0:delta_time:(Length_Output*delta_time)-delta_time;\n end\nelseif windowrange == reductionrange\n Length_Output = fix(time/windowrange);\n Length_Input_New = Length_Output*reductionrange/delta;\n delta_new = length_reduction;\n delta_time = windowrange;\n Input_reshaped = reshape(Inputdata_signal(1:Length_Input_New),delta_new,Length_Input_New/delta_new);\n switch func2str(fn)\n case 'mean'\n output_signal = mean(Input_reshaped);\n case 'max'\n output_signal = max(Input_reshaped);\n case 'sum'\n output_signal = sum(Input_reshaped);\n case 'int'\n output = sum(Input_reshaped)*delta_time;\n case 'min'\n output_signal = min(Input_reshaped);\n otherwise\n output_signal = rms(Input_reshaped);\n end\n if strcmp(func2str(fn),'int')\n output_signal = output(length_window:length(output));\n output_time = windowrange:delta_time:(Length_Output*delta_time)-delta_time;\n else\n output_time = 0:delta_time:(Length_Output*delta_time)-delta_time;\n end\nend\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/43536-ieccalculation/To Matlab/mvstat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6891417374855204}} {"text": "%[2015]-\"TSA: Tree-seed algorithm for continuous optimization\"\n\n% (9/12/2020)\n\nfunction TSA = jTreeSeedAlgorithm(feat,label,opts)\n% Parameters\nlb = 0;\nub = 1; \nthres = 0.5; \nST = 0.1; % switch probability\n\nif isfield(opts,'T'), max_Iter = opts.T; end\nif isfield(opts,'N'), N = opts.N; end\nif isfield(opts,'ST'), ST = opts.ST; end \nif isfield(opts,'thres'), thres = opts.thres; end\n\n% Objective function\nfun = @jFitnessFunction;\n% Number of dimensions\ndim = size(feat,2); \n% Initial (5)\nX = zeros(N,dim); \nfor i = 1:N\n for d = 1:dim\n X(i,d) = lb + (ub - lb) * rand();\n end \nend\n% Fitness\nfit = zeros(1,N); \nfor i = 1:N \n fit(i) = fun(feat,label,(X(i,:) > thres),opts);\nend\n% Best solution (6)\n[fitG, idx] = min(fit);\nXgb = X(idx,:);\n% Maximum & minimum number of seed\nSmax = round(0.25 * N); \nSmin = round(0.1 * N);\n% Pre\ncurve = zeros(1,max_Iter);\ncurve(1) = fitG;\nt = 2;\n% Iteration\nwhile t <= max_Iter\n for i = 1:N\n % Random number of seed\n num_seed = round(Smin + rand()* (Smax - Smin)); \n Xnew = zeros(num_seed, dim);\n for j = 1:num_seed\n % Random select a tree, but not i\n RN = randperm(N); \n RN(RN == i) = []; \n r = RN(1);\n for d = 1:dim\n % Alpha in [-1,1]\n alpha = -1 + 2 * rand();\n if rand() < ST \n % Generate seed (3)\n Xnew(j,d) = X(i,d) + alpha * (Xgb(d) - X(r,d));\n else\n % Generate seed (4)\n Xnew(j,d) = X(i,d) + alpha * (X(i,d) - X(r,d));\n end\n end\n % Boundary\n XB = Xnew(j,:); XB(XB > ub) = ub; XB(XB < lb) = lb;\n Xnew(j,:) = XB;\n end\n % Fitness\n for j = 1:num_seed\n % Fitness\n Fnew = fun(feat,label,(Xnew(j,:) > thres),opts);\n % Greedy selection\n if Fnew < fit(i)\n fit(i) = Fnew;\n X(i,:) = Xnew(j,:);\n end\n end\n end\n % Best solution (6)\n [fitG_new, idx] = min(fit);\n Xgb_new = X(idx,:);\n % Best update\n if fitG_new < fitG\n fitG = fitG_new;\n Xgb = Xgb_new;\n end\n % Store \n curve(t) = fitG;\n fprintf('\\nIteration %d Best (TSA)= %f',t,curve(t))\n t = t + 1;\nend\n% Select features\nPos = 1:dim; \nSf = Pos((Xgb > thres) == 1); \nsFeat = feat(:,Sf);\n% Store results\nTSA.sf = Sf;\nTSA.ff = sFeat; \nTSA.nf = length(Sf); \nTSA.c = curve; \nTSA.f = feat;\nTSA.l = label;\nend\n\n\n\n\n\n", "meta": {"author": "JingweiToo", "repo": "Wrapper-Feature-Selection-Toolbox", "sha": "91b050142f331d2a58f7127aba91356b397379b3", "save_path": "github-repos/MATLAB/JingweiToo-Wrapper-Feature-Selection-Toolbox", "path": "github-repos/MATLAB/JingweiToo-Wrapper-Feature-Selection-Toolbox/Wrapper-Feature-Selection-Toolbox-91b050142f331d2a58f7127aba91356b397379b3/jTreeSeedAlgorithm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.689090053878894}} {"text": "%QUESTION NO:4\n\n%For the following 2-class problem determine the decision boundaries\n%obtained by LMS and perceptron learning laws.\n% Class C1 : [-2 2]', [-2 3]', [-1 1]', [-1 4]', [0 0]', [0 1]', [0 2]', \n% [0 3]' and [1 1]'\n% Class C2 : [ 1 0]', [2 1]', [3 -1]', [3 1]', [3 2]', [4 -2]', [4 1]',\n% [5 -1]' and [5 0]'\n\nclear;\ninp=[-2 -2 -1 -1 0 0 0 0 1 1 2 3 3 3 4 4 5 5;2 3 1 4 0 1 2 3 1 0 1 -1 1 2 -2 1 -1 0];\nout=[1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0];\nchoice=input('1: Perceptron Learning Law\\n2: LMS Learning Law\\n Enter your choice :');\nswitch choice\n case 1\n network=newp([-2 5;-2 4],1);\n network=init(network);\n y=sim(network,inp);\n figure,plot(inp,out,inp,y,'o'),title('Before Training');\n axis([-10 20 -2.0 2.0]);\n network.trainParam.epochs = 20;\n network=train(network,inp,out);\n y=sim(network,inp);\n figure,plot(inp,out,inp,y,'o'),title('After Training');\n axis([-10 20 -2.0 2.0]);\n display('Final weight vector and bias values : \\n');\n Weights=network.iw{1};\n Bias=network.b{1};\n Weights\n Bias\n Actual_Desired=[y' out'];\n Actual_Desired\n case 2\n network=newlin([-2 5;-2 4],1);\n network=init(network);\n y=sim(network,inp);\n network=adapt(network,inp,out);\n y=sim(network,inp);\n display('Final weight vector and bias values : \\n');\n Weights=network.iw{1};\n Bias=network.b{1};\n Weights\n Bias\n Actual_Desired=[y' out'];\n Actual_Desired\n otherwise \n error('Wrong Choice');\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/14489-neural-network-programs/programs/perceptLMS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.6890900469536911}} {"text": "function [tfr,t,f] = tfrmhs(x,t,N,g,h,trace);\n%TFRMHS\tMargenau-Hill-Spectrogram time-frequency distribution.\n%\t[TFR,T,F]=TFRMHS(X,T,N,G,H,TRACE) computes the Margenau-Hill-Spectrogram \n%\tdistribution of a discrete-time signal X, or the cross\n%\tMargenau-Hill-Spectrogram representation between two signals. \n% \n%\tX : Signal if auto-MHS, or [X1,X2] if cross-MHS.\n%\tT : time instant(s) (default : 1:length(X)).\n%\tN : number of frequency bins (default : length(X)).\n%\tG,H : analysis windows, normalized so that the representation \n% preserves the signal energy.\n%\t (default : Hamming(N/10) and Hamming(N/4)). \n%\tTRACE : if nonzero, the progression of the algorithm is shown\n% (default : 0).\n%\tTFR : time-frequency representation. When called without \n% output arguments, TFRMHS runs TFRQVIEW.\n%\tF : vector of normalized frequencies.\n%\n%\tExample:\n%\t sig=fmlin(128,0.1,0.4); g=tftb_window(21,'Kaiser'); \n%\t h=tftb_window(63,'Kaiser'); tfrmhs(sig,1:128,64,g,h,1);\n% \n%\tSee also all the time-frequency representations listed in\n%\t the file CONTENTS (TFR*)\n\n%\tF. Auger, May-August 1994, July 1995.\n%\tCopyright (c) 1996 by CNRS (France).\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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nif (nargin == 0),\n error('At least 1 parameter required');\nend;\n[xrow,xcol] = size(x);\nif (xcol==0)|(xcol>2),\n error('X must have one or two columns');\nend\n\nif (nargin <= 2),\n N=xrow;\nelseif (N<0),\n error('N must be greater than zero');\nelseif (2^nextpow2(N)~=N),\n fprintf('For a faster computation, N should be a power of two\\n');\nend;\n\nhlength=floor(N/4); hlength=hlength+1-rem(hlength,2); \nglength=floor(N/10);glength=glength+1-rem(glength,2);\n\nif (nargin == 1),\n t=1:xrow; g = tftb_window(glength); h = tftb_window(hlength); trace = 0;\nelseif (nargin == 2)|(nargin == 3),\n g = tftb_window(glength); h = tftb_window(hlength); trace = 0;\nelseif (nargin == 4),\n h = tftb_window(hlength); trace = 0;\nelseif (nargin == 5),\n trace = 0;\nend;\n\n[trow,tcol] = size(t);\nif (trow~=1),\n error('T must only have one row'); \nend; \n\n[grow,gcol]=size(g); Lg=(grow-1)/2;\nif (gcol~=1)|(rem(grow,2)==0),\n error('G must be a smoothing window with odd length'); \nend;\n\n[hrow,hcol]=size(h); Lh=(hrow-1)/2; h=h/h(Lh+1);\nif (hcol~=1)|(rem(hrow,2)==0),\n error('H must be a smoothing window with odd length');\nend;\n\nLgh=min(Lg,Lh); points=-Lgh:Lgh; \nKgh=sum(h(Lh+1+points).*conj(g(Lg+1+points))); h=h/Kgh;\n\ntfr= zeros (N,tcol); tfr2= zeros(N,tcol);\nif trace, disp('Pseudo Margenau-Hill distribution'); end;\nfor icol=1:tcol,\n ti= t(icol);\n if trace, disprog(icol,tcol,10); end;\n tau=-min([round(N/2)-1,Lg,ti-1]):min([round(N/2)-1,Lg,xrow-ti]);\n indices= rem(N+tau,N)+1;\n tfr(indices,icol)=x(ti+tau,1).*conj(g(Lg+1+tau));\n tau=-min([round(N/2)-1,Lh,ti-1]):min([round(N/2)-1,Lh,xrow-ti]);\n indices= rem(N+tau,N)+1;\n tfr2(indices,icol)=x(ti+tau,xcol).*conj(h(Lh+1+tau));\nend; \nif trace, fprintf('\\n'); end;\ntfr=real(fft(tfr).*conj(fft(tfr2))); \n\nif (nargout==0),\n tfrqview(tfr,x,t,'tfrmhs',g,h);\nelseif (nargout==3),\n if rem(N,2)==0, \n f=[0:N/2-1 -N/2:-1]'/N;\n else\n f=[0:(N-1)/2 -(N-1)/2:-1]'/N; \n end;\nend;\n\n\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/mfiles/tfrmhs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.6890717018064334}} {"text": "function vu = burgers_solution ( nu, vxn, vx, vtn, vt )\n\n%*****************************************************************************80\n%\n%% BURGERS_SOLUTION evaluates a solution to the Burgers equation.\n%\n% Discussion:\n%\n% The form of the Burgers equation considered here is\n%\n% du du d^2 u\n% -- + u * -- = nu * -----\n% dt dx dx^2\n%\n% for -1.0 < x < +1.0, and 0 < t.\n%\n% Initial conditions are u(x,0) = - sin(pi*x). Boundary conditions\n% are u(-1,t) = u(+1,t) = 0. The viscosity parameter nu is taken\n% to be 0.01 / pi, although this is not essential.\n%\n% The authors note an integral representation for the solution u(x,t),\n% and present a better version of the formula that is amenable to\n% approximation using Hermite quadrature.\n%\n% This program library does little more than evaluate the exact solution\n% at a user-specified set of points, using the quadrature rule.\n% Internally, the order of this quadrature rule is set to 8, but the\n% user can easily modify this value if greater accuracy is desired.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 November 2011\n%\n% Author:\n%\n% John Burkardt.\n%\n% Reference:\n%\n% Claude Basdevant, Michel Deville, Pierre Haldenwang, J Lacroix,\n% J Ouazzani, Roger Peyret, Paolo Orlandi, Anthony Patera,\n% Spectral and finite difference solutions of the Burgers equation,\n% Computers and Fluids,\n% Volume 14, Number 1, 1986, pages 23-41.\n%\n% Parameters:\n%\n% Input, real NU, the viscoscity.\n%\n% Input, integer VXN, the number of spatial grid points.\n%\n% Input, real VX(VXN), the spatial grid points.\n%\n% Input, integer VTN, the number of time grid points.\n%\n% Input, real VT(VTN), the time grid points.\n%\n% Output, real VU(VXN,VTN), the solution of the Burgers\n% equation at each space and time grid point.\n%\n qn = 8;\n%\n% Compute the rule.\n%\n [ qx, qw ] = hermite_ek_compute ( qn );\n%\n% Evaluate U(X,T) for later times.\n%\n vu = zeros ( vxn, vtn );\n\n for vti = 1 : vtn\n\n if ( vt(vti) == 0.0 )\n\n vu(1:vxn,vti) = - sin ( pi * vx(1:vxn) );\n\n else\n\n for vxi = 1 : vxn\n\n top = 0.0;\n bot = 0.0;\n\n for qi = 1 : qn\n\n c = 2.0 * sqrt ( nu * vt(vti) );\n\n top = top - qw(qi) * c * sin ( pi * ( vx(vxi) - c * qx(qi) ) ) ...\n * exp ( - cos ( pi * ( vx(vxi) - c * qx(qi) ) ) ...\n / ( 2.0 * pi * nu ) );\n\n bot = bot + qw(qi) * c ...\n * exp ( - cos ( pi * ( vx(vxi) - c * qx(qi) ) ) ...\n / ( 2.0 * pi * nu ) );\n\n vu(vxi,vti) = top / bot;\n\n end\n\n end\n\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/burgers_solution/burgers_solution.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.6890716781319318}} {"text": "function [out] = smoothThreshold_temperature_logistic(T,Tt,r)\n%smoothThreshold_temperature_logistic Logisitic smoother for temperature threshold functions.\n\n% Copyright (C) 2018 Wouter J.M. Knoben\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% Smooths the transition of threshold functions of the form:\n%\n% Snowfall = { P, if T < Tt\n% { 0, if T >= Tt\n%\n% By transforming the equation above to Sf = f(P,T,Tt,r):\n% Sf = P * 1/ (1+exp((T-Tt)/r))\n%\n% Inputs:\n% P : current precipitation\n% T : current temperature\n% Tt : threshold temperature below which snowfall occurs\n% r : [optional] smoothing parameter rho, default = 0.01\n%\n% NOTE: this function only outputs the multiplier. This needs to be\n% applied to the proper flux utside of this function.\n\n% Check for inputs and use defaults if not provided\n% NOTE: this is not very elegant, but it is more than a factor 10 faster then: \n% if ~exist('r','var'); r = 0.01; end\nif nargin == 2\n r = 0.01;\nend\n\n% Calculate multiplier\nout = 1 ./ (1+exp((T-Tt)/(r)));\n\nend\n\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Functions/Flux smoothing/smoothThreshold_temperature_logistic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6889909957646506}} {"text": "function beta = linearCompressibility(S,x)\n% computes the linear compressibility of an elasticity tensor\n%\n% Description\n%\n% $$\\beta(x) = S_{ijkk} x_i x_j$$\n%\n% Input\n% S - elastic @complianceTensor\n% x - list of @vector3d\n%\n% Output\n% beta - linear compressibility in directions v\n%\n\n% return a function if required\nif nargin == 1 || isempty(x)\n beta = S2FunHarmonicSym.quadrature(@(x) linearCompressibility(S,x),'bandwidth',2,S.CS);\n return\nend\n\n% compute tensor product\nbeta = EinsteinSum(S,[-1 -2 -3 -3],x,-1,x,-2);\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/TensorAnalysis/@complianceTensor/linearCompressibility.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6889909936932561}} {"text": "function x = from_array(A,opt)\n %FROM_ARRAY Approximate full array by TTeMPS tensor of prescribed rank \n % or within a prescribed tolerance.\n %\n % X = TTeMPS.from_array( A, tol ) approximates the given array A by a\n % TTeMPS tensor such that the the error is in the order of tol.\n %\n % X = TTeMPS.from_array( A, r ), with r a vector of length (ndims(A))+1),\n % approximates the given array A by a rank-r TTeMPS tensor, such that \n % X.rank = r.\n % \n\n % TTeMPS Toolbox. \n % Michael Steinlechner, 2013-2016\n % Questions and contact: michael.steinlechner@epfl.ch\n % BSD 2-clause license, see LICENSE.txt\n\n n = size(A);\n d = length(n);\n\n if length(opt) == 1\n useTol = true;\n tol = opt;\n r = ones(1,d+1);\n else\n useTol = false;\n r = opt;\n if r(1) ~= 1 || r(d+1) ~= 1\n error('Invalid rank specified')\n end\n end\n\n U = cell(1,d);\n\n % process from left to right\n % first core\n A = reshape( A, n(1), prod(n(2:end)));\n [u,s,v] = svd(A,'econ');\n if useTol\n r(2) = trunc_singular( diag(s), tol );\n end\n U{1} = reshape( u(:,1:r(2)), [1, n(1), r(2)] );\n A = s(1:r(2),1:r(2))*v(:,1:r(2))';\n\n % middle cores\n for i = 2:d-1\n A = reshape( A, n(i)*r(i), prod(n(i+1:end)));\n [u,s,v] = svd(A,'econ');\n if useTol\n r(i+1) = trunc_singular( diag(s), tol );\n end\n U{i} = reshape( u(:,1:r(i+1)), [r(i), n(i), r(i+1)] );\n A = s(1:r(i+1),1:r(i+1)) * v(:,1:r(i+1))';\n end\n\n %last core\n U{d} = reshape(A, [r(d), n(d), 1]);\n\n x = TTeMPS( U );\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/ttfixedrank/TTeMPS_1.1/@TTeMPS/from_array.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605411, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6889909847516502}} {"text": "function circle_segment_test05 ( )\n\n%*****************************************************************************80\n%\n%% CIRCLE_SEGMENT_TEST05 tests the AREA and HEIGHT_FROM_AREA functions.\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 fprintf ( 1, '\\n' );\n fprintf ( 1, 'CIRCLE_SEGMENT_TEST05\\n' );\n fprintf ( 1, ' For circle segment with a given radius R,\\n' );\n fprintf ( 1, ' CIRCLE_SEGMENT_AREA_FROM_HEIGHT computes the area A, given the height.\\n' );\n fprintf ( 1, ' CIRCLE_SEGMENT_HEIGHT_FROM_AREA computes height H, given the area.\\n' );\n fprintf ( 1, ' Check that these functions are inverses of each other\\n' );\n fprintf ( 1, ' using random values of R, A, and H.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' R H => A => H2\\n' );\n fprintf ( 1, '\\n' );\n\n seed = 123456789;\n\n for test = 1 : 5\n [ r, seed ] = r8_uniform_01 ( seed );\n r = 5.0 * r;\n [ h, seed ] = r8_uniform_01 ( seed );\n h = 2.0 * r * h;\n a = circle_segment_area_from_height ( r, h );\n h2 = circle_segment_height_from_area ( r, a );\n fprintf ( 1, ' %12f %12f %12f %12f\\n', r, h, a, h2 );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' R A => H => A2\\n' );\n fprintf ( 1, '\\n' );\n for test = 1 : 5\n [ r, seed ] = r8_uniform_01 ( seed );\n r = 5.0 * r;\n [ a, seed ] = r8_uniform_01 ( seed );\n a = pi * r * r * a;\n h = circle_segment_height_from_area ( r, a );\n a2 = circle_segment_area_from_height ( r, h );\n fprintf ( 1, ' %12f %12f %12f %12f\\n', r, a, h, a2 );\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_test05.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.6889667362361817}} {"text": "function [peakVals,isMax,peakIdx]=findMaxMinPoints(data)\n%%FINDMAXMINPOINTS Given a grid of points in one or more dimensions, this\n% function finds all maxima and minima. A maximum/minimum\n% is declared if the point in question is higher/lower\n% than all neighboring points (including those diagonally\n% offset). Points at the edge of the matrix are not\n% considered to be maxima or minima.\n%\n%INPUTS: data An n1Xn2X...Xnk dimensional matrix. Singleton dimensions\n% (ni=1) are ignored. Non-singleton dimensions must be > 2. to\n% consider points that are not on the edge. data must be a real\n% matrix.\n%\n%OUTPUTS: peakVals A numValsX1 vector of the maximum and minimum values\n% found. If no values are found, this is an empty matrix. \n% isMax A numValsX1 vector indicating whether each value in\n% peakVals is a maximum or a minimum. 1 indicates maximum,\n% 0 indicated minimum.\n% peakIdx A numValsX1 vector of indices of the peaks such that\n% data(peakIdx(i)) provides the ith peak value.\n%\n%EXAMPLE:\n%This function is useful for finding maxima and minima of cost functions.\n%Here, we find all maxima and minima of a surface.\n% numPoints=100;\n% pts=linspace(0,2*pi,numPoints);\n% [X,Y]=meshgrid(pts,pts);\n% Z=sin(2*X+3*Y)+cos(X-2*Y);\n% %Display the surface whose peaks are desired.\n% figure(1)\n% clf\n% surface(X,Y,Z,'EdgeColor','None')\n% [peakVals,isMax,peakIdx]=findMaxMinPoints(Z)\n%One sees that all 13 of the maxma and minima (-1 and 1) that are found.\n%Values on the edge are not counted for maxma or minima.\n%\n%October 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\ndims=size(data);\n\n%Get rid of singleton dimensions.\ndims=dims(dims~=1);\nif(isempty(dims)||isscalar(dims)&&dims==1||any(dims==2))\n peakVals=[];\n peakIdx=[];\n isMax=[];\n return;\nend\n\nnumDims=length(dims);\nswitch(numDims)\n case 1%Find peaks for linear values. \n peakVals=[];\n peakIdx=[];\n isMax=[];\n for idx1=2:(dims(1)-1)\n curVal=data(idx1);\n \n vals=[curVal-data(idx1-1);\n curVal-data(idx1+1)];\n if(all(vals>0))\n peakVals=[peakVals;curVal];\n peakIdx=[peakIdx;idx1];\n isMax=[isMax;1];\n elseif(all(vals<0))\n peakVals=[peakVals;curVal];\n peakIdx=[peakIdx;idx1];\n isMax=[isMax;0];\n end\n end\n case 2\n data=reshape(data,dims(1),dims(2));\n \n peakVals=[];\n peakIdx=[];\n isMax=[];\n \n for idx1=2:(dims(1)-1)\n for idx2=2:(dims(2)-1)\n curVal=data(idx1,idx2);\n \n vals=[curVal-data(idx1,idx2-1);\n curVal-data(idx1-1,idx2-1);\n curVal-data(idx1+1,idx2-1);\n curVal-data(idx1,idx2+1);\n curVal-data(idx1-1,idx2+1);\n curVal-data(idx1+1,idx2+1);\n curVal-data(idx1-1,idx2);\n curVal-data(idx1+1,idx2)];\n \n %If we have found a maximum or a minimum\n if(all(vals>0))\n peakVals=[peakVals;curVal];\n idx=sub2ind(dims,idx1,idx2);\n peakIdx=[peakIdx;idx];\n isMax=[isMax;1];\n elseif(all(vals<0))\n peakVals=[peakVals;curVal];\n idx=sub2ind(dims,idx1,idx2);\n peakIdx=[peakIdx;idx];\n isMax=[isMax;0];\n end\n end\n end\n otherwise%3 or more dimensions\n maxTupleVals=dims-3;\n \n peakVals=[];\n peakIdx=[];\n isMax=[];\n \n idxList=getNextTuple(numDims);\n while(~isempty(idxList))\n %Points that will be compared to their neighbors are never the\n %edge points. Thus, the minimum value possible for an element\n %is 2 and the maximum value is one less than the number of\n %things in that dimension.\n shiftIdxList=idxList+2;\n \n curIdx=nDim2Index(dims,shiftIdxList);\n curVal=data(curIdx);\n \n %Now, we look at all neighbors of the current point. This means\n %that all points go through all combinations of +1,-1, and 0,\n %except for the all zero case. We can get the values using\n %tuples.\n maxSignVals=2*ones(numDims,1);\n \n signList=getNextTuple(zeros(numDims,1),maxSignVals);\n \n isMax=true;\n isMin=true;\n while(~isempty(signList)&&(isMax==true||isMin==true))\n temp=signList;\n temp(temp==2)=-1;\n\n shiftedIdx=nDim2Index(dims,shiftIdxList+temp);\n compVal=data(shiftedIdx);\n \n if(compVal>=curVal)\n isMax=false; \n end\n \n if(compVal<=curVal)\n isMin=false; \n end\n\n signList=getNextTuple(signList,maxSignVals);\n end\n \n if(~(isMax&&isMin))\n if(isMax)\n peakVals=[peakVals;curVal];\n peakIdx=[peakIdx;curIdx];\n isMax=[isMax;1];\n elseif(isMin)\n peakVals=[peakVals;curVal];\n peakIdx=[peakIdx;curIdx];\n isMax=[isMax;0];\n end\n end\n \n idxList=getNextTuple(idxList,maxTupleVals);\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/Misc/findMaxMinPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.6889667328369636}} {"text": "function adj = triangulation_order3_adj_set ( node_num, ...\n tri_num, triangle_node, triangle_neighbor, adj_num, adj_col )\n\n%*****************************************************************************80\n%\n%% TRIANGULATION_ORDER3_ADJ_SET sets adjacencies in a triangulation.\n%\n% Discussion:\n%\n% This routine is called to count the adjacencies, so that the\n% appropriate amount of memory can be set aside for storage when\n% the adjacency structure is created.\n%\n% The triangulation is assumed to involve 3-node triangles.\n%\n% Two nodes are \"adjacent\" if they are both nodes in some triangle.\n% Also, a node is considered to be adjacent to itself.\n%\n% This routine can be used to create the compressed column storage\n% for a linear triangle finite element discretization of \n% Poisson's equation in two dimensions.\n%\n% Diagram:\n%\n% 3\n% s |\\\n% i | \\\n% d | \\\n% e | \\ side 2\n% | \\\n% 3 | \\\n% | \\\n% 1-------2\n%\n% side 1\n%\n% The local node numbering\n%\n%\n% 21-22-23-24-25\n% |\\ |\\ |\\ |\\ |\n% | \\| \\| \\| \\|\n% 16-17-18-19-20\n% |\\ |\\ |\\ |\\ |\n% | \\| \\| \\| \\|\n% 11-12-13-14-15\n% |\\ |\\ |\\ |\\ |\n% | \\| \\| \\| \\|\n% 6--7--8--9-10\n% |\\ |\\ |\\ |\\ |\n% | \\| \\| \\| \\|\n% 1--2--3--4--5\n%\n% A sample grid\n%\n%\n% Below, we have a chart that summarizes the adjacency relationships\n% in the sample grid. On the left, we list the node, and its neighbors,\n% with an asterisk to indicate the adjacency of the node to itself\n% (in some cases, you want to count this self adjacency and in some\n% you don't). On the right, we list the number of adjancencies to\n% lower-indexed nodes, to the node itself, to higher-indexed nodes,\n% the total number of adjacencies for this node, and the location\n% of the first and last entries required to list this set of adjacencies\n% in a single list of all the adjacencies.\n%\n% N Adjacencies Below Self Above Total First Last\n%\n% -- -- -- -- -- -- -- -- -- -- -- -- --- 0 \n% 1: * 2 6 0 1 2 3 1 3\n% 2: 1 * 3 6 7 1 1 3 5 4 8\n% 3: 2 * 4 7 8 1 1 3 5 9 13\n% 4: 3 * 5 8 9 1 1 3 5 14 18\n% 5: 4 * 9 10 1 1 2 4 19 22\n% 6: 1 2 * 7 11 2 1 2 5 23 27\n% 7: 2 3 6 * 8 11 12 3 1 3 7 28 34\n% 8: 3 4 7 * 9 12 13 3 1 3 7 35 41\n% 9: 4 5 8 * 10 13 14 3 1 3 7 42 48\n% 10: 5 9 * 14 15 2 1 2 5 49 53\n% 11: 6 7 * 12 16 2 1 2 5 54 58\n% 12: 7 8 11 * 13 16 17 3 1 3 7 59 65\n% 13: 8 9 12 * 14 17 18 3 1 3 7 66 72\n% 14: 9 10 13 * 15 18 19 3 1 3 7 73 79\n% 15: 10 14 * 19 20 2 1 2 5 80 84\n% 16: 11 12 * 17 21 2 1 2 5 85 89\n% 17: 12 13 16 * 18 21 22 3 1 3 7 90 96\n% 18: 13 14 17 * 19 22 23 3 1 3 7 97 103\n% 19: 14 15 18 * 20 23 24 3 1 3 7 104 110\n% 20: 15 19 * 24 25 2 1 2 5 111 115\n% 21: 16 17 * 22 2 1 1 4 116 119\n% 22: 17 18 21 * 23 3 1 1 5 120 124\n% 23: 18 19 22 * 24 3 1 1 5 125 129\n% 24: 19 20 23 * 25 3 1 1 5 130 134\n% 25: 20 24 * 2 1 0 3 135 137\n% -- -- -- -- -- -- -- -- -- -- -- -- 138 ---\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 September 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, integer TRI_NUM, the number of triangles.\n%\n% Input, integer TRIANGLE_NODE(3,TRI_NUM), lists the nodes that\n% make up each triangle in counterclockwise order.\n%\n% Input, integer TRIANGLE_NEIGHBOR(3,TRI_NUM), for each side of\n% a triangle, lists the neighboring triangle, or -1 if there is\n% no neighbor.\n%\n% Input, integer ADJ_NUM, the number of adjacencies.\n%\n% Input, integer ADJ_COL(NODE_NUM+1). Information about column J is stored\n% in entries ADJ_COL(J) through ADJ_COL(J+1)-1 of ADJ.\n%\n% Output, integer ADJ(ADJ_NUM), the adjacency information.\n%\n triangle_order = 3;\n adj(1:adj_num) = -1;\n adj_copy(1:node_num) = adj_col(1:node_num);\n%\n% Set every node to be adjacent to itself.\n%\n for node = 1 : node_num\n adj(adj_copy(node)) = node;\n adj_copy(node) = adj_copy(node) + 1;\n end\n%\n% Examine each triangle.\n%\n for triangle = 1 : tri_num\n\n n1 = triangle_node(1,triangle);\n n2 = triangle_node(2,triangle);\n n3 = triangle_node(3,triangle);\n%\n% Add edge (1,2) if this is the first occurrence,\n% that is, if the edge (1,2) is on a boundary (TRIANGLE2 <= 0)\n% or if this triangle is the first of the pair in which the edge\n% occurs (TRIANGLE < TRIANGLE2).\n%\n triangle2 = triangle_neighbor(1,triangle);\n\n if ( triangle2 < 0 | triangle < triangle2 )\n adj(adj_copy(n1)) = n2;\n adj_copy(n1) = adj_copy(n1) + 1;\n adj(adj_copy(n2)) = n1;\n adj_copy(n2) = adj_copy(n2) + 1;\n end\n%\n% Add edge (2,3).\n%\n triangle2 = triangle_neighbor(2,triangle);\n\n if ( triangle2 < 0 | triangle < triangle2 )\n adj(adj_copy(n2)) = n3;\n adj_copy(n2) = adj_copy(n2) + 1;\n adj(adj_copy(n3)) = n2;\n adj_copy(n3) = adj_copy(n3) + 1;\n end\n%\n% Add edge (3,1).\n%\n triangle2 = triangle_neighbor(3,triangle);\n\n if ( triangle2 < 0 | triangle < triangle2 )\n adj(adj_copy(n1)) = n3;\n adj_copy(n1) = adj_copy(n1) + 1;\n adj(adj_copy(n3)) = n1;\n adj_copy(n3) = adj_copy(n3) + 1;\n end\n \n end\n%\n% Ascending sort the entries for each node.\n%\n for node = 1 : node_num\n k1 = adj_col(node);\n k2 = adj_col(node+1)-1;\n adj(k1:k2) = i4vec_sort_heap_a ( k2+1-k1, adj(k1:k2) );\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/triangulation/triangulation_order3_adj_set.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757312, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.6889667276815616}} {"text": "function v2 = r8vec_any_normal ( dim_num, v1 )\n\n%*****************************************************************************80\n%\n%% R8VEC_ANY_NORMAL returns some normal vector to V1.\n%\n% Discussion:\n%\n% If DIM_NUM < 2, then no normal vector can be returned.\n%\n% If V1 is the zero vector, then any unit vector will do.\n%\n% No doubt, there are better, more robust algorithms. But I will take\n% just about ANY reasonable unit vector that is normal to V1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 August 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, real V1(DIM_NUM), the vector.\n%\n% Output, real V2(DIM_NUM), a vector that is\n% normal to V2, and has unit Euclidean length.\n%\n if ( dim_num < 2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8VEC_ANY_NORMAL - Fatal error!\\n' );\n fprintf ( 1, ' Called with DIM_NUM < 2.\\n' );\n error ( 'R8VEC_ANY_NORMAL - Fatal error!' );\n end\n\n if ( r8vec_norm ( dim_num, v1 ) == 0.0 )\n v2(1) = 1.0;\n v2(2:dim_num) = 0.0;\n return\n end\n%\n% Seek the largest entry in V1, VJ = V1(J), and the\n% second largest, VK = V1(K).\n%\n% Since V1 does not have zero norm, we are guaranteed that\n% VJ, at least, is not zero.\n%\n j = -1;\n vj = 0.0;\n\n k = -1;\n vk = 0.0;\n\n for i = 1 : dim_num\n\n if ( abs ( vk ) < abs ( v1(i) ) || k < 1 )\n\n if ( abs ( vj ) < abs ( v1(i) ) || j < 1 )\n k = j;\n vk = vj;\n j = i;\n vj = v1(i);\n else\n k = i;\n vk = v1(i);\n end\n\n end\n\n end\n%\n% Setting V2 to zero, except that V2(J) = -VK, and V2(K) = VJ,\n% will just about do the trick.\n%\n v2(1:dim_num) = 0.0;\n\n v2(j) = -vk / sqrt ( vk * vk + vj * vj );\n v2(k) = vj / sqrt ( vk * vk + vj * vj );\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_any_normal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.6889667241239357}} {"text": "function g = p25_g ( n, x )\n\n%*****************************************************************************80\n%\n%% P25_G evaluates the gradient for problem 25.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 December 2000\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the values of the variables.\n%\n% Output, real G(N), the gradient of the objective function.\n%\n g = zeros ( n, 1 );\n\n for i = 1 : n\n g(i) = i * 4.0 * x(i)^3;\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_opt/p25_g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.6889667102555054}} {"text": "function [pmiss,pfa] = rocch(tar_scores,nontar_scores)\n% ROCCH: ROC Convex Hull.\n% Usage: [pmiss,pfa] = rocch(tar_scores,nontar_scores)\n% (This function has the same interface as compute_roc.)\n%\n% Note: pmiss and pfa contain the coordinates of the vertices of the\n% ROC Convex Hull.\n%\n% For a demonstration that plots ROCCH against ROC for a few cases, just\n% type 'rocch' at the MATLAB command line.\n%\n% Inputs:\n% tar_scores: scores for target trials\n% nontar_scores: scores for non-target trials\n\nif nargin==0\n test_this();\n return\nend\n\nassert(nargin==2)\nassert(isvector(tar_scores))\nassert(isvector(nontar_scores))\n\nNt = length(tar_scores);\nNn = length(nontar_scores);\nN = Nt+Nn;\nscores = [tar_scores(:)',nontar_scores(:)'];\nPideal = [ones(1,Nt),zeros(1,Nn)]; %ideal, but non-monotonic posterior\n\n%It is important here that scores that are the same (i.e. already in order) should NOT be swapped.\n%MATLAB's sort algorithm has this property.\n[scores,perturb] = sort(scores);\n\nPideal = Pideal(perturb);\n[Popt,width] = pavx(Pideal); \n\nnbins = length(width);\npmiss = zeros(1,nbins+1);\npfa = zeros(1,nbins+1);\n\n%threshold leftmost: accept eveything, miss nothing\nleft = 0; %0 scores to left of threshold\nfa = Nn;\nmiss = 0;\n\nfor i=1:nbins\n pmiss(i) = miss/Nt;\n pfa(i) = fa/Nn;\n left = left + width(i);\n miss = sum(Pideal(1:left));\n fa = N - left - sum(Pideal(left+1:end));\nend\npmiss(nbins+1) = miss/Nt;\npfa(nbins+1) = fa/Nn;\n\nend\n\n\nfunction test_this()\n\nfigure();\n\nsubplot(2,3,1);\ntar = [1]; non = [0];\n[pmiss,pfa] = rocch(tar,non);\n[pm,pf] = compute_roc(tar,non);\nplot(pfa,pmiss,'r-^',pf,pm,'g--v');\naxis('square');grid;legend('ROCCH','ROC');\ntitle('2 scores: non < tar');\n\nsubplot(2,3,2);\ntar = [0]; non = [1];\n[pmiss,pfa] = rocch(tar,non);\n[pm,pf] = compute_roc(tar,non);\nplot(pfa,pmiss,'r-^',pf,pm,'g-v');\naxis('square');grid;\ntitle('2 scores: tar < non');\n\nsubplot(2,3,3);\ntar = [0]; non = [-1,1];\n[pmiss,pfa] = rocch(tar,non);\n[pm,pf] = compute_roc(tar,non);\nplot(pfa,pmiss,'r-^',pf,pm,'g--v');\naxis('square');grid;\ntitle('3 scores: non < tar < non');\n\nsubplot(2,3,4);\ntar = [-1,1]; non = [0];\n[pmiss,pfa] = rocch(tar,non);\n[pm,pf] = compute_roc(tar,non);\nplot(pfa,pmiss,'r-^',pf,pm,'g--v');\naxis('square');grid;\ntitle('3 scores: tar < non < tar');\nxlabel('P_{fa}');\nylabel('P_{miss}');\n\nsubplot(2,3,5);\ntar = randn(1,100)+1; non = randn(1,100);\n[pmiss,pfa] = rocch(tar,non);\n[pm,pf] = compute_roc(tar,non);\nplot(pfa,pmiss,'r-^',pf,pm,'g');\naxis('square');grid;\ntitle('45^{\\circ} DET');\n\nsubplot(2,3,6);\ntar = randn(1,100)*2+1; non = randn(1,100);\n[pmiss,pfa] = rocch(tar,non);\n[pm,pf] = compute_roc(tar,non);\nplot(pfa,pmiss,'r-^',pf,pm,'g');\naxis('square');grid;\ntitle('flatter DET');\n\nend\n", "meta": {"author": "nesl", "repo": "asvspoof2019", "sha": "8b780369f7273345c22d979192119198bbf3db13", "save_path": "github-repos/MATLAB/nesl-asvspoof2019", "path": "github-repos/MATLAB/nesl-asvspoof2019/asvspoof2019-8b780369f7273345c22d979192119198bbf3db13/baseline/tDCF_v1/bosaris_toolkit.1.06/bosaris_toolkit/utility_funcs/det/rocch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6889368789805509}} {"text": "function [b,S] = bin_packing(a,V,varargin)\n % BIN_PACKING Given a list of n items of varying sizes (a), pack them into the\n % smallest number (b) of bins of equal size (V). \n %\n % Inputs:\n % a #a list of item sizes\n % V scalar size of bins\n % Outputs:\n % b minimal number of bins\n % S #a list of indices into 1:b, assigning each item to a bin\n %\n % Example:\n % a = ceil(rand(100,1)*10);\n % V = 20;\n % [b,S] = bin_packing(a,V);\n % barh(full(sparse(S,1:numel(a),a)),'stacked');\n % \n\n max_iters = 5;\n params_to_variables = containers.Map( ...\n {'MaxIters'},{'max_iters'});\n v = 1;\n while v <= numel(varargin)\n param_name = varargin{v};\n if isKey(params_to_variables,param_name)\n assert(v+1<=numel(varargin));\n v = v+1;\n % Trick: use feval on anonymous function to use assignin to this workspace\n feval(@()assignin('caller',params_to_variables(param_name),varargin{v}));\n else\n error('Unsupported parameter: %s',varargin{v});\n end\n v=v+1;\n end\n \n assert(all(aar(i),1,'first');\n if j>=b\n break;\n end\n Sr(i) = j;\n Br(j) = Br(j) - ar(i);\n end\n if j >= b\n continue;\n end\n \n br = find(Br==V,1,'first')-1;\n if br < b\n b = br;\n B = Br;\n S(P) = Sr;\n end\n end\n\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/matrix/bin_packing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.6889368713405962}} {"text": "% DEMVOWELSISOMAP Model the vowels data with a 2-D FGPLVM using RBF kernel.\n\n% FGPLVM\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\ndataSetName = 'vowels';\nexperimentNo = 1;\nind\n% load data\n[Y, lbls] = lvmLoadData(dataSetName);\nind = randperm(size(Y,1));\nmodel.X = isomapEmbed(Y, 2);\n\nsave('demVowelsIsomap', 'model');\n\nfigure,\nhold on\n\nax = gca;\nlvmTwoDPlot(model.X, lbls, getSymbols(size(lbls, 2)));\nxLim = [min(model.X(:, 1)) max(model.X(:, 1))]*1.1;\nyLim = [min(model.X(:, 2)) max(model.X(:, 2))]*1.1;\nset(ax, 'xLim', xLim);\nset(ax, 'yLim', yLim);\n\nset(ax, 'fontname', 'arial');\nset(ax, 'fontsize', 20);\n\nerrors = fgplvmNearestNeighbour(model, lbls);\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/demVowelsIsomap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6889259482858399}} {"text": "function hu = imHuInvariants(img)\n% Compute Hu's invariant for a 2D image.\n%\n% HU = imHuInvariants(IMG)\n% HU is a row vector with 12 elements.\n%\n% Example\n% imHuInvariants\n%\n% See also\n%\n% Current implementation is based on the paper:\n% \"Noise tolerance of moment invariants in pattern recognition\"\n% I. Baslev, Pattern Recognition Letters 19 (1998): 1183-1189\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% Created: 2008-10-08, using Matlab 7.4.0.287 (R2007a)\n% Copyright 2008 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.\n\n\n%% Compute image moments\n\n% total mass of image\nm00 = sum(img(:));\n\n% center of mass (first order non-centered moment)\ncx = imMoment(img, 1, 0)/m00;\ncy = imMoment(img, 0, 1)/m00;\n\n% second-order centered and scaled moments\nm02 = imCSMoment(img, 0, 2, [cx cy], m00);\nm11 = imCSMoment(img, 1, 1, [cx cy], m00);\nm20 = imCSMoment(img, 2, 0, [cx cy], m00);\n\n% third-order centered and scaled moments\nm30 = imCSMoment(img, 3, 0, [cx cy], m00);\nm21 = imCSMoment(img, 2, 1, [cx cy], m00);\nm12 = imCSMoment(img, 1, 2, [cx cy], m00);\nm03 = imCSMoment(img, 0, 3, [cx cy], m00);\n\n% fourth-order centered and scaled moments\nm40 = imCSMoment(img, 4, 0, [cx cy], m00);\nm31 = imCSMoment(img, 3, 1, [cx cy], m00);\nm22 = imCSMoment(img, 2, 2, [cx cy], m00);\nm13 = imCSMoment(img, 1, 3, [cx cy], m00);\nm04 = imCSMoment(img, 0, 4, [cx cy], m00);\n\n%% computation shortcuts\n\n% degree 2\na40 = m20 + m02;\na42 = m20 - m02;\nb42 = 2*m11;\n\n% degree 3\na51 = m30 + m12;\nb51 = m21 + m03;\na53 = m30 - m12;\nb53 = 3*m21 - m03;\n\n% degree 4\na60 = m40 + 2*m22 + m04;\na62 = m40 - m04;\nb62 = 2*(m31 + m13);\na64 = m40 - 6*m22 + m04;\nb64 = 4*(m31 - m13);\n\n\n%% Compute Hu's invariants\n\n% init size\nhu = zeros(1, 12);\n\n% degree 2\nhu(1) = a40;\nhu(2) = a42^2 + b42^2;\nhu(3) = a42*(a51^2-b51^2) + 2*a51*b51*b42;\n\n% degree 3\nhu(4) = a51^2 + b51^2;\nhu(5) = a53^2 + b53^2;\nhu(6) = a51*a53*(a51^2 - 3*b51^2) + b51*b53*(3*a51^2 - b51^2);\nhu(7) = a51*b53*(a51^2 - 3*b51^2) - b51*a53*(3*a51^2 - b51^2);\n\n% degree 4\nhu(8) = a60;\nhu(9) = a62^2 + b62^2;\nhu(10) = a64^2 + b64^2;\nhu(11) = a64*(a62^2-b62^2) + 2*a62*b62*b64;\nhu(12) = b64*(a62^2-b62^2) - 2*a62*b62*b64;\n\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imMeasures/imHuInvariants.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6889259347335124}} {"text": "function C = blkdiageye(X,k)\n% construct block-diagonal matrix with k copies of X on diagonal\n% Equivalent to C = kron(eye(k),X) but much faster\n%\n% Author: Tim Mullen, 2011 (C) SCCN/INC/UCSD\n\nss = repmat({X},1,k);\nC = blkdiag(ss{:});\n\n% alternate form\n% ss = repmat('X,',1,k); ss(end)=[];\n% eval(sprintf('C = blkdiag(%s);',ss));\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/utils/blkdiageye.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.6889192813640853}} {"text": "%% (Internal) Mean/Median filtering\n% \n% Output = MedianFilt(Input, WinSize, bRobust)\n% \n% Arguments:\n% \n% + Input: the signal\n% \n% + WinSize: The size of the window in samples\n% \n% + bRobust: use mean (false) or median (true)\n% \n% Output:\n% \n% + Output: filtered output\n% \n% Example:\n% \n% WinSize = round(0.2*SamplingFreq);\n% \n% %Baseline estimation.\n% BaselineEstimation = MedianFilt(noisyECG, WinSize );\n% \n% \n% See also BaselineWanderRemovalMedian\n% \n% Author: Mariano Llamedo Soria llamedom@electron.frba.utn.edu.ar\n% Version: 0.1 beta\n% Last update: 14/5/2014\n% Birthdate : 21/4/2015\n% Copyright 2008-2015\n% \nfunction Output = MedianFilt(Input, WinSize, bRobust)\n\nif(nargin < 2 || isempty(WinSize) )\n WinSize = 31;\nend\n\nif(nargin < 3 || isempty(bRobust) )\n bRobust = true;\nend\n\nif(bRobust)\n mean_ptr_func = @nanmedian;\nelse\n mean_ptr_func = @nanmean;\nend\n\nMidPoint = ceil(WinSize/2);\n\naux_seq = 1:size(Input,1);\nlaux_seq = length(aux_seq);\n\neach_sample_idx = arrayfun(@(a)(max(1,a):min(laux_seq,a + WinSize-1)), aux_seq - MidPoint+1, ...\n 'UniformOutput', false);\nOutput = cellfun(@(a)(mean_ptr_func(Input(a,:),1)), colvec(each_sample_idx), 'UniformOutput', false);\n\nOutput = cell2mat(Output);\n\n\n%old version\n% startSample = MidPoint;\n% endSample = size(Input,1) - fix(WinSize/2);\n% Output = zeros(endSample-startSample+1, size(Input,2));\n% \n% iCount = 1;\n% \n% for iSampleIndex = startSample:endSample\n% \n% startRange = iSampleIndex-MidPoint+1;\n% iRange = startRange:startRange+WinSize-1;\n% \n% Output(iCount,:) = median( Input(iRange,:) );\n% \n% iCount = iCount + 1;\n% \n% end\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/MedianFilt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.6889192593242306}} {"text": "#!/usr/bin/env octave\n%% Machine Learning Online Class\n% Exercise 7 | Principle Component Analysis and K-Means Clustering\n%\n% Instructions\n% ------------\n%\n% This file contains code that helps you get started on the\n% exercise. You will need to complete the following functions:\n%\n% pca.m\n% projectData.m\n% recoverData.m\n% computeCentroids.m\n% findClosestCentroids.m\n% kMeansInitCentroids.m\n%\n% For this exercise, you will not need to change any code in this file,\n% or any other files other than those mentioned above.\n%\n\n%% Initialization\nclear ; close all; clc\n\n%% ================== Part 1: Load Example Dataset ===================\n% We start this exercise by using a small dataset that is easily to\n% visualize\n%\nfprintf('Visualizing example dataset for PCA.\\n\\n');\n\n% The following command loads the dataset. You should now have the \n% variable X in your environment\nload ('ex7data1.mat');\n\n% Visualize the example dataset\nplot(X(:, 1), X(:, 2), 'bo');\naxis([0.5 6.5 2 8]); axis square;\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n\n%% =============== Part 2: Principal Component Analysis ===============\n% You should now implement PCA, a dimension reduction technique. You\n% should complete the code in pca.m\n%\nfprintf('\\nRunning PCA on example dataset.\\n\\n');\n\n% Before running PCA, it is important to first normalize X\n[X_norm, mu, sigma] = featureNormalize(X);\n\n% Run PCA\n[U, S] = pca(X_norm);\n\n% Compute mu, the mean of the each feature\n\n% Draw the eigenvectors centered at mean of data. These lines show the\n% directions of maximum variations in the dataset.\nhold on;\ndrawLine(mu, mu + 1.5 * S(1,1) * U(:,1)', '-k', 'LineWidth', 2);\ndrawLine(mu, mu + 1.5 * S(2,2) * U(:,2)', '-k', 'LineWidth', 2);\nhold off;\n\nfprintf('Top eigenvector: \\n');\nfprintf(' U(:,1) = %f %f \\n', U(1,1), U(2,1));\nfprintf('\\n(you should expect to see -0.707107 -0.707107)\\n');\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n\n%% =================== Part 3: Dimension Reduction ===================\n% You should now implement the projection step to map the data onto the \n% first k eigenvectors. The code will then plot the data in this reduced \n% dimensional space. This will show you what the data looks like when \n% using only the corresponding eigenvectors to reconstruct it.\n%\n% You should complete the code in projectData.m\n%\nfprintf('\\nDimension reduction on example dataset.\\n\\n');\n\n% Plot the normalized dataset (returned from pca)\nplot(X_norm(:, 1), X_norm(:, 2), 'bo');\naxis([-4 3 -4 3]); axis square\n\n% Project the data onto K = 1 dimension\nK = 1;\nZ = projectData(X_norm, U, K);\nfprintf('Projection of the first example: %f\\n', Z(1));\nfprintf('\\n(this value should be about 1.481274)\\n\\n');\n\nX_rec = recoverData(Z, U, K);\nfprintf('Approximation of the first example: %f %f\\n', X_rec(1, 1), X_rec(1, 2));\nfprintf('\\n(this value should be about -1.047419 -1.047419)\\n\\n');\n\n% Draw lines connecting the projected points to the original points\nhold on;\nplot(X_rec(:, 1), X_rec(:, 2), 'ro');\nfor i = 1:size(X_norm, 1)\n drawLine(X_norm(i,:), X_rec(i,:), '--k', 'LineWidth', 1);\nend\nhold off\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% =============== Part 4: Loading and Visualizing Face Data =============\n% We start the exercise by first loading and visualizing the dataset.\n% The following code will load the dataset into your environment\n%\nfprintf('\\nLoading face dataset.\\n\\n');\n\n% Load Face dataset\nload ('ex7faces.mat')\n\n% Display the first 100 faces in the dataset\ndisplayData(X(1:100, :));\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% =========== Part 5: PCA on Face Data: Eigenfaces ===================\n% Run PCA and visualize the eigenvectors which are in this case eigenfaces\n% We display the first 36 eigenfaces.\n%\nfprintf(['\\nRunning PCA on face dataset.\\n' ...\n '(this mght take a minute or two ...)\\n\\n']);\n\n% Before running PCA, it is important to first normalize X by subtracting \n% the mean value from each feature\n[X_norm, mu, sigma] = featureNormalize(X);\n\n% Run PCA\n[U, S] = pca(X_norm);\n\n% Visualize the top 36 eigenvectors found\ndisplayData(U(:, 1:36)');\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n\n%% ============= Part 6: Dimension Reduction for Faces =================\n% Project images to the eigen space using the top k eigenvectors \n% If you are applying a machine learning algorithm \nfprintf('\\nDimension reduction for face dataset.\\n\\n');\n\nK = 100;\nZ = projectData(X_norm, U, K);\n\nfprintf('The projected data Z has a size of: ')\nfprintf('%d ', size(Z));\n\nfprintf('\\n\\nProgram paused. Press enter to continue.\\n');\npause;\n\n%% ==== Part 7: Visualization of Faces after PCA Dimension Reduction ====\n% Project images to the eigen space using the top K eigen vectors and \n% visualize only using those K dimensions\n% Compare to the original input, which is also displayed\n\nfprintf('\\nVisualizing the projected (reduced dimension) faces.\\n\\n');\n\nK = 100;\nX_rec = recoverData(Z, U, K);\n\n% Display normalized data\nsubplot(1, 2, 1);\ndisplayData(X_norm(1:100,:));\ntitle('Original faces');\naxis square;\n\n% Display reconstructed data from only k eigenfaces\nsubplot(1, 2, 2);\ndisplayData(X_rec(1:100,:));\ntitle('Recovered faces');\naxis square;\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n\n%% === Part 8(a): Optional (ungraded) Exercise: PCA for Visualization ===\n% One useful application of PCA is to use it to visualize high-dimensional\n% data. In the last K-Means exercise you ran K-Means on 3-dimensional \n% pixel colors of an image. We first visualize this output in 3D, and then\n% apply PCA to obtain a visualization in 2D.\n\nclose all; close all; clc\n\n% Re-load the image from the previous exercise and run K-Means on it\n% For this to work, you need to complete the K-Means assignment first\nA = double(imread('bird_small.png'));\n\n% If imread does not work for you, you can try instead\n% load ('bird_small.mat');\n\nA = A / 255;\nimg_size = size(A);\nX = reshape(A, img_size(1) * img_size(2), 3);\nK = 16; \nmax_iters = 10;\ninitial_centroids = kMeansInitCentroids(X, K);\n[centroids, idx] = runkMeans(X, initial_centroids, max_iters);\n\n% Sample 1000 random indexes (since working with all the data is\n% too expensive. If you have a fast computer, you may increase this.\nsel = floor(rand(1000, 1) * size(X, 1)) + 1;\n\n% Setup Color Palette\npalette = hsv(K);\ncolors = palette(idx(sel), :);\n\n% Visualize the data and centroid memberships in 3D\nfigure;\nscatter3(X(sel, 1), X(sel, 2), X(sel, 3), 10, colors);\ntitle('Pixel dataset plotted in 3D. Color shows centroid memberships');\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% === Part 8(b): Optional (ungraded) Exercise: PCA for Visualization ===\n% Use PCA to project this cloud to 2D for visualization\n\n% Subtract the mean to use PCA\n[X_norm, mu, sigma] = featureNormalize(X);\n\n% PCA and project the data to 2D\n[U, S] = pca(X_norm);\nZ = projectData(X_norm, U, 2);\n\n% Plot in 2D\nfigure;\nplotDataPoints(Z(sel, :), idx(sel), K);\ntitle('Pixel dataset plotted in 2D, using PCA for dimensionality reduction');\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n", "meta": {"author": "SaveTheRbtz", "repo": "ml-class", "sha": "74ce689e21e9f3ca184e60313351b31112e5dd56", "save_path": "github-repos/MATLAB/SaveTheRbtz-ml-class", "path": "github-repos/MATLAB/SaveTheRbtz-ml-class/ml-class-74ce689e21e9f3ca184e60313351b31112e5dd56/ex7/ex7_pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.6888243664562106}} {"text": "function gamblers_ruin_simulation ( a_stakes, b_stakes, game_num )\n\n%*****************************************************************************80\n%\n%% GAMBLERS_RUIN_SIMULATION simulates the game of gambler's ruin.\n%\n% Discussion:\n%\n% Two players, A and B, repeatedly toss a coin. \n% For heads, A wins one dollar from B;\n% For tails, B wins one dollar from A.\n% Play continues until one player is bankrupt.\n%\n% This program \"plays\" the game GAME_NUM times, always starting from\n% the same initial configuration.\n%\n% it keeps track of the number of coin tosses required, the number\n% of times the lead changes, and the number of times each player wins.\n%\n% At the end, it prints some statistics, and plots histograms of the\n% length of the game, and the number of lead changes.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 April 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer A_STAKES, B_STAKES, the number of dollars that A and\n% B have initially.\n%\n% Input, integer GAME_NUM, the number of games to simulate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GAMBLERS_RUIN_SIMULATION\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n\n if ( nargin < 1 )\n a_stakes = input ( 'Enter A_STAKES: ' );\n else\n a_stakes = str2num ( a_stakes );\n end\n\n if ( nargin < 2 )\n b_stakes = input ( 'Enter B_STAKES: ' );\n else\n b_stakes = str2num ( b_stakes );\n end\n\n if ( nargin < 3 )\n game_num = input ( 'Enter GAME_NUM, the number of games to play: ' );\n else\n game_num = str2num ( game_num );\n end\n\n a_wins = 0;\n b_wins = 0;\n%\n% Play GAME_NUM games.\n%\n for game = 1 : game_num\n\n step_num = 0;\n leader = '0';\n flip_num = -1;\n a = a_stakes;\n b = b_stakes;\n\n while ( 0 < a & 0 < b )\n\n step_num = step_num + 1;\n\n r = rand ( );\n \n if ( r <= 0.5 )\n a = a + 1;\n b = b - 1;\n else\n a = a - 1;\n b = b + 1;\n end\n\n if ( a_stakes < a & leader ~= 'A' )\n leader = 'A';\n flip_num = flip_num + 1;\n elseif ( a < a_stakes & leader ~= 'B' )\n leader = 'B';\n flip_num = flip_num + 1;\n end\n\n end\n\n if ( b == 0 ) \n a_wins = a_wins + 1;\n else\n b_wins = b_wins + 1;\n end\n\n flip(game) = flip_num;\n step(game) = step_num;\n\n end\n%\n% Average over the number of games.\n%\n step_ave = sum ( step(1:game_num) ) / game_num;\n prob_a_win = a_wins / game_num;\n prob_b_win = b_wins / game_num;\n%\n% Print statistics.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of games in simulation = %d\\n', game_num );\n fprintf ( 1, ' A starts game with %d\\n', a_stakes );\n fprintf ( 1, ' B starts game with %d\\n', b_stakes );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Average number of steps = %f\\n', step_ave );\n fprintf ( 1, ' Expected number of steps = %d\\n', a_stakes * b_stakes );\n fprintf ( 1, ' Maximum number of steps = %d\\n', max ( step ) );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Average chance of A winning = %f\\n', prob_a_win );\n fprintf ( 1, ' Expected chance of A winning = %f\\n', a_stakes / ( a_stakes + b_stakes ) );\n fprintf ( 1, ' Average chance of B winning = %f\\n', prob_b_win );\n fprintf ( 1, ' Expected chance of B winning = %f\\n', b_stakes / ( a_stakes + b_stakes ) );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Average number of flips = %f\\n', sum ( flip ) / game_num );\n fprintf ( 1, ' Maximum number of flips = %d\\n', max ( flip ) );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Initial flip table:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number Freq Prob\\n' );\n fprintf ( 1, '\\n' );\n for flip_num = 0 : 10\n i = find ( flip == flip_num );\n k = length ( i );\n fprintf ( 1, ' %4d %6d %f\\n', flip_num, k, k / game_num );\n end\n%\n% Plot steps.\n%\n figure ( 1 )\n\n hist ( step, 40 )\n\n title ( 'Gambler''s ruin, number of steps' )\n xlabel ( 'Steps' )\n ylabel ( 'Frequency' )\n\n figure ( 2 )\n\n hist ( flip, 40 )\n title ( 'Gambler''s ruin, number of changes in the lead (flips)' )\n xlabel ( 'Flips' )\n ylabel ( 'Frequency' )\n\n return\nend\n\n\n\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/gamblers_ruin_simulation/gamblers_ruin_simulation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.6888243554193173}} {"text": "function im = IdealLowPass(im0,fc)\n% fc is the circular cutoff frequency which is normalized to [0 1], that is,\n% the highest radian frequency \\pi of digital signals is mapped to 1.\n\n[ir,ic,iz] = size(im0);\nhr = (ir-1)/2;\nhc = (ic-1)/2;\n[x, y] = meshgrid(-hc:hc, -hr:hr); \n\nmg = sqrt((x/hc).^2 + (y/hr).^2);\nlp = double(mg <= fc);\n\nIM = fftshift(fft2(double(im0)));\nIP = zeros(size(IM));\nfor z = 1:iz\n IP(:,:,z) = IM(:,:,z) .* lp;\nend\nim = abs(ifft2(ifftshift(IP)));\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/36674-ideal-low-pass-filtering-of-an-image/IdealLowPass/IdealLowPass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6888117148515875}} {"text": "function oeprint1(mu, oev)\n\n% print six classical orbital elements\n% and orbital period in minutes\n\n% input\n\n% mu = gravitational constant (km**3/sec**2)\n% oev(1) = semimajor axis (kilometers)\n% oev(2) = orbital eccentricity (non-dimensional)\n% (0 <= eccentricity < 1)\n% oev(3) = orbital inclination (radians)\n% (0 <= inclination <= pi)\n% oev(4) = argument of perigee (radians)\n% (0 <= argument of perigee <= 2 pi)\n% oev(5) = right ascension of ascending node (radians)\n% (0 <= raan <= 2 pi)\n% oev(6) = true anomaly (radians)\n% (0 <= true anomaly <= 2 pi)\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nrtd = 180 / pi;\n\n% unload orbital elements array\n\nsma = oev(1);\necc = oev(2);\ninc = oev(3);\nargper = oev(4);\nraan = oev(5);\ntanom = oev(6);\n\narglat = mod(tanom + argper, 2.0 * pi);\n\nif (sma > 0.0)\n period = 2.0d0 * pi * sma * sqrt(sma / mu);\nelse\n period = 99999.9;\nend\n\n% print orbital elements\n\nfprintf ('\\n sma (km) eccentricity inclination (deg) argper (deg)');\n\nfprintf ('\\n %+16.14e %+16.14e %+16.14e %+16.14e \\n', sma, ecc, inc * rtd, argper * rtd);\n\nfprintf ('\\n raan (deg) true anomaly (deg) arglat (deg) period (min)');\n\nfprintf ('\\n %+16.14e %+16.14e %+16.14e %+16.14e \\n', raan * rtd, tanom * rtd, arglat * rtd, period / 60);\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/39494-geodetic-and-geocentric-coordinates/oeprint1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.688797015800923}} {"text": "%% fnc_getSobolSetMatlab: give a set of sobol quasi-random \n%\n% Usage:\n% X = fnc_getSobolSetMatlab(dim, N)\n%\n% Inputs:\n% dim number of variables, the MAX number of variables is 40\n% N number of samples\n%\n% Output:\n% X matrix [N x dim] with the quasti-random samples\n%\n% ------------------------------------------------------------------------\n%\n%\n% Author : Flavio Cannavo'\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\n% Release: 1.0\n% Date : 07-02-2011\n%\n% History:\n% 1.0 07-02-2011 First release.\n%\n%\n%\n\n%%\n\nfunction X = fnc_getSobolSetMatlab(dim, N)\n\np = sobolset(dim);\np = scramble(p,'MatousekAffineOwen');\nX = net(p,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/40759-global-sensitivity-analysis-toolbox/GSAT/fnc_getSobolSetMatlab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6887155094224212}} {"text": "%% WGMGRATE Test convergence of multigrid methods for weak Galerkin method\n%\n% Reference\n%\n% An auxiliary space multigrid preconditioner for the weak Galerkin method.\n% By Long Chen, Junping Wang, Yanqiu Wang, and Xiu Ye. Computers and\n% Mathematics with Applications, 70(4):330?344 2015.\n% doi:10.1016/j.camwa.2015.04.016\n\n\n%% Options\nclear variables; \nclose all;\noption.maxIt = 4;\noption.elemType = 'WG';\noption.solver = 'mg';\noption.smoothingstep = 2;\noption.plotflag = 1;\noption.rateflag = 0;\noption.dispflag = 1;\ncolname = {'#Dof','Steps','Time'};\n\n%% Example: circle mesh and Poisson equation\npde = sincosdata;\n[node,elem] = circlemesh(0,0,1,0.25);\n% showmesh(node,elem,'Facecolor','w');\nbdFlag = setboundary(node,elem,'Dirichlet');\nmesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);\n\noption.L0 = 1;\noption.maxN = 3e5;\noption.reducesystem = 0; % Solve the original system\n[err,time,solver] = femPoisson(mesh,pde,option);\ndisptable(colname,solver.N,[],solver.itStep,[],solver.time,'%4.2g');\n\noption.reducesystem = 1; % Solve the reduced system\n[err,time,solver] = femPoisson(mesh,pde,option);\ndisptable(colname,solver.N,[],solver.itStep,[],solver.time,'%4.2g');\n\n%% Example: square mesh and variable Poisson equation\n[node,elem] = squaremesh([0,1,0,1],0.25); \n% showmesh(node,elem,'Facecolor','w');\nbdFlag = setboundary(node,elem,'Dirichlet');\nmesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);\n\noption.L0 = 2;\noption.dquadorder = 4;\npde = oscdiffdata;\n\noption.reducesystem = 0; % Solve the original system\n[err,time,solver] = femPoisson(mesh,pde,option);\ndisptable(colname,solver.N,[],solver.itStep,[],solver.time,'%4.2g');\n\noption.reducesystem = 1; % Solve the reduced system\n[err,time,solver] = femPoisson(mesh,pde,option);\ndisptable(colname,solver.N,[],solver.itStep,[],solver.time,'%4.2g');\n\n%% Example: adaptive mesh and Poisson equation with less regularity\n[node,elem] = squaremesh([-1,1,-1,1],1);\n[node,elem] = delmesh(node,elem,'x>0 & y<0');\nbdFlag = setboundary(node,elem,'Dirichlet');\nmesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);\n\npde = Lshapedata;\noption.maxIt = 30;\noption.maxN = 1e4;\noption.printlevel = 0;\noption.rateflag = 1;\n\noption.reducesystem = 0; % Solve the original system\n[err,time,solver] = afemPoisson(mesh,pde,option);\ndisptable(colname,solver.N,[],solver.itStep,[],solver.time,'%4.2g');\n\noption.reducesystem = 1; % Solve the reduced system\n[err,time,solver,eqn,node,elem] = afemPoisson(mesh,pde,option);\ndisptable(colname,solver.N,[],solver.itStep,[],solver.time,'%4.2g');\n% figure; showmesh(node,elem,'Facecolor','w');", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/example/solver/WGmgrate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6887127287414739}} {"text": "function M = centeredmatrixfactory(m, n, rows_or_cols)\n% Linear manifold struct. for optimization over matrices with centered cols\n%\n% function M = centeredmatrixfactory(m, n)\n% function M = centeredmatrixfactory(m, n, 'cols')\n% function M = centeredmatrixfactory(m, n, 'rows')\n%\n% Returns M, a structure for Manopt describing the Euclidean space of\n% m-by-n matrices whose columns sum to zero (or whose rows sum to zero,\n% if 'rows' is passed as last input).\n%\n% The metric is the standard Frobenius distance and associated trace inner\n% product. Matrices on M, denoted by X, have size mxn and obey\n% X*ones(n, 1) = 0 (centered columns) or ones(1, m)*X = 0 (centered rows).\n%\n% See also: euclideanfactory\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, July 3, 2015.\n% Contributors: \n% Change log: \n\n if ~exist('rows_or_cols', 'var') || isempty(rows_or_cols)\n rows_or_cols = 'cols';\n end\n \n % Define a centering operator: it subtracts the mean column or row.\n switch lower(rows_or_cols)\n case 'cols'\n center = @(X) bsxfun(@minus, X, mean(X, 2));\n M.dim = @() m*n - m;\n case 'rows'\n center = @(X) bsxfun(@minus, X, mean(X, 1));\n M.dim = @() m*n - n;\n otherwise\n error('The third input must be either ''rows'' or ''cols''.');\n end\n \n % This is a non-standard function to have in a Manopt manifold.\n % It is included because it might be helpful in some situations.\n M.center = center;\n\n M.name = @() sprintf('Space of size %d x %d matrices with centered %s', ...\n m, n, lower(rows_or_cols));\n \n M.inner = @(x, d1, d2) d1(:).'*d2(:);\n \n M.norm = @(x, d) norm(d, 'fro');\n \n M.dist = @(x, y) norm(x-y, 'fro');\n \n M.typicaldist = @() sqrt(M.dim());\n \n M.proj = @(X, U) center(U);\n \n M.egrad2rgrad = M.proj;\n \n M.ehess2rhess = @(x, eg, eh, d) center(eh);\n \n M.tangent = @(x, d) d;\n \n M.exp = @exp;\n function y = exp(x, d, t)\n if nargin == 3\n y = x + t*d;\n else\n y = x + d;\n end\n end\n \n M.retr = M.exp;\n\t\n\tM.log = @(x, y) y-x;\n\n M.hash = @(x) ['z' hashmd5(x(:))];\n \n M.randvec = @(X) randvec();\n function U = randvec()\n U = center(randn(m, n));\n U = U / norm(U, 'fro');\n end\n \n M.rand = @() center(randn(m, n));\n \n M.lincomb = @matrixlincomb;\n \n M.zerovec = @(x) zeros(m, n);\n \n M.transp = @(x1, x2, d) d;\n \n M.pairmean = @(x1, x2) .5*(x1+x2);\n \n M.vec = @(x, u_mat) u_mat(:);\n M.mat = @(x, u_vec) reshape(u_vec, [m, n]);\n M.vecmatareisometries = @() true;\n\nend\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/manopt/manopt/manifolds/euclidean/centeredmatrixfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253257, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.6887127174513537}} {"text": "\nT=1/f;\n\n\nsl=3*T; % signal length\n\nxl=get(handles.axes1,'Xlim');\nyl=get(handles.axes1,'Ylim');\ndxl=xl(2)-xl(1);\ndyl=yl(2)-yl(1);\n\nxc1=0:dxl/res:sl;\nxc=mod(xc1,T); % turn to one period\nif iscnt\n yc=interp1([xys(1,:)-dxl xys(1,:) xys(1,:)+dxl],[xys(2,:) xys(2,:) xys(2,:)],xc,mth,'extrap');\nelse\n yc=interp1(xys(1,:),xys(2,:),xc,mth,'extrap');\nend\n\nnf=max(abs(yc)); % normalization factor\nyc=yc/nf; % mormalize\n\nfigure;\nplot(xc1,yc,'b-',xys(1,:),xys(2,:)/nf,'rx',[T T],[-1 1],'k--',[2*T 2*T],[-1 1],'k--');\nxlabel('time, s');\nylabel('signal, notmalized');\ntitle('3 periods of the signal');\nylim([-1 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/23526-waveform-generator-gui/waveform_generator_files/plot_3p.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6887127158185001}} {"text": "function [sh,pnl,pos] = marisa(x,N,M)\n% this is a combo model, MA+RSI\nthresh=55;\nS=length(x);\ne=ema(x,N);\n% take the RSI of the *DETRENDED* series\nr=rsi2(x-ema(x,15*M),M);\n% bid/ask spreads\ncost=0.01; % BUND/BOBL\n%cost=0.005; % SCHATZ\n%cost=1/64; %Treasury futures\n%cost = 0.0001; %US/EUR\n%cost = 0.05; %EUR/JPY\n%cost = 0.04; %US/JPY\n%cost = 0.0005; %AUS/USD\n%cost= 0.02;\n%cost=1; % eurostoxx\n\nrpos=zeros(S,1);\n% position of the ema\nepos=sign(x-e);\n% position of the rsi\nI= (thresh-r)<0; \nIU=[~1;I(1:end-1) & ~I(2:end)];\nrpos(IU)=-1;\n% crossing the lower threshold\nI= ((100-thresh)-r)>0;\nIL=[~1;I(1:end-1) & ~I(2:end)];\nrpos(IL)=1; \n% copy down previous position values\nfor i=2:S\n if rpos(i)==0;\n rpos(i)=rpos(i-1);\n end\nend\n\n% get the combined signal position\npos=(rpos+epos)/2; \npos( abs(pos) < 1)=0;\n\n% pnl calculation\npnl= pos(1:end-1).*diff(x) - abs(diff(pos))*cost/2;\nsh= sqrt(250)*mean(pnl)/std(pnl);\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/24320-algorithmic-trading-with-matlab-2009-update/marisa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6887013524245672}} {"text": "\n\nclear all; close all;\nI=imread('pout.tif');\nJ=log(im2double(I)+1);\t\nK=fft2(J);\nn=5;\nD0=0.1*pi;\nrh=0.7;\nrl=0.4;\n[row, column]=size(J);\nfor i=1:row\n for j=1:column\n D1(i,j)=sqrt(i^2+j^2);\n H(i,j)=rl+(rh/(1+(D0/D1(i,j))^(2*n)));\n end\nend\nL=K.*H;\nM=ifft2(L);\nN=exp(M)-1;\nfigure;\nsubplot(121);\nimshow(I);\nsubplot(122);\nimshow(real(N));\n\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/\u300aMATLAB\u56fe\u50cf\u5904\u7406\u300b\u6e90\u6587\u4ef6/\u672c\u4e66\u6e90\u6587\u4ef6/chap5/chap5_30.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6887013513736837}} {"text": "function val=evalBSplinePoly(t,x,k,idx)\n%%EVALBSPLINEPOLY Given a set of knots in non-decreasing order (some can be\n% repeated), evaluate the idx-th order-k B-spline\n% polynomial. This is B_{idx,k}(x). The first subscript\n% refers to the knots used in determining the polynomial.\n% Unlike the function evalBSplinePolys, this function can\n% handle values of x that are outside of the region\n% t(idx+-1k)<=x<=t(idx+k).\n%\n%INPUTS: t A 1XnumKnots or numKnotsX1 vector containing the knots. The\n% knots must be sorted in ascending order. It is possible for the\n% knots to be repeated.\n% x The scalar or matrix set of points at which the polynomials\n% should be evaluated.\n% k Optionally, the order of the B-spline polynomials. If this\n% parameter is omitted, then the default of fix(length(t)/2)+1 is\n% used. This is the highest order that can be used with the given\n% number of knots.\n% idx This input specifies where in terms of the knots the B-spline\n% polynomials are centered. This is an integer value from 1 to\n% numKnots-k.\n%\n%OUTPUTS: val The value of the b-spline B_{idx,k}(x) evaluated at all of\n% the points in x. This has the same size as x.\n%\n%This function implements the divided difference formulation of the splines\n%from Equation 1 in Chapter IX of [1]. A clearer explanation of the\n%notation is given in Chapter 2.4.4 of [2], where Equation 2.4.4.3 is the\n%divided difference formula.\n%\n%EXAMPLE:\n%Here, we plot all of the b-spline basis functions from example IX.1 of\n%Chapter IX of [1]. The functions only sum to one over the region from 1 to\n%6. Thus, the sum is not one over the region plotted before x=1.\n% t=[0;1;1;3;4;6;6;6];\n% k=3;\n% numPoints=500;\n% x=linspace(0,6,numPoints);\n% \n% b1=evalBSplinePoly(t,x,k,1);\n% b2=evalBSplinePoly(t,x,k,2);\n% b3=evalBSplinePoly(t,x,k,3);\n% b4=evalBSplinePoly(t,x,k,4);\n% b5=evalBSplinePoly(t,x,k,5);\n% figure(1)\n% clf\n% hold on\n% plot(x,b1,'-k','linewidth',2)\n% plot(x,b2,'--r','linewidth',2)\n% plot(x,b3,'-.g','linewidth',2)\n% plot(x,b4,'-b','linewidth',2)\n% plot(x,b5,'--c','linewidth',2)\n%\n%REFERENCES:\n%[1] C. de Boor, A Practical Guide to Splines. New York: Springer-Verlag,\n% 1978.\n%[2] J. Stoer and R. Burlisch, Introduction to Numerical Analysis, 2nd ed.\n% New York: Springer-Verlag, 1991.\n%\n%April 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nval=zeros(size(x));\nnumEls=numel(x);\nfor curIdx=1:numEls\n xCur=x(curIdx);\n tSel=t(idx:(idx+k));\n f=max(tSel-xCur,0).^(k-1);\n fDeriv=@(ti,nd)prod((k-(1:nd)))*max(ti-xCur,0).^(k-1-nd);\n\n val(curIdx)=(t(idx+k)-t(idx))*evalDividedDiff(tSel,f,fDeriv);\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/Interpolation/B-Splines/evalBSplinePoly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.6886820390423383}} {"text": "function triangle_symq_rule_test05 ( degree, numnodes, vert1, vert2, vert3 )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_SYMQ_RULE_TEST05 calls TRIASYMQ for a quadrature rule of given order and region.\n%\n% Licensing:\n%\n% This code is distributed under the GNU GPL license.\n%\n% Modified:\n%\n% 27 June 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Hong Xiao, Zydrunas Gimbutas,\n% A numerical algorithm for the construction of efficient quadrature\n% rules in two and higher dimensions,\n% Computers and Mathematics with Applications,\n% Volume 59, 2010, pages 663-676.\n%\n% Parameters:\n%\n% Input, integer DEGREE, the desired total polynomial degree \n% exactness of the quadrature rule. 0 <= DEGREE <= 50.\n%\n% Input, integer NUMNODES, the number of nodes to be used by the rule.\n%\n% Input, real VERT1(2), VERT2(2), VERT3(2), the\n% vertices of the triangle.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGLE_SYMQ_RULE_TEST05\\n' );\n fprintf ( 1, ' Compute a quadrature rule for a triangle.\\n' );\n fprintf ( 1, ' Check it by integrating orthonormal polynomials.\\n' );\n fprintf ( 1, ' Polynomial exactness degree DEGREE = %d\\n', degree );\n\n area = triangle_area ( vert1, vert2, vert3 );\n%\n% Retrieve a symmetric quadrature rule.\n%\n [ rnodes, weights ] = triasymq ( degree, vert1, vert2, vert3, numnodes );\n%\n% Construct the matrix of values of the orthogonal polynomials\n% at the user-provided nodes\n%\n npols = ( ( degree + 1 ) * ( degree + 2 ) ) / 2;\n\n rints = zeros ( npols, 1 );\n\n for i = 1 : numnodes\n z(1) = rnodes(1,i);\n z(2) = rnodes(2,i);\n r = triangle_to_ref ( vert1, vert2, vert3, z );\n pols = ortho2eva ( degree, r );\n rints(1:npols) = rints(1:npols) + weights(i) * pols(1:npols);\n end\n\n scale = sqrt ( sqrt ( 3.0 ) ) / sqrt ( area );\n rints(1:npols) = rints(1:npols) * scale;\n\n d = ( rints(1) - sqrt ( area ) )^2 + sum ( rints(2:npols).^2 );\n d = sqrt ( d ) / npols;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' RMS integration error = %g\\n', d );\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_symq_rule/triangle_symq_rule_test05.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.6886820372176143}} {"text": "%% AMG TEST I: DIFFERENT MESHES\n% \n% We consider linear finite element discretization of the Poisson equation\n% with homongenous Dirichlet boundary condition on different meshes. \n\n%%\nclear all; close all;\n%% Uniform mesh\n[node,elem] = squaremesh([0,1,0,1],0.1);\n[node,elem] = uniformrefine(node,elem);\n[node,elem] = uniformrefine(node,elem);\nshowmesh(node,elem);\nsnapnow;\n[N,itStep,time,err,errHist] = amgtest(node,elem);\n%% \ncolHeaders = {'Unknowns','Iterations','Time (sec)','Error'};\nmakeHtmlTable([N itStep time err],[],[],colHeaders,[],6);\n%%\ncolHeaders = {'Iterations','Approximate Error', 'Residual'};\nmakeHtmlTable([(0:itStep(end))' errHist],[],[],colHeaders,[],6);\n%%\nr = showrate(N,time,2);\nxlabel('N'); ylabel('Time');\ntitle(['Complexity is N^{' num2str(r) '}'] ,'Fontsize', 14);\n\n%% Circle mesh\nclose all;\n[node,elem] = circlemesh(0,0,1,0.2);\n[node,elem] = uniformrefine(node,elem);\n[node,elem] = uniformrefine(node,elem);\nshowmesh(node,elem);\nsnapnow;\n[N,itStep,time,err] = amgtest(node,elem);\n%% \ncolHeaders = {'Unknowns','Iterations','Time (sec)','Error'};\nmakeHtmlTable([N itStep time err],[],[],colHeaders,[],6);\n%%\nr = showrate(N,time,2);\nxlabel('N'); ylabel('Time');\ntitle(['Complexity is N^{' num2str(r) '}'] ,'Fontsize', 14);\n\n%% Unstructured mesh\nclose all;\nload lakemesh\nshowmesh(node,elem);\nsnapnow;\n[N,itStep,time,err] = amgtest(node,elem);\n%% \ncolHeaders = {'Unknowns','Iterations','Time (sec)','Error'};\nmakeHtmlTable([N itStep time err],[],[],colHeaders,[],6);\n%%\nr = showrate(N,time,2);\nxlabel('N'); ylabel('Time');\ntitle(['Complexity is N^{' num2str(r) '}'],'Fontsize', 14);", "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/doc/amgdoctest1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332893, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.6886820311855489}} {"text": "function y = hmean(x)\n% HMEAN 1/mean(1/input)\n%\n% Description:\n% Y = HMEAN(X) evaluates y=1./mean(1./x)\n\n% Copyright (c) 1998 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\ny=1./mean(1./x);\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/mc/hmean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6886018062773016}} {"text": "function [theta] = tapas_sem_sample_gaussian_uniform_priors(ptheta)\n%% Sample from a Gaussian prior. \n%\n% aponteeduardo@gmail.com\n% copyright (C) 2016\n%\n\nnp = size(ptheta.jm, 2);\n\nsample_pars = logical(sum(ptheta.jm, 2));\n\nif size(ptheta.pm, 2) ~= np\n pm = diag(ptheta.pm);\nelse\n pm = ptheta.pm;\nend\n\nlt = chol(pm);\ntheta = ptheta.mu + lt \\ ptheta.jm * randn(np, 1);\n\n% Beta parameters.\nbdist = zeros(size(ptheta.pm));\nbdist(ptheta.bdist) = 1;\nbdist = logical(bdist .* sample_pars);\nvals = betarnd(abs(ptheta.mu), abs(ptheta.pm));\nvals = ptheta.jm * ptheta.sm' * vals;\ntheta(bdist) = log(vals(bdist) ./ ( 1 - vals(bdist)));\n\ntheta(~sample_pars) = ptheta.p0(~sample_pars);\n\n\nend\n\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/sem/matlab/tapas_sem_sample_gaussian_uniform_priors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6886017942006376}} {"text": "function state = sample_mdp(prior, trans, act)\n% SAMPLE_MDP Sample a sequence of states from a Markov Decision Process.\n% state = sample_mdp(prior, trans, act)\n%\n% Inputs:\n% prior(i) = Pr(Q(1)=i)\n% trans{a}(i,j) = Pr(Q(t)=j | Q(t-1)=i, A(t)=a)\n% act(a) = A(t), so act(1) is ignored\n%\n% Output:\n% state is a vector of length T=length(act)\n\nlen = length(act);\nstate = zeros(1,len);\nstate(1) = sample_discrete(prior);\nfor t=2:len\n state(t) = sample_discrete(trans{act(t)}(state(t-1),:));\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/dmlt/external/murphy/hmm/mdp_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6886017933724222}} {"text": "function [suspicious_index abof] = fastABOD(A,n_k)\n%\n% Angle Based Outlier Detection \n% Authors: Hans-Peter, Kriegel Matthias, Schubert Arthur Zimek \n% Original paper : \n% Angle-Based Outlier Detection in High-dimensional Data In KDD2008 \n% Website : http://www.dbs.ifi.lmu.de/ \n% e-mail : {kriegel,schubert,zimek}@dbs.ifi.lmu.de \n% Programmer: Yi-Ren Yeh \n% modified by: Wei-Chih Lai \n% \n% Time Complexity : O(n^2 + n * n_k^2) \n% \n% Inputs \n% A: Represent NxM data \n% N is number of instance \n% M is number of feature \n% n_k: 1x1 integer (0, N] \n% iterator time for approximate abof value \n% \n% Outputs \n% abof: Nx1 vector \n% suspicious abof value for each instance \n% suspicious_index: Nx1 vector \n% [~,suspicious_index]=sort(abof,'ascend') \n% Note \n% 1. each value in output abof was normalized to [0, 1] \n% 2. if input n_k == N - 1, then the effect is equal to ABOD \n%\n [A, ia, ic] = unique(A,'rows');\n instance_number = size(ia, 1);\n origin_instance_number = size(ic, 1);\n var_array = zeros(instance_number, 1);\n n_k = min(n_k, instance_number);\n\n for i=1:instance_number\n var_front = 0;\n var_back = 0;\n denominator = 0;\n Temp = repmat(A(i, :), instance_number, 1) - A;\n Temp = sum(Temp .^ 2, 2);\n [~, index] = sort(Temp);\n index = index(2:n_k);\n index = index';\n count = 0;\n for j=index\n count = count + 1;\n for k=index(count+1:end)\n vector1 = A(j, :) - A(i, :);\n vector2 = A(k, :) - A(i, :);\n norm_vector1Xnorm_vector2 = norm(vector1) * norm(vector2);\n vector1Xvector2T = vector1 * vector2';\n var_front = var_front + (1 / norm_vector1Xnorm_vector2) * (vector1Xvector2T / (norm_vector1Xnorm_vector2 ^ 2)) ^ 2;\n var_back = var_back + (vector1Xvector2T / norm_vector1Xnorm_vector2 ^ 3);\n denominator = denominator + (1 / norm_vector1Xnorm_vector2);\n end\n end\n var_array(i) = var_front / denominator - (var_back / denominator) ^ 2;\n end\n\n min_var_array = min(var_array);\n abof = (var_array - min_var_array) / (max(var_array) - min_var_array);\n origin_abof = zeros(origin_instance_number, 1);\n for i=1:origin_instance_number\n origin_abof(i, 1) = abof(ic(i, 1), 1);\n end\n abof = origin_abof;\n [~, suspicious_index] = sort(abof);", "meta": {"author": "dsmi-lab-ntust", "repo": "AnomalyDetectionToolbox", "sha": "b9385ba405026f56a008f88c0580b1a18e24b355", "save_path": "github-repos/MATLAB/dsmi-lab-ntust-AnomalyDetectionToolbox", "path": "github-repos/MATLAB/dsmi-lab-ntust-AnomalyDetectionToolbox/AnomalyDetectionToolbox-b9385ba405026f56a008f88c0580b1a18e24b355/Algorithms/angleBased/ABOD/fastABOD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6886017844930973}} {"text": "function [dat, opt] = proc_pca(dat, varargin)\n%PROC_PCA - Principal Component Analysis\n% [dat_pca, pca_opt] = proc_pca(dat, )\n% \n%Synopsis for training PCA:\n% [DAT_PCA_TRAIN, PCA_OPT] = proc_pca(DAT_TRAIN, )\n%\n%Synopsis for applying PCA:\n% DAT_PCA_TEST = proc_pca(DAT_TEST, PCA_OPT)\n%\n%Arguments:\n% DAT_TRAIN - data structure of continuous or epoched data\n% OPT - struct or property/value list of optional properties:\n% .whitening - if 1, the output dimensions will all have unit variance\n% (default 0)\n% PCA_OPT - a struct that contains: a bias vector, filters and field\n% patterns of the sources\n%\n%Returns\n% DAT_PCA_TRAIN,\n% DAT_PCA_TEST - updated data structure\n% PCA_OPT - a struct that contains: a bias vector, filters and field\n% patterns of the sources\n%\n\n% Sven Daehne, 03.2011, sven.daehne@tu-berlin.de\n% Matthias Schultze-Kraft, 12.2015, schultze-kraft@tu-berlin.de\n\nprops= {'whitening' 0 'BOOL'\n 'filters' [] 'DOUBLE'\n 'field_patterns' [] 'DOUBLE'\n 'bias' [] 'DOUBLE'};\n\nif nargin==0,\n dat = props; return\nend\n\ndat = misc_history(dat);\nmisc_checkType(dat, 'STRUCT(x clab y)');\n\nopt = opt_proplistToStruct(varargin{:});\nopt = opt_setDefaults(opt, props);\nopt_checkProplist(opt, props);\n\n[T,nChans,nEpos] = size(dat.x);\n\n%% train PCA\nif isempty(opt.filters) || isempty(opt.bias)\n % get the data matrix\n if ndims(dat.x)==3\n % since time structure does not matter, we can simply concatenate all\n % epochs to get one big data matrix\n X = permute(dat.x, [1,3,2]); % now channels are the last dimension\n X = reshape(X, [T*nEpos, nChans]);\n else\n X = dat.x;\n end\n % remove the mean here already\n b = mean(X,1);\n B = repmat(b, [T*nEpos, 1]);\n X = X - B;\n \n % perform PCA and compute whitening matrix\n C = cov(X);\n [V, D] = eig(C);\n [ev_sorted, sort_idx] = sort(diag(D), 'descend');\n V = V(:,sort_idx);\n D = diag(ev_sorted);\n \n if opt.whitening\n V = V * diag(diag(D).^-0.5);\n end\n \n opt.filters = V;\n opt.field_patterns = V';\n opt.eigenvalues = ev_sorted;\n opt.bias = b;\n\nend\n\n%% apply PCA\nif not(length(opt.bias) == nChans)\n error('Dimension of bias must equal the number of channels!')\nend\n% make sure opt.bias is a row vector\nif size(opt.bias, 1) > size(opt.bias,2)\n opt.bias = opt.bias';\nend\n\n% subtract bias, then apply filters\nB = squeeze(repmat(opt.bias, [T,1,nEpos]));\ndat.x = dat.x - B;\ndat = proc_linearDerivation(dat, opt.filters);\n\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/processing/proc_pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6885455241847307}} {"text": "load demo.mat \npitch = -120/180*pi;\nyaw = -30/180*pi;\npitchR = [1 0 0 ;...\n 0 cos(pitch) -sin(pitch) ;...\n 0 sin(pitch) cos(pitch) ];\nyawR = [cos(yaw) 0 sin(yaw) ;...\n 0 1 0 ;...\n -sin(yaw) 0 cos(yaw) ];\n\nR = pitchR * yawR ;\n\nRt = [R [0.8;0;12]];\n\nwidth = 640*1;\nheight= 480*1;\nK = [ 1100*1 0 width/2 ;...\n 0 1100*1 height/2 ;...\n 0 0 1];\n[render,depth] = RenderPCcameraMatlab(double(pt),color, ptCamera,colorCamera ,K, Rt,width,height);\nimshow(render);\nimwrite(render,'demo.png');\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/RenderPCcamera/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660923657093, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.688518557622571}} {"text": "function varargout = centerOfMass(A,varargin)\n% CENTEROFMASS finds the center of mass of the N-dimensional input array\n%\n% CENTEROFMASS(A) finds the gray-level-weighted center of mass of the\n% N-dimensional numerical array A. A must be real and finite. A warning\n% is issued if A contains any negative values. Any NaN elements of A will\n% automatically be ignored. CENTEROFMASS produces center of mass\n% coordinates in units of pixels. An empty array is returned if the\n% center of mass is undefined.\n%\n% The center of mass is reported under the assumption that the first\n% pixel in each array dimension is centered at 1.\n%\n% Also note that numerical arrays other than DOUBLE and SINGLE are\n% converted to SINGLE in order to prevent numerical roundoff error.\n%\n% Examples:\n% A = rgb2gray(imread('saturn.png'));\n% C = centerOfMass(A);\n%\n% figure; imagesc(A); colormap gray; axis image\n% hold on; plot(C(2),C(1),'rx')\n%\n% See also: \n%\n%\n\n%\n% Jered R Wells\n% 2013/05/07\n% jered [dot] wells [at] gmail [dot] com\n%\n% v1.0\n%\n% UPDATES\n% YYYY/MM/DD - jrw - v1.1\n%\n%\n\n%% INPUT CHECK\nnarginchk(0,1);\nnargoutchk(0,1);\nfname = 'centerOfMass';\n\n% Checked required inputs\nvalidateattributes(A,{'numeric'},{'real','finite'},fname,'A',1);\n\n%% INITIALIZE VARIABLES\nA(isnan(A)) = 0;\nif ~(strcmpi(class(A),'double') || strcmpi(class(A),'single'))\n A = single(A);\nend\nif any(A(:)<0)\n warning('MATLAB:centerOfMass:neg','Array A contains negative values.');\nend\n\n%% PROCESS\nsz = size(A);\nnd = ndims(A);\nM = sum(A(:));\nC = zeros(1,nd);\nif M==0\n C = [];\nelse\n for ii = 1:nd\n shp = ones(1,nd);\n shp(ii) = sz(ii);\n rep = sz;\n rep(ii) = 1;\n ind = repmat(reshape(1:sz(ii),shp),rep);\n C(ii) = sum(ind(:).*A(:))./M;\n end\nend\n\n% Assemble the VARARGOUT cell array\nvarargout = {C};\n\nend % MAIN", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/centerOfMass/centerOfMass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.6884922943071419}} {"text": "function [ n_data, x, fx ] = cos_degree_values ( n_data )\n\n%*****************************************************************************80\n%\n%% COS_DEGREE_VALUES: the cosine function with argument in degrees.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% Cos[x Degree]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 March 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz, Irene Stegun,\n% Handbook of Mathematical Functions,\n% National Bureau of Standards, 1964,\n% ISBN: 0-486-61272-4,\n% LC: QA47.A34.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Cambridge University Press, 1999,\n% ISBN: 0-521-64314-7,\n% LC: QA76.95.W65.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 \n% before the first call. On each call, the routine increments N_DATA by 1,\n% and returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 22;\n\n fx_vec = [ ...\n 0.99619469809174553230, ...\n 1.0000000000000000000, ...\n 0.99984769515639123916, ...\n 0.99939082701909573001, ...\n 0.99862953475457387378, ...\n 0.99756405025982424761, ...\n 0.99619469809174553230, ...\n 0.98480775301220805937, ...\n 0.96592582628906828675, ...\n 0.86602540378443864676, ...\n 0.70710678118654752440, ...\n 0.50000000000000000000, ...\n 0.25881904510252076235, ...\n 0.087155742747658173558, ...\n 0.069756473744125300776, ...\n 0.052335956242943832722, ...\n 0.034899496702500971646, ...\n 0.017452406437283512819, ...\n 0.000000000000000000000, ...\n -0.017452406437283512819, ...\n -0.25881904510252076235, ...\n -1.0000000000000000000 ];\n x_vec = [ ...\n -5.0, ...\n 0.0, ...\n 1.0, ...\n 2.0, ...\n 3.0, ...\n 4.0, ...\n 5.0, ...\n 10.0, ...\n 15.0, ...\n 30.0, ...\n 45.0, ...\n 60.0, ...\n 75.0, ...\n 85.0, ...\n 86.0, ...\n 87.0, ...\n 88.0, ...\n 89.0, ...\n 90.0, ...\n 91.0, ...\n 105.0, ...\n 180.0 ];\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 x = 0.0;\n fx = 0.0;\n else\n x = x_vec(n_data);\n fx = fx_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/cos_degree_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.6884922782720162}} {"text": "\n% ----------------------------------------------------------------- %\n% Matlab Programs included the Appendix B in the book: %\n% Xin-She Yang, Engineering Optimization: An Introduction %\n% with Metaheuristic Applications %\n% Published by John Wiley & Sons, USA, July 2010 %\n% ISBN: 978-0-470-58246-6, Hardcover, 347 pages %\n% ----------------------------------------------------------------- %\n% Citation detail: %\n% X.-S. Yang, Engineering Optimization: An Introduction with %\n% Metaheuristic Application, Wiley, USA, (2010). %\n% % \n% http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470582464.html % \n% http://eu.wiley.com/WileyCDA/WileyTitle/productCd-0470582464.html %\n% ----------------------------------------------------------------- %\n% ===== ftp:// ===== ftp:// ===== ftp:// ======================= %\n% Matlab files ftp site at Wiley %\n% ftp://ftp.wiley.com/public/sci_tech_med/engineering_optimization %\n% ---------------------------------------------------------------- %\n\n\n% Design Optimization of a Pressure Vessel using fmincon %\n% This is essentially a different problem as integer multiples %\n% are not applied. If leaves an exercise to modify the program that %\n% the first two design variables are the integer multiples of 0.0625 %\n% ------------------------------------------------------------------ %\n\nfunction B7_pressure\n \n d=0.0625;\n % Linear inequality constraints\n A=[-1 0 0.0193 0;0 -1 0.00954 0;0 0 0 1];\n b=[0; 0; 240];\n % Simple bounds\n Lb=[d; d; 10; 10];\n Ub=[99*d; 99*d; 200; 200];\n x0=Lb+(Ub-Lb).*rand(size(Lb));\n options=optimset('Display','iter','TolFun',1e-08);\n [x,fval]=fmincon(@objfun,x0,A,b,[],[],Lb,Ub,@nonfun,options)\n\n% The objective function\nfunction f=objfun(x)\nf=0.6224*x(1)*x(3)*x(4)+1.7781*x(2)*x(3)^2 ...\n +3.1661*x(1)^2*x(4)+19.84*x(1)^2*x(3)\n\n% Nonlinear constraints\nfunction [g,geq]=nonfun(x)\n% Nonlinear inequality\n g=-pi*x(3)^2*x(4)-4*pi/3*x(3)^3+1296000;\n% Equality constraint [none]\n geq=[];\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/29682-engineering-optimization-an-introduction-with-metaheuristic-applications/B7_pressure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.6884351367778385}} {"text": "function lambda = combin_eigenvalues ( alpha, beta, n )\n\n%*****************************************************************************80\n%\n%% COMBIN_EIGENVALUES returns the eigenvalues of the COMBIN matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real ALPHA, BETA, scalars that define A.\n%\n% Input, integer N, the order of A.\n%\n% Output, real LAMBDA(N,1), the eigenvalues.\n%\n lambda = zeros ( n, 1 );\n\n lambda(1:n-1,1) = alpha;\n lambda(n,1) = alpha + n * beta;\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/combin_eigenvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.688435129802481}} {"text": "function h = histp(x, xmin, xmax, nbins)\n%HISTP\tHistogram estimate of 1-dimensional probability distribution.\n%\n%\tDescription\n%\n%\tHISTP(X, XMIN, XMAX, NBINS) takes a column vector X of data values\n%\tand generates a normalized histogram plot of the distribution. The\n%\thistogram has NBINS bins lying in the range XMIN to XMAX.\n%\n%\tH = HISTP(...) returns a vector of patch handles.\n%\n%\tSee also\n%\tDEMGAUSS\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\nndata = length(x);\n\nbins = linspace(xmin, xmax, nbins);\n\nbinwidth = (xmax - xmin)/nbins;\n\nnum = hist(x, bins);\n\nnum = num/(ndata*binwidth);\n\nh = bar(bins, num, 0.6);\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/netlab3.3/histp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.6884351265968606}} {"text": "function hermite_polynomial_test11 ( p, e )\n\n%*****************************************************************************80\n%\n%% HERMITE_POLYNOMIAL_TEST11 tests HEN_POWER_PRODUCT.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 February 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer P, the maximum degree of the polynomial factors.\n%\n% Input, integer E, the exponent of X in the integrand.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HERMITE_POLYNOMIAL_TEST11\\n' );\n fprintf ( 1, ' Compute a normalized probabilist''s Hermite polynomial power product table.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Tij = integral ( -oo < X < +oo ) X^E Hen(I,X) Hen(J,X) exp(-0.5*X*X) dx\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' where Hen(I,X) = normalized probabilist''s Hermite polynomial of degree I.\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Maximum degree P = %d\\n', p );\n fprintf ( 1, ' Exponent of X = %d\\n', e );\n\n table = hen_power_product ( p, e );\n\n r8mat_print ( p + 1, p + 1, table, ' Power weighted table:' );\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_polynomial/hermite_polynomial_test11.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.688435118721104}} {"text": "%% EXAMPLE 9: Multitaper-Welch.\n% Multitaper-Welch estimators provide lower variance estimates at a fixed\n% frequency resolution or higher frequency resolution at similar variance\n% compared to the standard algorithm. In this example, we retain the high\n% frequency resolution of a three block Welch estimate but significantly\n% reduce the variance of the SPOD spectrum by using 10 Slepian tapers.\n%\n% References:\n% [1] O. T. Schmidt, Spectral proper orthogonal decomposition using\n% multitaper estimates, Theor. Comput. Fluid Dyn., 2022, 1-14, \n% DOI 10.1007/s00162-022-00626-x, https://rdcu.be/cUtP3\n%\n% O. T. Schmidt (oschmidt@ucsd.edu)\n% Last revision: 5-Sep-2022\n\nclc, clear variables\naddpath('utils')\ndisp('Loading the entire test database might take a second...')\nload(fullfile('jet_data','jetLES.mat'),'p','x','r','dt');\n\n% trapezoidal quadrature weights for cylindrical coordinates\nintWeights = trapzWeightsPolar(r(:,1),x(1,:));\n\n%% Standard SPOD\n% SPOD with a large block size to get a high frequency resolution and\n% resolve the low-frequency regime.\nnFFT = 2048;\nnOvlp = nFFT/2;\n[L,P,f] = spod(p,nFFT,intWeights,nOvlp,dt);\n\n% Plot the SPOD spectrum and three leading modes at the frequency of\n% interest.\nf_plot = 0.24;\n[~,fi] = min(abs(f-f_plot));\nnBlk = size(L,2);\n\nfigure\nsubplot(5,2,[1 3])\nloglog(f,L)\nxlim([f(2) f(end)]), ylim([1e-9 1e-3])\nxlabel('frequency'), ylabel('SPOD mode energy')\ntitle('Welch (standard)')\nhold on\nplot([f(fi) f(fi)],ylim,'k:')\n\ncount = 5;\nfor mi = 1:3\n subplot(5,2,count)\n contourf(x,r,real(squeeze(P(fi,:,:,mi))),11,'edgecolor','none'), axis equal tight, caxis(max(abs(caxis))*[-1 1])\n xlabel('x'), ylabel('r'), title(['f=' num2str(f(fi),'%.2f') ', mode ' num2str(mi)])\n xlim([0 10]); ylim([0 2])\n count = count + 2;\nend\ndrawnow\n\n%% Multitaper-Welch SPOD\n% SPOD using a retangular window of length 256 and 50 snaphots overlap\n% 10 Slapian tapers by setting the time-halfbandwidth product to 5.5.\nbw = 5.5;\n[L,P,f] = spod(p,[nFFT bw],intWeights,nOvlp,dt);\n\n% Plot the SPOD spectrum and modes as before. Compared to the standard\n% algorithm, the variance of the spectrum has been reduced significanlty\n% and the modes are better converged.\nsubplot(5,2,[2 4])\nloglog(f,L(:,1:nBlk)), hold on\nloglog(f,L(:,nBlk+1:end),'Color',[0.75 0.75 0.75]), hold on\nxlim([f(2) f(end)]), ylim([1e-9 1e-3])\nxlabel('frequency'), ylabel('SPOD mode energy')\ntitle(['Multitaper-Welch, b_w=' num2str(bw)])\n\nhold on\nplot([f(fi) f(fi)],ylim,'k:')\n\ncount = 6;\nfor mi = 1:3\n subplot(5,2,count)\n contourf(x,r,real(squeeze(P(fi,:,:,mi))),11,'edgecolor','none'), axis equal tight, caxis(max(abs(caxis))*[-1 1])\n xlabel('x'), ylabel('r'), title(['f=' num2str(f(fi),'%.2f') ', mode ' num2str(mi)])\n xlim([0 10]); ylim([0 2])\n count = count + 2;\nend\n", "meta": {"author": "SpectralPOD", "repo": "spod_matlab", "sha": "12d6d7d098eb3247ef0d8a502e2ce9600968869c", "save_path": "github-repos/MATLAB/SpectralPOD-spod_matlab", "path": "github-repos/MATLAB/SpectralPOD-spod_matlab/spod_matlab-12d6d7d098eb3247ef0d8a502e2ce9600968869c/example_9_multitaperWelch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.6884351147832255}} {"text": "function bsv_test06 ( )\n\n%*****************************************************************************80\n%\n%% BSV_TEST06 estimates the expected value of the zero crossing.\n%\n% Discussion:\n%\n% We assume that the left boundary condition ALPHA can vary like\n% a Gaussian variable with mean 1 and standard deviation 0.05.\n%\n% Estimate the integral:\n%\n% E(X0(ALPHA)) = integral ( -oo < alpha < +oo ) x0(alpha) e^(-0.5*alpha^2/sigma^2) dalpha\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 April 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BSV_TEST06:\\n' );\n fprintf ( 1, ' For the Burgers equation on [A,B] with viscosity NU and \\n' );\n fprintf ( 1, ' boundary conditions U(A)=ALPHA, U(B) = BETA,\\n' );\n fprintf ( 1, ' with ALPHA and BETA of opposite sign,\\n' );\n fprintf ( 1, ' let X0 be the point where the solution U changes sign.\\n' );\n fprintf ( 1, ' Assume ALPHA is Gaussian with mean 0 and standard deviation 0.05.\\n' );\n fprintf ( 1, ' Estimate E(X0(ALPHA)) using M Gaussian samples.\\n' );\n\n a = -1.0;\n b = +1.0;\n beta = -1.0;\n nu = 0.1;\n n = 81;\n output = 0;\n\n x = linspace ( a, b, n );\n%\n% Monte Carlo Estimate.\n% Choose M normal random samples with the correct STD, \n% find X0 for each, and average.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' M E(X0(ALPHA)) estimate\\n' );\n fprintf ( 1, '\\n' );\n\n for j = 4 : 12\n\n m = 2^j;\n mu = 1.0;\n sigma = 0.05;\n alpha_vec = mu + 0.05 * randn ( m, 1 );\n\n x0_bar = 0.0;\n\n for i = 1 : m\n alpha = alpha_vec(i);\n print = 0;\n u = bsv ( a, b, alpha, beta, nu, n, output );\n x0 = bsv_crossing ( a, b, n, x, u );\n x0_bar = x0_bar + x0;\n end\n\n x0_bar = x0_bar / m;\n\n fprintf ( 1, ' %4d %14.6g\\n', m, x0_bar );\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/burgers_steady_viscous/bsv_test06.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6884225552024203}} {"text": "function [A, B] = convertHypergraphToBipartiteGraph(S, printLevel)\n% Converts a hypergraph into an undirected bipartite graph\n%\n% USAGE:\n%\n% [A, B] = convertHypergraphToBipartiteGraph(S, printLevel)\n%\n% INPUT:\n% S: `m x n` matrix with `m` nodes and `n` hyperedges\n% printLevel: timer\n%\n% OUTPUTS:\n% A: `(m+n) x (m+n)` adjacency matrix for an undirected graph (symmetric)\n% B: `(m+n) x nnz(S)` incidence matrix for a directed graph\n%\n% .. Author: - Ronan Fleming 2013\n\nif ~exist('printLevel', 'var')\n printLevel = 0;\nend\n\n[nMet, nRxn] = size(S);\n\nif printLevel\n tic\nend\n\nS = sparse(S);\nnnzS = nnz(S);\n\n[row, col, v] = find(S);\nnumbers = 1:nnzS;\nrowIndices = zeros(2 * nnzS, 1);\ncolIndices = zeros(2 * nnzS, 1);\n\nvalues = zeros(2 * nnzS, 1);\nrowIndices(1:2:end) = row;\ncolIndices(1:2:end) = numbers;\nvalues(1:2:end) = v;\n\nrowIndices(2:2:end) = nMet + col;\ncolIndices(2:2:end) = numbers;\nvalues(2:2:end) = sign(v) * -1;\n\n% incidence matrix for a bipartite graph\nB = sparse(rowIndices, colIndices, values);\nif printLevel\n toc\nend\n\nif printLevel\n tic\nend\n\n% create the adjacency matrix from undirected incidence matrix\nA = inc2adj(B ~= 0);\nif printLevel\n toc\nend\n\n% sanity check\nassert(all(sum(B ~= 0, 1) == 2))\nend\n\n% old code\n% %converts to bipartite hypergraph\n% A=sparse(nMet+nRxn,nMet+nRxn);\n%\n% for j=1:nRxn\n% for i=1:nMet\n% if S(i,j)~=0\n% A(i,nMet+j)=1;\n% A(nMet+j,i)=1;\n% end\n% end\n% end\n\n% old methods\n% switch method\n% case 1\n% %incidence matrix for a bipartite graph\n% B=sparse(nMet+nRxn,nnzS);\n% k=1;\n% for j=1:nRxn\n% for i=1:nMet\n% if S(i,j)~=0\n% if S(i,j)<0\n% B(i,k)=S(i,j);\n% B(nMet+j,k)=1;\n% else\n% B(i,k)=S(i,j);\n% B(nMet+j,k)=-1;\n% end\n% k=k+1;\n%\n% end\n% end\n% end\n% case 2\n% rowIndices=zeros(2*nnzS,1);\n% colIndices=zeros(2*nnzS,1);\n% values=zeros(2*nnzS,1);\n% k=1;\n% p=1;\n% for j=1:nRxn\n% for i=1:nMet\n% if S(i,j)~=0\n% if S(i,j)<0\n% rowIndices(p)=i;\n% colIndices(p)=k;\n% values(p)=S(i,j);\n% p=p+1;\n% rowIndices(p)=nMet+j;\n% colIndices(p)=k;\n% values(p)=1;\n% p=p+1;\n% else\n% rowIndices(p)=i;\n% colIndices(p)=k;\n% values(p)=S(i,j);\n% p=p+1;\n% rowIndices(p)=nMet+j;\n% colIndices(p)=k;\n% values(p)=-1;\n% p=p+1;\n% end\n% k=k+1;\n% end\n% end\n% end\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/topology/graphHypergraphConversion/convertHypergraphToBipartiteGraph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6884225496721358}} {"text": "function y = ainv_x ( x, R, k )\n\n%*****************************************************************************80\n%\n%% AINV_X computes inverse(A)*x.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 February 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X(*), the vector to be multiplied by inverse(A).\n%\n% Input, character R, the first argument to the NUMGRID command.\n%\n% Input, integer K, the order of the grid.\n%\n% Output, real Y, the value of inverse(A)*X.\n%\n y = ( delsq ( numgrid ( R, k ) ) ) \\ x;\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/arpack/ainv_x.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6884225454797366}} {"text": "function result=robpca(x,varargin)\n\n%ROBPCA is a 'ROBust method for Principal Components Analysis'. \n% It is resistant to outliers in the data. The robust loadings are computed\n% using projection-pursuit techniques and the MCD method. \n% Therefore ROBPCA can be applied to both low and high-dimensional data sets.\n% In low dimensions, the MCD method is applied (see mcdcov.m).\n%\n% The ROBPCA method is described in\n% Hubert, M., Rousseeuw, P.J., Vanden Branden, K. (2005), ROBPCA: a\n% new approach to robust principal components analysis, Technometrics, 47, 64-79.\n%\n%\n% To select the number of principal components, a robust PRESS (predicted\n% residual sum of squares) curve is drawn, based on a fast algorithm for\n% cross-validation. This approach is described in:\n%\n% Hubert, M., Engelen, S. (2007),\n% \"Fast cross-validation of high-breakdown resampling algorithms for PCA\",\n% Computational Statistics and Data Analysis, 51, 5013-5024.\n%\n% ROBPCA is designed for normally distributed data. If the data are skewed,\n% a modification of ROBPCA is available, based on the adjusted outlyingness \n% (see adjustedoutlyingness.m). This method is described in:\n%\n% Hubert, M., Rousseeuw, P.J., Verdonck, T. (2008),\n% \"Robust PCA for skewed data and its outlier map\", Computational Statistics\n% and Data Analysis, in press.\n%\n% For the up-to-date reference, please consult the website:\n% wis.kuleuven.be/stat/robust.html\n%\n% Required input arguments:\n% x : Data matrix (observations in the rows, variables in the\n% columns)\n%\n% Optional input arguments:\n% k : Number of principal components to compute. If k is missing, \n% or k = 0, a scree plot and a press curve are drawn which allows you to select\n% the number of principal components. \n% kmax : Maximal number of principal components to compute (default = 10).\n% If k is provided, kmax does not need to be specified, unless k is larger\n% than 10. \n% alpha : (1-alpha) measures the fraction of outliers the algorithm should\n% resist. Any value between 0.5 and 1 may be specified (default = 0.75). \n% h : (n-h+1) measures the number of outliers the algorithm should \n% resist. Any value between n/2 and n may be specified. (default = 0.75*n)\n% Alpha and h may not both be specified.\n% mcd : If equal to one: when the number of variables is sufficiently small,\n% the loadings are computed as the eigenvectors of the MCD covariance matrix, \n% hence the function 'mcdcov.m' is automatically called. The number of \n% principal components is then taken as k = rank(x). (default)\n% If equal to zero, the robpca algorithm is always applied.\n% plots : If equal to one, a scree plot, a press curve and a robust score outlier map are\n% drawn (default). If the input argument 'classic' is equal to one, \n% the classical plots are drawn as well.\n% If 'plots' is equal to zero, all plots are suppressed (unless k is missing,\n% then the scree plot and press curve are still drawn).\n% See also makeplot.m\n% labsd : The 'labsd' observations with largest score distance are\n% labeled on the outlier map. (default = 3)\n% labod : The 'labod' observations with largest orthogonal distance are\n% labeled on the outlier map. default = 3) \n% classic : If equal to one, the classical PCA analysis will be performed\n% (see also cpca.m). (default = 0)\n% scree : If equal to one, a scree plot is drawn. If k is given as input, the default value is 0, else the default value is one.\n% press : If equal to one, a plot of robust press-values is drawn. \n% If k is given as input, the default value is 0, else the default value is one.\n% If the input argument 'skew' is equal to one, no plot is\n% drawn.\n% robpcamcd : If equal to one (default), the whole robpca procedure is run (computation of outlyingness and\n% MCD).\n% If equal to zero, the program stops after the computation of the outlyingness. The \n% robust eigenvectors then correspond with the eigenvectors of the covariance matrix \n% of the h observations with smallest outlyingness. This yields the same\n% PCA subspace as the full robpca, but not the same eigenvectors and eigenvalues.\n% skew : If equal to zero the regular robpca is run. If equal to\n% one, the adjusted robpca algorithm for skewed data is run.\n%\n% I/O: result=robpca(x,'k',k,'kmax',10,'alpha',0.75,'h',h,'mcd',1,'plots',1,'labsd',3,'labod',3,'classic',0);\n% The user should only give the input arguments that have to change their default value.\n% The name of the input arguments needs to be followed by their value.\n% The order of the input arguments is of no importance.\n% \n% Examples: \n% result=robpca(x,'k',3,'alpha',0.65,'plots',0)\n% result=robpca(x,'alpha',0.80,'kmax',15,'labsd',5)\n%\n% The output of ROBPCA is a structure containing \n% \n% result.P : Robust loadings (eigenvectors)\n% result.L : Robust eigenvalues \n% result.M : Robust center of the data\n% result.T : Robust scores \n% result.k : Number of (chosen) principal components\n% result.kmax : Maximal number of principal components\n% result.alpha : see interpretation in the list of input arguments\n% result.h : The quantile h used throughout the algorithm\n% result.Hsubsets : A structure that contains H0, H1 and Hfreq:\n% H0 : The h-subset that contains the h points with the smallest outlyingness. \n% H1 : The optimal h-subset of mcdcov. \n% Hfreq : The subset of h points which are the most frequently selected during the mcdcov\n% algorithm.\n% result.sd : Robust score distances within the robust PCA subspace\n% result.od : Orthogonal distances to the robust PCA subspace \n% result.cutoff : Cutoff values for the robust score and orthogonal distances\n% result.flag : The observations whose score distance is larger than result.cutoff.sd (==> result.flag.sd)\n% or whose orthogonal distance is larger than result.cutoff.od (==> result.flag.od)\n% can be considered as outliers and receive a flag equal to zero (result.flag.all).\n% The regular observations receive a flag 1.\n% result.class : 'ROBPCA' \n% result.classic : If the input argument 'classic' is equal to one, this structure\n% contains results of the classical PCA analysis (see also cpca.m). \n%\n% Short description of the method:\n%\n% Let n denote the number of observations, and p the number of original variables,\n% then ROBPCA finds a robust center (p x 1) of the data M and a loading matrix P which \n% is (p x k) dimensional. Its columns are orthogonal and define a new coordinate\n% system. The scores (n x k) are the coordinates of the centered observations with \n% respect to the loadings: T=(X-M)*P. \n% Note that ROBPCA also yields a robust covariance matrix (often singular) which\n% can be computed as\n% cov=out.P*out.L*out.P'\n%\n% To select the number of principal components, it is useful to look at the scree plot which\n% shows the eigenvalues, and the press curve which displays a weighted sum of the squared \n% cross-validated orthogonal distances. \n% The outlier map visualizes the observations by plotting their orthogonal\n% distance to the robust PCA subspace versus their robust distances \n% within the PCA subspace. This allows to classify the data points into 4 types:\n% regular observations, good leverage points, bad leverage points and \n% orthogonal outliers. \n%\n% This function is part of LIBRA: the Matlab Library for Robust Analysis,\n% available at: \n% http://wis.kuleuven.be/stat/robust\n%\n% Written by Mia Hubert, Sabine Verboven, Karlien Vanden Branden, Sanne Engelen, Tim Verdonck\n% Last Update: 17/06/2003, 03/07/2006, 31/07/2007\n% Last Revision: 27/03/2008, 09/06/2008\n\n%\n% initialization with defaults\n%\ndata=x;\n[n,p]=size(data);\n\n% First Step: classical PCA on data\nif n < p\n [P1,T1,L1,r,Xc,clm]=kernelEVD(data);\nelse\n\t[P1,T1,L1,r,Xc,clm]=classSVD(data);\nend\n% dim(P1): p x r\n \nif r==0\n error('All data points collapse!')\nend\n\nniter=100;\ncounter=1;\nkmax=min([10,floor(n/2),r]);\nk=0;\nalfa=0.75;\nh=min(floor(2*floor((n+kmax+1)/2)-n+2*(n-floor((n+kmax+1)/2))*alfa),n);\nlabsd=3;\nlabod=3;\nplots=1;\nscree = 1;\npress = 1;\nmcd=1; % user wants the mcd approach (in case n>>p)\nrobpcamcd = 1;\ncutoff = 0.975;\nskew=0;\n% default is a structure needed for input checking\ndefault=struct('alpha',alfa,'h',h,'labsd',labsd,'labod',labod,...\n 'k',k,'plots',plots,'kmax',kmax,'mcd',mcd,'classic',0,'scree',scree,'press',press,'robpcamcd',robpcamcd,'cutoff',cutoff,'skew',0);\nlist=fieldnames(default);\noptions=default; %input by user\nIN=length(list);\ni=1;\n%\nif nargin==2\n error('Incorrect number of input arguments!')\nend\ndummy = 0; %Assume we didn't get h or alpha, unless we find it below.\nif nargin>2\n %\n %placing inputfields in array of strings\n %\n for j=1:nargin-2\n if rem(j,2)~=0\n chklist{i}=varargin{j};\n i=i+1;\n end\n end \n dummy=sum(strcmp(chklist,'h')+2*strcmp(chklist,'alpha')); %checking if h and alpha are provided both or not\n switch dummy\n case 0 % Take on default values \n options.alpha=alfa; \n if any(strcmp(chklist,'kmax'))\n for j=1:nargin-2 % searching the index of the accompanying field\n if rem(j,2)~=0 % fieldnames are placed on odd index\n if strcmp('kmax',varargin{j})\n I=j;\n end\n end\n end\n options=setfield(options,'kmax',varargin{I+1});\n kmax = max(min([floor(options.kmax),floor(n/2),r]),1); %acceptable kmax\n options.h=min(floor(2*floor((n+kmax+1)/2)-n+2*(n-floor((n+kmax+1)/2))*alfa),n); %depends on kmax, so if kmax is given by user, get it first!\n else %kmax is not given by user\n options.h=h;\n end\n case 3\n error('Both inputarguments alpha and h are provided. Only one is required.')\n end\n \n %\n % Checking which default parameters have to be changed\n % and keep them in the structure 'options'.\n %\n while counter<=IN \n index=strmatch(list(counter,:),chklist,'exact');\n if ~isempty(index) % in case of similarity\n for j=1:nargin-2 % searching the index of the accompanying field\n if rem(j,2)~=0 % fieldnames are placed on odd index\n if strcmp(chklist{index},varargin{j})\n I=j;\n end\n end\n end\n options=setfield(options,chklist{index},varargin{I+1});\n index=[];\n end\n counter=counter+1;\n end\n options.h=floor(options.h);\n options.kmax=floor(options.kmax);\n options.k=floor(options.k);\n kmax=max(min([options.kmax,floor(n/2),r]),1);\n labod=max(0,min(floor(options.labod),n));\n labsd=max(0,min(floor(options.labsd),n));\n k=options.k;\n \n if k<0 \n k=0;\n elseif k > kmax\n k=kmax;\n mess=sprintf(['Attention (robpca.m): The number of principal components, k = ',num2str(options.k)...\n ,'\\n is larger than kmax= ',num2str(kmax),'; k is set to ',num2str(kmax)]);\n disp(mess)\n end\n if dummy==1 % checking input variable h\n options.alpha=options.h/n;\n if k==0\n if options.h < floor((n+kmax+1)/2 )\n options.h=floor((n+kmax+1)/2);\n options.alpha=options.h/n;\n mess=sprintf(['Attention (robpca.m): h should be larger than (n+kmax+1)/2.\\n',...\n 'It is set to its minimum value ',num2str(options.h)]);\n disp(mess)\n end \n else\n if options.h < floor((n+k+1)/2)\n options.h=floor((n+k+1)/2);\n options.alpha=options.h/n;\n mess=sprintf(['Attention (robpca.m): h should be larger than (n+k+1)/2.\\n',...\n 'It is set to its minimum value ',num2str(options.h)]);\n disp(mess)\n end\n end\n if options.h > n\n options.alpha=0.75;\n if k==0\n options.h=floor(2*floor((n+kmax+1)/2)-n+2*(n-floor((n+kmax+1)/2))*options.alpha);\n else\n options.h=floor(2*floor((n+k+1)/2)-n+2*(n-floor((n+k+1)/2))*options.alpha);\n end \n mess=sprintf(['Attention (robpca.m): h should be smaller than n. \\n',...\n 'It is set to its default value ',num2str(options.h)]);\n disp(mess)\n end\n elseif dummy==2 %checking input variable alpha\n if options.alpha < 0.5\n options.alpha=0.5;\n mess=sprintf(['Attention (robpca.m): Alpha should be larger than 0.5.\\n',...\n 'It is set to 0.5.']);\n disp(mess)\n end\n if options.alpha > 1\n options.alpha=0.75;\n mess=sprintf(['Attention (robpca.m): Alpha should be smaller than 1. \\n',...\n 'It is set to 0.75.']);\n disp(mess)\n end\n if k==0\n options.h=floor(2*floor((n+kmax+1)/2)-n+2*(n-floor((n+kmax+1)/2))*options.alpha);\n else\n options.h=floor(2*floor((n+k+1)/2)-n+2*(n-floor((n+k+1)/2))*options.alpha);\n end \n end\n alfa=options.alpha;\n dummyh = strcmp(chklist,'h');\n dummykmax = strcmp(chklist,'kmax');\n % if all(dummyh == 0) & any(dummykmax) & k==0\n % h = min(floor(2*floor((n+kmax+1)/2)-n+2*(n-floor((n+kmax+1)/2))*alfa),n);\n % end\n if all(dummyh == 0)&& any(dummykmax) %kmax was given by the user\n if k==0\n options.h=floor(2*floor((n+kmax+1)/2)-n+2*(n-floor((n+kmax+1)/2))*options.alpha);\n else\n options.h=floor(2*floor((n+k+1)/2)-n+2*(n-floor((n+k+1)/2))*options.alpha);\n end\n elseif all(dummyh == 0) && ~any(dummykmax) %kmax is the default value\n if k==0\n options.h=floor(2*floor((n+kmax+1)/2)-n+2*(n-floor((n+kmax+1)/2))*options.alpha);\n else\n options.h=floor(2*floor((n+k+1)/2)-n+2*(n-floor((n+k+1)/2))*options.alpha);\n end\n end\n h=options.h;\n dummyscree = strcmp(chklist,'scree');\n dummypress = strcmp(chklist,'press');\n if all(dummyscree == 0)\n if k~=0\n options.scree = 0;\n end\n end\n if all(dummypress == 0)\n if k~=0\n options.press = 0;\n end\n end\n scree = options.scree;\n press = options.press;\n labsd=floor(max(0,min(options.labsd,n)));\n labod=floor(max(0,min(options.labod,n)));\n plots=options.plots;\n mcd=options.mcd;\n robpcamcd = options.robpcamcd;\n cutoff = options.cutoff;\n skew = options.skew;\n if skew==1\n press=0; %press curve not available for skewed data\n end\nend\n%\n% MAIN PART\n%\nX=T1;\ncenter=clm;\nrot=P1;\n% Depending on n and p, perform MCD or ROBPCA:\n% p << n => MCD\np1=size(X,2);\nif p1<=min(floor(n/5),kmax) && mcd && (skew==0)\n options.h=h;\n [res,raw]=mcdcov(X,'h',h,'plots',0);\n [U,S,P]=svd(res.cov,0);\n L=diag(S);\n if k~=0\n options.k=min(k,p1);\n else\n bdwidth=5;\n topbdwidth=30;\n set(0,'Units','pixels');\n scnsize=get(0,'ScreenSize');\n pos1=[bdwidth, 1/3*scnsize(4)+bdwidth, scnsize(3)/2-2*bdwidth, scnsize(4)/2-(topbdwidth+bdwidth)];\n pos2=[pos1(1)+scnsize(3)/2, pos1(2), pos1(3), pos1(4)];\n if press == 1\n outcvMcd = cvMcd(X,p1,res,h);\n figure('Position',pos1)\n set(gcf,'Name', 'PRESS curve','NumberTitle', 'off');\n plot(1:p1,outcvMcd.press,'o-')\n title('MCD')\n xlabel('number of LV')\n ylabel('R-PRESS')\n end\n if scree == 1\n figure('Position',pos2)\n screeplot(L,'MCD');\n end\n if (scree == 1) || (press == 1)\n cumperc = cumsum(L)./sum(L);\n disp(['The cumulative percentage of variance explained by the first ',num2str(kmax),' components is:']);\n disp(num2str(cumperc'));\n disp(['How many principal components would you like to retain? Max = ',num2str(kmax),'. ']);\n k=input('');\n end\n % to close the figures.\n if scree == 1\n close\n end\n if press == 1\n close\n end\n end\n options.k = k;\n T=(X-repmat(res.center,size(X,1),1))*U;\n out.M=center+res.center*rot';\n out.L=L(1:options.k)';\n out.P=rot*U(:,1:options.k);\n out.T=T(:,1:options.k);\n out.h=h;\n out.k=options.k;\n out.alpha=alfa;\n out.Hsubsets.H0 = res.Hsubsets.Hopt;\n out.Hsubsets.H1 = [];\n out.Hsubsets.Hfreq = res.Hsubsets.Hfreq;\n out.skew=skew;\nelse\n % p > n => ROBPCA\n niter=100;\n seed=0;\n if h~=n\n if skew==0\n B=twopoints(T1,250,seed); %n*ri\n for i=1:size(B,1)\n Bnorm(i)=norm(B(i,:),2);\n end\n Bnormr=Bnorm(Bnorm > 1.e-12); %ndirect*1\n B=B(Bnorm > 1.e-12,:); %ndirect*n\n A=diag(1./Bnormr)*B; %ndirect*n\n %projected points in columns\n Y=T1*A';%n*ndirect\n m=length(Bnormr);\n Z=zeros(n,m);\n for i=1:m\n [tmcdi,smcdi,weights]=unimcd(Y(:,i),h);\n if smcdi<1.e-12\n r2=rank(data(weights,:));\n if r2==1\n error(['At least ',num2str(sum(weights)),' obervations are identical.']);\n end\n else\n Z(:,i)=abs(Y(:,i)-tmcdi)/smcdi;\n end\n end\n d=max(Z,[],2);\n else %adjusted robpca for skewed data\n outAO=adjustedoutlyingness(T1,'ndir',min(250*p,2500));\n d=outAO.adjout;\n end\n [ds,is]=sort(d);\n Xh=T1(is(1:h),:); % Xh contains h (good) points out of Xcentr\n [P2,T2,L2,r2,Xm,clmX]=classSVD(Xh);\n out.Hsubsets.H0 = is(1:h);\n Tn=(T1-repmat(clmX,n,1))*P2;\n else\n P2=eye(r);\n Tn=T1;\n L2=L1;\n r2=r;\n out.Hsubsets.H0=1:n;\n Xm=T1;\n clmX=zeros(1,size(T1,2));\n end\n\n %dim(P2) = r x r2\n L=L2;\n kmax=min(r2,kmax);\n\n % choice of k:\n %-------------\n bdwidth=5;\n topbdwidth=30;\n set(0,'Units','pixels');\n scnsize=get(0,'ScreenSize');\n pos1=[bdwidth, 1/3*scnsize(4)+bdwidth, scnsize(3)/2-2*bdwidth, scnsize(4)/2-(topbdwidth+bdwidth)];\n pos2=[pos1(1)+scnsize(3)/2, pos1(2), pos1(3), pos1(4)];\n\n if press == 1\n disp('The robust press curve based on cross-validation is now computed.')\n outprMCDkmax = projectMCD(Tn,L,kmax,h,niter,rot,P1,P2,center,cutoff);\n if size(out.Hsubsets.H0,2)==1\n out.Hsubsets.H0=out.Hsubsets.H0';\n end\n outprMCDkmax.Hsubsets.H0 = out.Hsubsets.H0;\n outpress = cvRobpca(data,kmax,outprMCDkmax,0,h);\n figure('Position',pos1)\n set(gcf,'Name', 'PRESS curve','NumberTitle', 'off');\n plot(1:kmax,outpress.press,'o-')\n title('ROBPCA')\n xlabel('Number of LV')\n ylabel('R-PRESS')\n else\n if size(out.Hsubsets.H0,2)==1\n out.Hsubsets.H0=out.Hsubsets.H0';\n end\n end\n\n if scree == 1\n figure('Position',pos2)\n screeplot(L(1:kmax),'ROBPCA')\n end\n\n if (scree == 1)||(press == 1)\n cumperc = (cumsum(L(1:kmax))./sum(L))';\n disp(['The cumulative percentage of variance explained by the first ',num2str(kmax),' components is:']);\n disp(num2str(cumperc));\n disp(['How many principal components would you like to retain? Max = ',num2str(kmax),'.']);\n k=input('');\n k=max(min(min(r2,k),kmax),1);\n % we compute again the robpca results for a specific k value. alpha\n % and h can change again, because until now they were based on the kmax\n % value.\n if dummy == 2\n options.h=floor(2*floor((n+k+1)/2)-n+2*(n-floor((n+k+1)/2))*alfa);\n %if dummy == 1 no changes needed\n elseif dummy~=1\n options.h=floor(2*floor((n+k+1)/2)-n+2*(n-floor((n+k+1)/2))*options.alpha);\n end\n h=options.h;\n % to close the figures.\n if scree == 1\n close\n end\n if press == 1\n close\n end\n else\n k=min(min(r2,k),kmax);\n end\n \n if k~=r % extra reweighting step\n XRc=T1-repmat(clmX,n,1);\n Xtilde=XRc*P2(:,1:k)*P2(:,1:k)';\n Rdiff = XRc-Xtilde;\n for i=1:n\n odh(i,1)=norm(Rdiff(i,:));\n end\n if skew==0\n [m,s]=unimcd(odh.^(2/3),h);\n cutoffodh = sqrt(norminv(cutoff,m,s).^3);\n else %adjusted robpca for skewed data\n mcodh=mc(odh);\n if mcodh>0\n cutoffodh = prctile(odh,75)+1.5*exp(3*mcodh)*iqr(odh);\n else\n cutoffodh = prctile(odh,75)+1.5*iqr(odh);\n end\n ttup = sort(-odh(odhrh\n k = rh;\n end\n end\n center=center+clmX*rot';\n rot=rot*P2(:,1:k);\n Tn=(T1-repmat(clmX,n,1))*P2;\n \n % if only the subspace is important, not the PC themselves: do not\n % perform MCD anymore.\n if ~robpcamcd\n out.P = rot; %=P1*P2(:,1:k);\n out.T = Tn(:,1:k);\n out.M = center;\n out.L = Lh;\n out.k = k;\n out.h = h;\n out.alpha = alfa;\n out.kmax=kmax;\n out.skew=skew; \n end\n \n % projection, mcd\n %-----------------\n if skew==0\n outpr = projectMCD(Tn,L,k,h,niter,rot,P1,P2,center,cutoff);\n else %adjusted robpca for skewed data\n outpr = projectAO(Tn,k,h,rot,center);\n end\n out.T = outpr.T;\n out.P = outpr.P;\n out.M = outpr.M;\n out.L = outpr.L;\n out.k = k;\n out.kmax=kmax;\n out.h = h;\n out.alpha = alfa;\n out.skew = skew;\n if skew==0\n out.Hsubsets.H1 = outpr.Hsubsets.H1;\n out.Hsubsets.Hfreq = outpr.Hsubsets.Hfreq;\n else\n out.AO=outpr.AO;\n out.cutoff.AO=outpr.cutoff.AO;\n end\nend\n \n% Classical analysis\nif options.classic==1\n out.classic.P=P1(:,1:out.k);\n out.classic.L=L1(1:out.k)';\n out.classic.M=clm;\n out.classic.T=T1(:,1:out.k);\n out.classic.k=out.k;\n out.classic.Xc=Xc;\nend\n\noutpr = out;\n\n% Calculation of the distances, flags\n%-------------------------------------\n\nif options.classic == 1\n outDist = CompDist(data,r,outpr,cutoff,robpcamcd,out.classic);\nelse\n outDist = CompDist(data,r,outpr,cutoff,robpcamcd);\nend\n\nout.sd = outDist.sd;\nout.cutoff.sd = outDist.cutoff.sd;\nout.od = outDist.od;\nout.cutoff.od = outDist.cutoff.od;\nout.flag = outDist.flag;\nout.class = outDist.class;\nout.classic = outDist.classic;\nif options.classic == 1\n out.classic.sd = outDist.classic.sd;\n out.classic.od = outDist.classic.od;\n out.classic.cutoff.sd = outDist.classic.cutoff.sd;\n out.classic.cutoff.od = outDist.classic.cutoff.od;\n out.classic.class = outDist.classic.class;\n out.classic.flag = outDist.classic.flag;\nend \n \n\nresult=struct('P',{out.P},'L',{out.L},'M',{out.M},'T',{out.T},'k',{out.k},'kmax',{kmax},'alpha',{out.alpha},...\n 'h',{out.h},'Hsubsets',{out.Hsubsets},'sd', {out.sd},'od',{out.od},'cutoff',{out.cutoff},'flag',out.flag',...\n 'class',{out.class},'classic',{out.classic});\n\n% Plots\ntry\n if plots && options.classic\n makeplot(result,'classic',1,'labsd',labsd,'labod',labod)\n elseif plots\n makeplot(result,'labsd',labsd,'labod',labod) \n end\ncatch %output must be given even if plots are interrupted \n %> delete(gcf) to get rid of the menu \nend\n\n%--------------------------------------------------------------------------\nfunction outprMCD = projectMCD(Tn,L,k,h,niter,rot,P1,P2,center,cutoff)\n\n% this function performs the last part of ROBPCA when k is determined.\n% input : \n% Tn : the projected data\n% L : the matrix of the eigenvalues\n% k : the number of components\n% h : lower bound for regular observations\n% niter : the number of iterations\n% rot : the rotation matrix\n% P1, P2: the different eigenvector matrices after each transformation\n% center : the classical center of the data\n\nX2=Tn(:,1:k);\nn = size(X2,1);\nrot=rot(:,1:k);\n% first apply c-step with h points from first step,i.e. those that\n% determine the covariance matrix after the c-steps have converged.\nmah=libra_mahalanobis(X2,zeros(size(X2,2),1),'cov',L(1:k));\noldobj=prod(L(1:k));\nP4=eye(k); \nkorig=k;\nfor j=1:niter\n [mahs,is]=sort(mah);\n Xh=X2(is(1:h),:);\n [P,T,L,r3,Xm,clmX]=classSVD(Xh);\n obj=prod(L);\n X2=(X2-repmat(clmX,n,1))*P;\n center=center+clmX*rot';\n rot=rot*P;\n mah=libra_mahalanobis(X2,zeros(size(X2,2),1),'cov',diag(L));\n P4=P4*P;\n if ((r3==k) && (abs(oldobj-obj) < 1.e-12))\n break;\n else\n oldobj=obj;\n j=j+1;\n if r3 < k\n j=1;\n k=r3;\n end\n end\nend\n% dim(P4): k x k0 with k0 <= k but denoted as k\n% dim X2: n x k0\n% perform mcdcov on X2\n[zres,zraw]= mcdcov(X2,'plots',0,'ntrial',250,'h',h,'file',0);\nout.resMCD = zres;\nif zraw.objective < obj\n z = zres;\n out.Hsubsets.H1 = zres.Hsubsets.Hopt;\nelse\n sortmah = sort(mah);\n if h==n\n factor=1;\n else\n factor = sortmah(h)/chi2inv(h/n,k);\n end\n mah = mah/factor;\n weights = mah <= chi2inv(cutoff,k);\n [center_noMCD,cov_noMCD] = weightmecov(X2,weights);\n mah = libra_mahalanobis(X2,center_noMCD,'cov',cov_noMCD);\n z.flag = (mah <= chi2inv(cutoff,k));\n z.center = center_noMCD;\n z.cov = cov_noMCD;\n out.Hsubsets.H1 = is(1:h);\nend\ncovf=z.cov;\ncenterf=z.center;\n[P6,L]=eig(covf);\n[L,I]=greatsort(diag(real(L)));\nP6=P6(:,I);\nout.T=(X2-repmat(centerf,n,1))*P6;\nP=P1*P2;\nout.P=P(:,1:korig)*P4*P6;\ncenterfp=center+centerf*rot';\nout.M=centerfp;\nout.L=L';\nout.k=k;\nout.h=h;\n\n% creation of Hfreq\nout.Hsubsets.Hfreq = zres.Hsubsets.Hfreq(1:h);\n \noutprMCD = out;\n%----------------------------------------------------------------------------\nfunction outprAO = projectAO(Tn,k,h,rot,center)\n\n% this function performs the last part of ROBPCA when k is determined.\n% input :\n% Tn : the projected data\n% k : the number of components\n% h : lower bound for regular observations\n% rot : the rotation matrix\n% center : the classical center of the data\n\nseed=0;\nX2=Tn(:,1:k);\n[n,p]=size(X2);\noutAO=adjustedoutlyingness(X2,'ndir',min(250*p,2500));\nAO=outAO.adjout;\ncutoffAO=outAO.cutoff;\nindexset = find(AO<=cutoffAO)';\n%SVD\n[P6,T6,L6,r6,Xm6,clmX6]=classSVD(X2(indexset,:));\nout.T = (X2-repmat(clmX6,n,1))*P6;\nout.P = rot*P6;\nout.M = center+clmX6*rot';\nout.L = L6;\nout.k = k;\nout.h = h;\nout.AO=AO;\nout.cutoff.AO=cutoffAO;\noutprAO=out;\n\n%--------------------------------------------------------------------------------\nfunction outDist = CompDist(data,r,out,cutoff,robpcamcd,classic)\n\n% Calculates the distances.\n% input: data : the original data\n% r : the rank of the data\n% out is a structure that contains the results of the PCA.\n% classic: an optional structure:\n% classic.P1\n% classic.T1\n% classic.L1\n% classic.clm\n% classic.Xc\n\nif nargin < 6\n options.classic = 0;\nelse\n options.classic = 1;\nend\n\nn = size(data,1);\np = size(data,2);\nk = out.k;\nskew=out.skew;\n\n% Computing distances \n% Robust score distances in robust PCA subspace\nif robpcamcd\n if skew==0\n out.sd=sqrt(libra_mahalanobis(out.T,zeros(size(out.T,2),1),'cov',out.L))';\n out.cutoff.sd=sqrt(chi2inv(cutoff,out.k));\n else\n out.sd=out.AO;\n out.cutoff.sd=out.cutoff.AO;\n end\nelse\n out.sd=zeros(n,1);\n out.cutoff.sd=0;\nend\n% Orthogonal distances to robust PCA subspace\nXRc=data-repmat(out.M,n,1);\nXtilde=out.T*out.P';\nRdiff=XRc-Xtilde;\nfor i=1:n\n out.od(i,1)=norm(Rdiff(i,:));\nend\n% Robust cutoff-value for the orthogonal distance\nif k~=r\n if skew==0\n [m,s]=unimcd(out.od.^(2/3),out.h);\n out.cutoff.od = sqrt(norminv(cutoff,m,s).^3);\n else\n mcod=mc(out.od);\n if mcod>0\n out.cutoff.od = prctile(out.od,75)+1.5*exp(3*mcod)*iqr(out.od);\n else\n out.cutoff.od = prctile(out.od,75)+1.5*iqr(out.od);\n end\n ttup = sort(-out.od(out.od0)-1; % Pilot sequence generation\n %Data = ((2*(randn(1,Nd)>0)-1) + j*(2*(randn(1,Nd)>0)-1))/sq2; % QPSK modulation\n msgint=randint(1,Nfft-Np,M); % bit generation\n Data = modulate(mod_object,msgint)*A;\n %Data = modulate(mod_object, msgint); \n %Data = modnorm(Data,'avpow',1)*Data; % normalization\n ip = 0; \n pilot_loc = [];\n for k=1:Nfft\n if mod(k,Nps)==1\n X(k) = Xp(floor(k/Nps)+1); \n pilot_loc = [pilot_loc k]; \n ip = ip+1;\n else\n X(k) = Data(k-ip);\n end\n end\n x = ifft(X,Nfft); % IFFT\n xt = [x(Nfft-Ng+1:Nfft) x]; % Add CP\n h = [(randn+j*randn) (randn+j*randn)/2]; % generates a (2-tap) channel\n H = fft(h,Nfft); \n channel_length = length(h); % True channel and its time-domain length\n H_power_dB = 10*log10(abs(H.*conj(H))); % True channel power in dB\n y_channel = conv(xt, h); % Channel path (convolution)\n sig_pow = mean(y_channel.*conj(y_channel));\n %y_aw(1,1:Nofdm) = y(1,1:Nofdm) + ...\n % sqrt((10.^(-SNR/10))*sig_pow/2)*(randn(1,Nofdm)+j*randn(1,Nofdm)); % Add noise(AWGN)\n yt = awgn(y_channel,SNR,'measured'); \n y = yt(Ng+1:Nofdm); % Remove CP\n Y = fft(y); % FFT\n for m=1:3\n if m==1\n H_est = LS_CE(Y,Xp,pilot_loc,Nfft,Nps,'linear'); \n method='LS-linear'; % LS estimation with linear interpolation\n elseif m==2\n H_est = LS_CE(Y,Xp,pilot_loc,Nfft,Nps,'spline');\n method='LS-spline'; % LS estimation with spline interpolation\n else\n H_est = MMSE_CE(Y,Xp,pilot_loc,Nfft,Nps,h,SNR);\n method='MMSE'; % MMSE estimation\n end\n H_est_power_dB = 10*log10(abs(H_est.*conj(H_est)));\n h_est = ifft(H_est); \n h_DFT = h_est(1:channel_length); \n H_DFT = fft(h_DFT,Nfft); % DFT-based channel estimation\n H_DFT_power_dB = 10*log10(abs(H_DFT.*conj(H_DFT)));\n if nsym==1\n figure(1)\n subplot(319+2*m)\n plot(H_power_dB,'b','linewidth',1);\n grid on; \n hold on;\n plot(H_est_power_dB,'r:+','Markersize',4,'linewidth',1);\n %axis([0 32 -6 10])\n title(method);\n xlabel('Subcarrier Index'); \n ylabel('Power[dB]');\n legend('True Channel',method,4); \n set(gca,'fontsize',9)\n subplot(320+2*m)\n plot(H_power_dB,'b','linewidth',1); \n grid on; \n hold on;\n plot(H_DFT_power_dB,'r:+','Markersize',4,'linewidth',1); \n %axis([0 32 -6 10])\n title([method ' with DFT']);\n xlabel('Subcarrier Index');\n ylabel('Power[dB]');\n legend('True Channel',[method ' with DFT'],4); \n set(gca,'fontsize',9)\n end\n MSE(m) = MSE(m) + (H-H_est)*(H-H_est)';\n MSE(m+3) = MSE(m+3) + (H-H_DFT)*(H-H_DFT)';\n end\n Y_eq = Y./H_est;\n if nsym>=Nsym-10\n figure(2)\n subplot(221)\n plot(Y,'.','Markersize',5)\n axis([-1.5 1.5 -1.5 1.5])\n axis('equal')\n set(gca,'fontsize',9)\n hold on,\n subplot(222)\n plot(Y_eq,'.','Markersize',5)\n axis([-1.5 1.5 -1.5 1.5])\n axis('equal')\n set(gca,'fontsize',9)\n hold on, \n end\n ip = 0;\n for k=1:Nfft\n if mod(k,Nps)==1\n ip=ip+1; \n else\n Data_extracted(k-ip)=Y_eq(k); \n end\n end\n msg_detected = demodulate(demod_object,Data_extracted/A);\n nose = nose + sum(msg_detected~=msgint);\n end \n MSEs(i,:) = MSE/(Nfft*Nsym);\nend \nNumber_of_symbol_errors=nose\nfigure(3)%, clf\nsemilogy(SNRs',MSEs(:,1),'-x', SNRs',MSEs(:,3),'-o')\nlegend('LS-linear','MMSE')\nfprintf('MSE of LS-linear/LS-spline/MMSE Channel Estimation = %6.4e/%6.4e/%6.4e\\n',MSEs(end,1:3));\nfprintf('MSE of LS-linear/LS-spline/MMSE Channel Estimation with DFT = %6.4e/%6.4e/%6.4e\\n',MSEs(end,4:6));", "meta": {"author": "LyricYang", "repo": "MIMO_OFDM", "sha": "df25e1837bc4019f2bbcd946bc49b0942827a847", "save_path": "github-repos/MATLAB/LyricYang-MIMO_OFDM", "path": "github-repos/MATLAB/LyricYang-MIMO_OFDM/MIMO_OFDM-df25e1837bc4019f2bbcd946bc49b0942827a847/\u7b2c6\u7ae0 \u4fe1\u9053\u4f30\u8ba1/channel_estimation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6884177917476461}} {"text": "% test for denoising using Non Local Means vs Wavelets\n%\n% Copyright (c) 2007 Gabriel Peyre\n\npath(path, 'toolbox/');\n\nif not(exist('name'))\n name = 'peppers';\n name = 'polygons_blurred';\n name = 'boat';\n name = 'mandrill';\n name = 'lenacoul';\n name = 'lena';\n name = 'images/corral';\n name = 'barb';\nend\n\n%% load image\nn = 64*2;\nn0 = [];\nM = load_image(name, n0);\nc = size(M)/2;\nif strcmp(name, 'lena') && n==128\n c = [120 200]; % lena hat\nend\nif strcmp(name, 'mandrill') && n==128\n c = [350 350];\nend\neta = 0.12;\nM0 = rescale( crop(M,n,c), eta, 1-eta );\ns = size(M0,3); % number of colors\n\n%% add some Gaussian noise\nsigma = 0.06 * max( M0(:) );\nrandn('state',1234); % to have reproductible results\nM = M0 + randn(n,n,s)*sigma;\n% approx wavelet threshold\nT = 3*sigma;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% TI Wavelets\nclear options;\noptions.wavelet_type = 'biorthogonal';\noptions.wavelet_vm = 3;\nJmin = 4;\noptions.decomp_type = 'quad';\nMW = perform_atrou_transform(M,Jmin,options);\ndisp('--> Computing best threshold (wavelets).');\nTwav = compute_best_threshold('wavelet',M,M0,sigma, options);\nMWT = perform_thresholding(MW, T);\nMW1 = perform_atrou_transform(MWT,Jmin,options);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Portilla and Simoncelli method\noptions.sigma = sigma;\noptions.repres2 = 'daub3';\noptions.parent = 1;\ndisp('--> BLS-GSM denoising.');\nML1 = perform_blsgsm_denoising(M, options);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Non-local means\n% options of NL means (15,30)\noptions.max_dist = 5; % search width, the smaller the faster the algorithm will be\noptions.ndims = 40; % number of dimension used for distance computation (PCA dim.reduc. to speed up)\noptions.do_patchwise = 0;\noptions.mask = 'linear';\noptions.mask = 'cst';\ndisp('--> NLMeans denoising.');\noptions.Tlist = linspace(0.02,0.07,12);\noptions.klist = [4 5];\n[tmp,options] = compute_best_threshold('nlmeans',M,M0,sigma, options);\n[MN1,Wx,Wy] = perform_nl_means(M, options);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Non-local patchwise\ndo_patchwise = 1;\nif do_patchwise\noptions.do_patchwise = 1;\ndisp('--> NLMeans denoising.');\n[tmp,options] = compute_best_threshold('nlmeans',M,M0,sigma, options);\n[MNpwise1,Wx,Wy] = perform_nl_means(M, options);\nend\n\n\n\npnoisy = psnr(M,M0);\npwav = psnr(M0,MW1);\npbls= psnr(M0,ML1);\npnlm= psnr(M0,MN1);\nif do_patchwise\n pnlpwise = psnr(M0,MNpwise1);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Display\nimgs = {M0 M MW1 ML1 MN1};\nopts = {'Original' sprintf('Noisy,psnr=%.2f', pnoisy) sprintf('Wav,psnr=%.2f', pwav) ...\n sprintf('BLS,psnr=%.2f(+%.2f)', pbls, pbls-pwav) ...\n sprintf('NLMeans,psnr=%.2f(+%.2f)', pnlm, pnlm-pwav) };\nif do_patchwise\n imgs{end+1} = MNpwise1;\n opts{end+1} = sprintf('NLMedian,psnr=%.2f(+%.2f)', pnlpwise, pnlpwise-pwav);\nend\ndisplay_image_layout(imgs, opts );\n\n% save\nrepimg = ['results/denoising/'];\nif not(exist(repimg))\n mkdir(repimg);\nend\nsaveas(gcf, [repimg name '-denoising.png'], 'png');\n\nrepimg = ['results/denoising/' name '/'];\nif not(exist(repimg))\n mkdir(repimg);\nend\n\n\n%% write results\nfid = fopen([repimg name '-results.txt'], 'a');\nfprintf(fid, '--> %s: n=%d, max_dist=%d, ndims=%d, sigma=%.2f, k=%d, T=%.2f, mask=%s\\n', name, n, ...\n options.max_dist, options.ndims, sigma, options.k, options.T, options.mask);\nfprintf(fid, 'Noisy %.4f\\n', pnoisy);\nfprintf(fid, 'Wavelets %.4f\\n', pwav);\nfprintf(fid, 'BLS-GSM %.4f (+%.4f)\\n', pbls, pbls-pwav);\nfprintf(fid, 'NL-Means %.4f (+%.4f)\\n', pnlm, pnlm-pwav);\nif do_patchwise\n fprintf(fid, 'NL-Median %.4f (+%.4f)\\n', pnlpwise, pnlpwise-pwav);\nend\nfclose(fid);\n\n% scaling for method noise\ns = std(M0(:)-MW1(:))*6;\n\n%% save images\nwarning off;\nimwrite(clamp(M0), [repimg name '-original.png'], 'png');\nimwrite(clamp(M), [repimg name '-noisy.png'], 'png');\nimwrite(clamp(MW1), [repimg name '-wavelets.png'], 'png');\nimwrite(clamp(ML1), [repimg name '-blsgsm.png'], 'png');\nimwrite(clamp(MN1), [repimg name '-nlmeans.png'], 'png');\nimwrite(clamp( 0.5+ (M-MW1)/s ) , [repimg name '-wavelets-methnoise.png'], 'png');\nimwrite(clamp( 0.5+ (M-ML1)/s ) , [repimg name '-blsgsm-methnoise.png'], 'png');\nimwrite(clamp( 0.5+ (M-MN1)/s ) , [repimg name '-nlmeans-methnoise.png'], 'png');\nif do_patchwise\nimwrite(clamp(MNpwise1), [repimg name '-nlpatchwise.png'], 'png'); \nimwrite(clamp( 0.5+ (M-MNpwise1)/s ) , [repimg name '-nlpatchwise-methnoise.png'], 'png');\nend\nwarning off;", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_nlmeans/tests/test_denoising.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460027, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6884177916874471}} {"text": "function [v,x,t,m,ze]=v_quadpeak(z)\n%V_PEAK2DQUAD find quadratically-interpolated peak in a N-D array\n%\n% Inputs: Z(m,n,...) is the input array (ignoring trailing singleton dimensions)\n% Note: a row vector will have 2 dimensions\n%\n% Outputs: V is the peak value\n% X(:,1) is the position of the peak (in fractional subscript values)\n% T is -1, 0, +1 for maximum, saddle point or minimum\n% M defines the fitted quadratic: z = [x y ... 1]*M*[x y ... 1]'\n% ZE the estimated version of Z\n\n%\t Copyright (C) Mike Brookes 2008\n% Version: $Id: v_quadpeak.m 10865 2018-09-21 17:22:45Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\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 can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\npersistent wz a\n% first calculate the fixed matrix, a (can be stored if sz is constant)\nsz=size(z); % size of input array\npsz=prod(sz); % number of elements in input array\ndz=numel(sz); % number of input dimensions\nmz=find(sz>1); % non-singleton dimension indices\nnm=numel(mz); % number of non-singleton dimensions\nvz=sz(mz); % size of squeezed input array\ndx=max(mz); % number of output dimensions\nif ~nm % if the input array is a scalar\n error('Cannot find peak of a scalar');\nend\nnc=(nm+1)*(nm+2)/2; % number of columns in A matrix\nif min(vz)<3\n error('Need at least 3 points in each non-singleton dimension');\nend\nif isempty(wz) || numel(wz)~=numel(vz) || ~all(wz==vz)\n wz=vz;\n a=ones(psz,nc);\n ix=(0:psz-1)';\n for i=1:nm\n jx=floor(ix/sz(mz(i)));\n a(:,i+nc-nm-1)=1+ix-jx*sz(mz(i));\n ix=jx;\n a(:,(i^2-i+2)/2:i*(i+1)/2)=a(:,nc-nm:i+nc-nm-1).*repmat(a(:,i+nc-nm-1),1,i);\n end\n a=(a'*a)\\a'; % converts to polynomial coeficients {x^2 xy y^2 x y 1]\nend\n\n% now find the peak\n\nc=a*z(:); % polynomial coefficients for this data\nw=zeros(nm+1,nm+1);\ni=1:(nm+1)*(nm+2)/2;\nj=floor((sqrt(8*i-7)-1)/2);\nw(i+j.*(2*nm+1-j)/2)=c;\nw=(w+w.')/2; % make it symmetrical\nmr=w(1:nm,1:nm);\nwe=w(1:nm,nm+1);\ny=-(mr\\we);\nv=y'*we+w(nm+1,nm+1); % value at peak\n\n% insert singleton dimensions into outputs\n\nx=zeros(dx,1);\nx(mz)=y;\nm=zeros(dx+1,dx+1);\nmz(nm+1)=dx+1;\nm(mz,mz)=w;\nif nargout>2\n ev=eig(mr);\n t=all(ev>0)-all(ev<0);\nend\nif nargout>4\n ze=zeros(sz);\n scp=cumprod([1 sz(1:end-1)]);\n ivec=fix(repmat((0:psz-1)',1,dz)./repmat(scp,psz,1));\n xe=[1+ivec-repmat(sz,psz,1).*fix(ivec./repmat(sz,psz,1)) ones(psz,1)];\n ze=reshape(sum((xe*m).*xe,2),sz);\nend\n\n\nif ~nargout && nm<=2\n % plot the data\n desc={'Maximum','Saddle Point','Minimum'};\n if nargout<=2\n ev=eig(mr);\n t=all(ev>0)-all(ev<0);\n end\n if nm==1\n xax=linspace(1,psz,100);\n plot(xax,c(1)*xax.^2+c(2)*xax+c(3),'-r',1:psz,z(:),'ob',x,v,'^k');\n set(gca,'xlim',[0.9 psz+0.1]);\n ylabel('z');\n xlabel(sprintf('x%d',mz(1)));\n title(sprintf('\\\\Delta = %s: z(%.2g) = %.2g',desc{t+2},y(1),v));\n else\n ngr=17;\n xax=repmat(linspace(1,vz(1),ngr)',1,ngr);\n yax=repmat(linspace(1,vz(2),ngr),ngr,1);\n zq=(c(1)*xax+c(2)*yax+c(4)).*xax+(c(3)*yax+c(5)).*yax+c(6);\n hold off\n mesh(xax,yax,zq,'EdgeColor','r');\n hold on\n plot3(repmat((1:vz(1))',1,vz(2)),repmat(1:vz(2),vz(1),1),reshape(z,vz),'ob',y(1),y(2),v,'^k');\n hold off\n set(gca,'xlim',[0.9 vz(1)+0.1],'ylim',[0.9 vz(2)+0.1]);\n xlabel(sprintf('x%d',mz(1)));\n ylabel(sprintf('x%d',mz(2)));\n zlabel('z');\n title(sprintf('\\\\Delta = %s: z(%.2g,%.2g) = %.2g',desc{t+2},y(1),y(2),v));\n end\nend\n\n\n", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_quadpeak.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6884012356052381}} {"text": "function bc = specific_bc(xbd,ybd)\n%solution4_bc Reference problem 1.4 boundary condition \n% bc = specific_bc(xbd,ybd);\n% input\n% xbd x boundary coordinate vector\n% ybd y boundary coordinate vector \n% IFISS function: DJS; 28 February 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \nbc=(xbd.^2+ybd.^2).^(1/3) .*sin((pi+2*atan2(ybd,xbd))/3);\nreturn\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/toms866/diffusion/test_problems/solution4_bc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181876, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6884012125130021}} {"text": " function [A, phi, f] = amplitude_spectrum(td)\n %amplitude_spectrum Simple method to compute amplitude\n % spectrum for a trace. Uses the MATLAB fft function.\n % [A, phi, f] = amplitude_spectrum(td)\n %\n % Inputs:\n % td - a single TraceData\n %\n % Outputs:\n % A - the amplitude coefficients\n % phi - the phase coefficients\n % f - the frequency values corresponding to elements of A and phi\n %\n % Example:\n % [A phi, f] = amplitude_spectrum(td)\n % plot(f,A);\n % xlabel('Frequency (Hz)')\n % ylabel('Amplitude');\n %\n % See also fft\n % Glenn Thompson, November 21, 2014\n \n %TODO: Rename this to amplitudespectrum or move it elsewhere\n \n N = length(td.data);\n NFFT = 2 ^ nextpow2(N); % Next power of 2 from length of y\n Y = fft(td.data, NFFT); % X will have same length as signal, and will be complex with a magnitude and phase\n A = 2 * abs(Y(1:NFFT/2+1)) / N;\n phi = angle(Y);\n f = td.samplerate / 2 * linspace(0,1,NFFT/2+1);\n end", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/dev/@TraceData/amplitude_spectrum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181876, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.6884012125130021}} {"text": "function R = p2p_rcu(a, n_vals, eps)\n% Compute the achievable sum rate (at the symmetrical rate point) from the point-to-point RCU bound \n% for the joint source distribution: [a 1/3*(1-a); 1/3*(1-a) 1/3*(1-a)].\n\n% Input:\n% a: parameter to define the joint source distribution, should be in range [0.25, 1)\n% n_vals: a vector containing the blocklengths\n% eps: target error probability\n% Output:\n% R: the achievable rates for the blocklengths specified in n_vals.\n\n p = [a 1/3*(1-a); 1/3*(1-a) 1/3*(1-a)];\n H = sum(sum(p.*log(1./p))); % Source joint entropy\n\n % Compute log binomial coefficients\n log_b = binomial_coeff(max(n_vals));\n\n R = zeros(length(n_vals),1);\n\n for i = 1:length(n_vals)\n n = n_vals(i);\n m = 0:n; % Number of occurrence of the largest joint probability mass\n % log_Pr stores all the log probabilities in descending order\n log_Pr = m*log(a)+(n-m)*log(1/3*(1-a)); \n\n % [x, y]: initial range for the bisection algorithm\n x = H;\n y = H + 2;\n %%%%%%%%%% Use this part to check if the range is valid for bisection algorithm %%%%%%%%%%\n c = x;\n log_indicator = zeros(1,n+1); \n for j = 0:n \n log_indicator(j+1) = min(0, my_logsumexp(log_b{n+1}(j+1:n+1)+(n-(j:n))*log(3))-n*c);\n end\n err = exp(my_logsumexp(log_Pr + log_b{n+1} + (n-m)*log(3) + log_indicator));\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n % Start of bisection iteration\n iter = 0;\n while abs(x - y) > 0.00001 && iter <= 25\n c = (x+y)/2;\n %%%%%%%%%%%%%%%% body of iteration %%%%%%%%%%%%%%%%\n log_indicator = zeros(1,n+1); \n for j = 0:n \n log_indicator(j+1) = min(0, my_logsumexp(log_b{n+1}(j+1:n+1)+(n-(j:n))*log(3))-n*c);\n end\n err = exp(my_logsumexp(log_Pr + log_b{n+1} + (n-m)*log(3) + log_indicator));\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if err - eps < 0\n y = c;\n else\n x = c;\n end\n iter = iter + 1;\n end\n R(i) = c;\n end\nend\n\n", "meta": {"author": "yp-mit", "repo": "spectre", "sha": "57af76799e4eb43aa707cc13c4c5220d281e0b78", "save_path": "github-repos/MATLAB/yp-mit-spectre", "path": "github-repos/MATLAB/yp-mit-spectre/spectre-57af76799e4eb43aa707cc13c4c5220d281e0b78/lossless-sc/p2p_rcu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6883992880745908}} {"text": "function [F, p, resid, df_model, df_error] = F_test_full_vs_red(y, X, Xred, px, pxred)\n% :Usage:\n% ::\n%\n% [F, p, resid, df_model, df_error] = F_test_full_vs_red(y, X, Xred, px, pxred)\n%\n% :Examples:\n% ::\n%\n% X = randn(100, 3); Xred = X(:,1); y = X(:,2) + randn(100, 1);\n% px = pinv(X); pxred = pinv(Xred);\n% [F, p, resid] = F_test_full_vs_red(y, X, Xred, px, pxred);\n%\n%\n% % Test full-model F-value against regress.m\n% Xred = X(:,end); % intercept only\n% px = pinv(X);\n% pxred = pinv(Xred);\n% [F, p, resid, dfm, dfe] = F_test_full_vs_red(y, X, Xred, px, pxred); % full model F-test\n% [b, bint, r, rint, stats] = regress(y, X);\n%\n% ..\n% Tested OK on 11/27/07, by tor\n% ..\n\n T = length(y); % Length of time course\n\n k = size(px, 1); % predictors: full model\n kred = size(pxred, 1); % predictors: reduced model\n\n % Degrees of freedom: model: Full - reduced\n df_model = k - kred; % degrees of freedom for model (param - 1)\n df_error = T - k; % error DF, full model\n\n % Step 1: Find the OLS solution for the FULL model\n % ---------------------------------------------------\n beta = px * y; % Beta values\n resid = y - X * beta; % Residuals\n\n % Sums of squares\n %SST = y' * y;\n SSE = resid' * resid;\n %SSfull = SST - SSE;\n var_est = SSE / df_error; % Estimate of Sigma^2\n\n % Step 2: Find the OLS solution for the REDUCED model\n % F-test for full vs. reduced\n % ---------------------------------------------------\n betared = pxred * y; % Beta values\n residred = y - Xred * betared;\n SSEred = residred' * residred;\n %SSred = betared' * Xred' * y; % Full model sum of squares\n\n % F stat\n % (SSred - SSfull) ./ (var * df_model)\n F = (SSEred - SSE) / (var_est * df_model); % F-statistic - compare with F-distribution with (param-1, df) degrees of freedom\n\n p = 1 - fcdf(F, df_model, df_error);\nend\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/F_test_full_vs_red.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6883385658415513}} {"text": "function d=jensen_shannon_divergence(XI,XJ)\n % Implementation of the Jensen-Shannon Divergence to use with pdist\n % (cf. \"The Earth Movers' Distance as a Metric for Image Retrieval\",\n % Y. Rubner, C. Tomasi, L.J. Guibas, 2000)\n %\n % @author: B. Schauerte\n % @date: 2009\n % @url: http://cvhci.anthropomatik.kit.edu/~bschauer/\n \n % Copyright 2009 B. Schauerte. All rights reserved.\n % \n % Redistribution and use in source and binary forms, with or without \n % modification, are permitted provided that the following conditions are \n % met:\n % \n % 1. Redistributions of source code must retain the above copyright \n % notice, this list of conditions and the following disclaimer.\n % \n % 2. 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 \n % distribution.\n % \n % THIS SOFTWARE IS PROVIDED BY B. SCHAUERTE ''AS IS'' AND ANY EXPRESS OR \n % IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \n % WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \n % DISCLAIMED. IN NO EVENT SHALL B. SCHAUERTE OR CONTRIBUTORS BE LIABLE \n % FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n % CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n % SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR \n % BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, \n % WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n % OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n % ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n % \n % The views and conclusions contained in the software and documentation\n % are those of the authors and should not be interpreted as representing \n % official policies, either expressed or implied, of B. Schauerte.\n \n d=jeffrey_divergence(XI,XJ);\n d=d / 2;\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/base/utilities/histogram_distance/jensen_shannon_divergence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.688338565599924}} {"text": "function popDist = totaldistance(pop,dis)\n% TOTALDISTANCE\n% popDist = TOTALDISTANCE(pop, dis) calculate total distance of pop(routes)\n% with the distance matrix dis. Evaluate Each Population Member (Calculate \n% Total Distance)\n\n[popSize, numberofcities] = size(pop);\nfor i = 1:popSize\n d = dis(pop(i,end),pop(i,1)); % Closed Path\n for k = 2:numberofcities\n d = d + dis(pop(i,k-1),pop(i,k));\n end\n popDist(i) = d;\nend", "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/HeuristicAlgorithm\uff08\u8865\u5206\u542f\u53d1\u5f0f\u7b97\u6cd5\uff0c\u5305\u62ec\u795e\u7ecf\u7f51\u7edc\u3001\u6a21\u62df\u9000\u706b\u3001\u9057\u4f20\u7b97\u6cd5\uff09/\u9057\u4f20\u7b97\u6cd5/TSP(GA)/totaldistance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6883385609195013}} {"text": "% This is material illustrating the methods from the book\n% Financial Modelling - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors: Joerg Kienitz\n% Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\n\n% Discretization of a 2d Variance Gamma process\n\n\n% Monte Carlo parameters\nNBatches = 1; % Number of batches \nNSim = 10000;%100000; % Number of paths per batch\nNt = 250; % Number of time steps until T!\n \n% Asset parameters\nS0 = [1.0 1.0]; % spot price of stock index\nr = 0.042; % risk free rate\nd = [0.00 0.00]; % dividend yield\nT = 0.5; % Time horizon (in years)\nrho = 0.5;\nlnS1 = zeros(NSim, Nt+1); % log spot prices asset 1\nlnS2 = zeros(NSim, Nt+1); % log spot prices asset 2 \n\n% Model parameters (theta, sigma, nu representation)\ntheta = [-0.6094 -0.8301]; % parameter of VG\nsigma = [0.0325 0.9406]; % parameter of VG\nnu = 0.2570; % parameter of VG\nomegaT = -1/nu * [log(1-theta(1)*nu - nu*sigma(1)^2/2) log(1-theta(2)*nu - nu*sigma(2)^2/2)];\ndrift = [r-d(1) r-d(2)]; % parameter of VG\n\n%Corr = [1 .6495; .6495 1];\nCorr = [1 rho; rho 1];\n%Corr = [1 .9; .9 1];\n%Corr = [1 -.9; -.9 1];\nR = chol(Corr);\n\n% Option parameters\nvalue = ones(NBatches,1); % Stores the option value per batch\n\n% precomputed constants\ndeltaT = T / Nt; % delta for time discretization\nlnS1(:,1) = log(S0(1)); % Set the starting spot price\nlnS2(:,1) = log(S0(2));\n\n%oNt = ones(Nt,1); % used during simulation\noNs = ones(NSim,1); \n% Start Monte Carlo here\ntic;\nfor number = 1 : NBatches\n % Time discretization\n \n for m=1:Nt\n %G = nu*gamrnd(deltaT/nu, oNt); % Gamma Subordinator\n G = nu * gamrnd(deltaT/nu,oNs);\n W = randn(NSim,2);\n W = W*R;\n lnS1(:,m+1) = lnS1(:,m) + (drift(1)-omegaT(1)) * deltaT ...\n + theta(1) * G + sqrt(G) * sigma(1) .* W(:,1);\n lnS2(:,m+1) = lnS2(:,m) + (drift(2)-omegaT(2))* deltaT ...\n + theta(2) * G + sqrt(G) * sigma(2) .* W(:,2);\n end\n \n S1 = exp(lnS1); % Simulated prices for asset 1\n S2 = exp(lnS2); % Simulated prices for asset 2\n \n \n if(NSim ==1)\n figure1 = figure;\n axes1 = axes('Parent',figure1);\n hold on;\n plot1 = plot(S1,'Parent',axes1,'MarkerSize',4,'Marker','o','Color',[0 0 1],'DisplayName','Asset 1');\n plot1 = plot(S2, 'Marker','.','Color',[1 0 0],'DisplayName','Asset 2');\n %plot(S1,'b');\n %plot(S2,'r');\n\n % Create xlabel\n xlabel('step');\n\n % Create ylabel\n ylabel('S(t)');\n\n % Create title\n title({'2d Variance Gamma Process','- zero correlation -'},...\n 'FontWeight','bold','FontSize',12,'FontName','Arial');\n\n % Create legend\n legend1 = legend(axes1,'show');\n set(legend1,'Position',[0.8206 0.831 0.08047 0.06204]);\n\n end\n \n % Option Pricing\n value(number) = exp(-r*T)* WorstOfCall(S1,S2);\n %value(number) = exp(-r*T)* BestOfCall(S1,S2);\n %value(number) = exp(-r*T)* Spread(S1,S2);\n\nend\n\nmean(value) % Output of Option price\n%Elapsed_Time = toc % Time spend on MC simulation\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/37618-monte-carlo-simulation-and-derivatives-pricing/StandardMonteCarlo/MCvg2d_oxford_script.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6883385589417311}} {"text": "function kernel = MimNormalisedGaussianKernel(voxel_size_mm, filter_size_mm, minimum_grid_size_mm)\n % MimNormalisedGaussianKernel.\n %\n %\n % The input and output images are of class PTKImage.\n %\n %\n % Licence\n % -------\n % Part of the TD MIM Toolkit. https://github.com/tomdoel\n % Author: Tom Doel, Copyright Tom Doel 2014. www.tomdoel.com\n % Distributed under the MIT licence. Please see website for details.\n %\n \n if nargin < 3\n minimum_grid_size_mm = [];\n end\n\n if numel(minimum_grid_size_mm) == 1\n minimum_grid_size_mm = repmat(minimum_grid_size_mm, [1, 3]);\n end\n \n sigma_mm = filter_size_mm;\n \n epsilon = 1e-3;\n sigma_voxels = sigma_mm./voxel_size_mm;\n grid_size = 2*(ceil((sigma_voxels).*sqrt(-2*log(sqrt(2*pi).*(sigma_voxels)*epsilon)))) + 1;\n \n if ~isempty(minimum_grid_size_mm)\n minimum_grid_size = 2*(ceil((minimum_grid_size_mm./voxel_size_mm)/2));\n grid_size = max(grid_size, minimum_grid_size);\n end\n \n grid_size_i = grid_size(1);\n grid_size_j = grid_size(2);\n grid_size_k = grid_size(3);\n \n center_i = grid_size_i/2 + 0.5;\n center_j = grid_size_j/2 + 0.5;\n center_k = grid_size_k/2 + 0.5;\n \n n_i = 1 : grid_size_i;\n n_j = 1 : grid_size_j;\n n_k = 1 : grid_size_k;\n \n sigmai = sigma_voxels(1);\n sigmaj = sigma_voxels(2);\n sigmak = sigma_voxels(3);\n \n keri = zeros(1, 1, grid_size_i, 'single');\n kerj = zeros(1, 1, grid_size_j, 'single');\n kerk = zeros(1, 1, grid_size_k, 'single');\n \n keri(1,1,:) = (1/((2*pi*sigmai.^2).^(1/2))) * exp(-((n_i - center_i).^2)/(2*sigmai.^2));\n kerj(1,1,:) = (1/((2*pi*sigmaj.^2).^(1/2))) * exp(-((n_j - center_j).^2)/(2*sigmaj.^2));\n kerk(1,1,:) = (1/((2*pi*sigmak.^2).^(1/2))) * exp(-((n_k - center_k).^2)/(2*sigmak.^2));\n \n % Normalise\n keri = keri./sum(keri);\n kerj = kerj./sum(kerj);\n kerk = kerk./sum(kerk);\n \n ker1 = repmat(shiftdim(keri, 2), [1, grid_size_j, grid_size_k]);\n ker2 = repmat(shiftdim(kerj, 1), [grid_size_i, 1, grid_size_k]);\n ker3 = repmat(kerk, [grid_size_i, grid_size_j, 1]);\n kernel = ker1.*ker2.*ker3;\n \n kernel = kernel/max(kernel(:));\nend", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/External/mim/Library/Filters/MimNormalisedGaussianKernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6883385545029359}} {"text": "function lambda = chow_eigenvalues ( alpha, beta, n )\n\n%*****************************************************************************80\n%\n%% CHOW_EIGENVALUES returns the eigenvalues of the CHOW matrix.\n%\n% Example:\n%\n% ALPHA = 2, BETA = 3, N = 5\n%\n% 9.49395943\n% 6.10991621\n% 3.0\n% 3.0\n% 3.0\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 September 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real ALPHA, the ALPHA value. A typical value is 1.0.\n%\n% Input, real BETA, the BETA value. A typical value is 0.0.\n%\n% Input, integer N, the order of A.\n%\n% Output, real LAMBDA(N,1), the eigenvalues of A.\n%\n lambda = zeros ( n, 1 );\n\n k = n - round ( ( n + 1 ) / 2 );\n\n for i = 1 : k\n angle = i * pi / ( n + 2 );\n lambda(i,1) = beta + 4.0 * alpha * ( cos ( angle ) )^2;\n end\n\n lambda(k+1:n,1) = beta;\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/chow_eigenvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.6883259014155562}} {"text": "function ciu = consensus_und(d,tau,reps)\n% CONSENSUS_UND Consensus clustering\n%\n% CIU = CONSENSUS(D,TAU,REPS) seeks a consensus partition of the \n% agreement matrix D. The algorithm used here is almost identical to the\n% one introduced in Lancichinetti & Fortunato (2012): The agreement\n% matrix D is thresholded at a level TAU to remove an weak elements. The\n% resulting matrix is then partitions REPS number of times using the\n% Louvain algorithm (in principle, any clustering algorithm that can\n% handle weighted matrixes is a suitable alternative to the Louvain\n% algorithm and can be substituted in its place). This clustering\n% produces a set of partitions from which a new agreement is built. If\n% the partitions have not converged to a single representative partition,\n% the above process repeats itself, starting with the newly built\n% agreement matrix.\n%\n% NOTE: In this implementation, the elements of the agreement matrix must\n% be converted into probabilities.\n%\n% NOTE: This implementation is slightly different from the original\n% algorithm proposed by Lanchichinetti & Fortunato. In its original\n% version, if the thresholding produces singleton communities, those\n% nodes are reconnected to the network. Here, we leave any singleton\n% communities disconnected.\n%\n% Inputs: D, agreement matrix with entries between 0 and 1\n% denoting the probability of finding node i in the\n% same cluster as node j\n% TAU, threshold which controls the resolution of the\n% reclustering\n% REPS, number of times that the clustering algorithm is\n% reapplied\n%\n% Outputs: CIU, consensus partition\n%\n% References: Lancichinetti & Fortunato (2012). Consensus clustering in\n% complex networks. Scientific Reports 2, Article number: 336.\n%\n% Richard Betzel, Indiana University, 2012\n%\n% modified on 3/2014 to include \"unique_partitions\"\n\nn = length(d); flg = 1;\nwhile flg == 1\n \n flg = 0;\n dt = d.*(d >= tau).*~eye(n);\n if nnz(dt) == 0\n ciu = (1:n)';\n else\n ci = zeros(n,reps);\n for iter = 1:reps\n ci(:,iter) = community_louvain(dt);\n end\n ci = relabel_partitions(ci);\n ciu = unique_partitions(ci);\n nu = size(ciu,2);\n if nu > 1\n flg = 1;\n d = agreement(ci)./reps;\n end\n end\n \nend\n\nfunction cinew = relabel_partitions(ci)\n[n,m] = size(ci);\ncinew = zeros(n,m);\nfor i = 1:m\n c = ci(:,i);\n d = zeros(size(c));\n count = 0;\n while sum(d ~= 0) < n\n count = count + 1;\n ind = find(c,1,'first');\n tgt = c(ind);\n rep = c == tgt;\n d(rep) = count;\n c(rep) = 0;\n end\n cinew(:,i) = d;\nend\n\nfunction ciu = unique_partitions(ci)\nci = relabel_partitions(ci);\nciu = [];\ncount = 0;\nc = 1:size(ci,2);\nwhile ~isempty(ci)\n count = count + 1;\n tgt = ci(:,1);\n ciu = [ciu,tgt]; %#ok\n dff = sum(abs(bsxfun(@minus,ci,tgt))) == 0;\n ci(:,dff) = [];\n c(dff) = [];\nend", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/2019_03_03_BCT/consensus_und.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6883258952827364}} {"text": "% This is material illustrating the methods from the book\n% Financial Modelling - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors: Joerg Kienitz\n% Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\n% Script chap::2::script\n% Density NIG Model with Gamma Ornstein Uhlenbeck stochastic clock\n%\n% \n%\nT = 5; % maturity\nf0 = 100; % spot value\nr=0;\nd=0;\nad = 600; % spot value\nN = 1024; % number of grid points \nx = ( (0:N-1) - N/2 ) / ad; % range\n\n%f = 90:.01:110; % range\n\nalpha = 2;\nbeta = 0; % CEV exponent base scenario\ndelta = .3;\nlambda = 3;\na = 1;\nb = 1;\n\nlegend = 'Base';\ntitle_plot = 'NIG-OU Density';\n\nfunc = @(x) cf_nigou(x,T,0,r,d,alpha, beta, delta, lambda,a,b);\ny = fftdensity(func,ad,N);\n%% Changing a\na_low = .5;\na_high = 2;\n\nfunc_low = @(x) cf_nigou(x,T,0,r,d,alpha, beta, delta, lambda, a_low,b);\ny_low = fftdensity(func_low,ad,N);\nfunc_high = @(x) cf_nigou(x,T,0,r,d,alpha, beta, delta, lambda, a_high,b);\ny_high = fftdensity(func_high,ad,N);\nlegend_low = 'Changing a low';\nlegend_high = 'Changing a high';\n\ncreatefigure_density(x,y,y_low,y_high,title_plot,legend,legend_low,legend_high);\n\n%% Changing b\nb_low = .5;\nb_high = 2;\n\nfunc_low = @(x) cf_nigou(x,T,0,r,d,alpha, beta, delta, lambda, a,b_low);\ny_low = fftdensity(func_low,ad,N);\nfunc_high = @(x) cf_nigou(x,T,0,r,d,alpha, beta, delta, lambda, a,b_high);\ny_high = fftdensity(func_high,ad,N);\nlegend_low = 'Changing b low';\nlegend_high = 'Changing b high';\n\ncreatefigure_density(x,y,y_low,y_high,title_plot,legend,legend_low,legend_high);\n\n%% Changing lambda\nlambda_low = 1;\nlambda_high = 20;\n\nfunc_low = @(x) cf_nigou(x,T,0,r,d,alpha, beta, delta, lambda_low, a,b);\ny_low = fftdensity(func_low,ad,N);\nfunc_high = @(x) cf_nigou(x,T,0,r,d,alpha, beta, delta, lambda_high, a,b);\ny_high = fftdensity(func_high,ad,N);\nlegend_low = 'Changing \\lambda low';\nlegend_high = 'Changing \\lambda high';\n\ncreatefigure_density(x,y,y_low,y_high,title_plot,legend,legend_low,legend_high);\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/36966-risk-neutral-densities-for-financial-models/Script_Density_NIGOU.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.6883258833922824}} {"text": "function out = cov(f, g, varargin)\n%COV Covariance of a CHEBFUN.\n% COV(F) is the same as VAR(F) if F is a scalar-valued CHEBFUN.\n% COV(F) returns the covariance of the array-valued CHEBFUN F. \n% COV(F, G) returns the covariance matrix of the columns of F and G.\n%\n% See also VAR, MEAN.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Empty case:\nif ( isempty(f) )\n out = NaN;\n return\nend\n\n% Error checking:\nif ( (nargin == 2) && ~all(size(f) == size(g)) )\n error('CHEBFUN:CHEBFUN:cov:size',' CHEBFUN dimensions do not agree.');\nend\nif ( nargin == 3 )\n error('CHEBFUN:CHEBFUN:cov:nargin', ...\n 'CHEBFUN/COV does not support normalization.');\nend\n\n% Deal with row CHEBFUN objects:\nif ( f(1).isTransposed )\n if ( nargin == 1 )\n out = transpose(cov(transpose(f)));\n else\n out = transpose(cov(transpose(f), transpose(g)));\n end\n return\nend\n\n% Conditional on COV(f) and COV(f, g).\nif ( nargin == 1 ) % COV(f)\n \n if ( numColumns(f) == 1 )\n % The covariance of a scalar-valued CHEBFUN is the same as the variance:\n out = var(f);\n return\n \n else\n % Array-valued CHEBFUN or quasimatrix.\n \n Y = f - mean(f);\n out = diag(mean(Y.*conj(Y)));\n % Convert Y to a cell array of scalar-valued CHEBFUN objects.\n Y = mat2cell(Y);\n % Loop over each of the columns:\n for j = 1:numel(Y)\n for k = j+1:numel(Y)\n % Compute the scaled inner product of the jth and kth columns:\n out(j,k) = mean(Y{j}.*conj(Y{k}));\n % Use symmetry:\n out(k,j) = conj(out(j,k));\n end\n end\n \n end\n \nelse % COV(f, g)\n \n % Convert to cell arrays of scalar-valued CHEBFUN objects:\n Y = cheb2cell(f - mean(f));\n Z = cheb2cell(g - mean(g));\n % Initialise output matrix:\n out = zeros(numel(f));\n % Loop over each of the columns:\n for j = 1:numel(Y)\n for k = 1:numel(Y)\n out(j,k) = mean(Y{j}.*conj(Z{k}));\n end\n end\n\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/@chebfun/cov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6883258817231946}} {"text": "% AUTHORSHIP\n% Primary Developer: Stephen Meehan \n% Math Lead & Secondary Developer: Connor Meehan \n% Bioinformatics Lead: Wayne Moore \n% Provided by the Herzenberg Lab at Stanford University \n% License: BSD 3 clause\n%\nclassdef ProbabilityDensity2 < handle\n properties(Constant) \n DEFAULT_BAND_WIDTH=.014;\n DEFAULT_GRID_SIZE=256;\n N_MIN=5000;\n end\n \n properties(SetAccess=private)\n deltas;\n onScale;\n xyData;\n xgrid;\n ygrid;\n wmat;\n fmat;\n fmatVector;\n ye;\n xm;\n ym;\n h;\n M;\n N;\n D;\n mins;\n maxs;\n dataBinIdxs;\n end\n \n methods\n function this=ProbabilityDensity2(xyData, mins, maxs, gridSize, bandWidth)\n assert(nargin>0);\n [this.N, this.D]=size(xyData);\n assert(this.D==2); %2D only\n if nargin<5\n bandWidth=this.DEFAULT_BAND_WIDTH;\n if nargin<4\n gridSize=this.DEFAULT_GRID_SIZE;\n if nargin<3\n maxs=[];\n if nargin<2\n mins=[];\n end\n end\n end\n end\n needsScaling=~isempty(maxs) || ~isempty(mins);\n if isempty(maxs)\n maxs=max(xyData);\n end\n if isempty(mins)\n mins=min(xyData);\n end\n if needsScaling\n this.onScale=MatBasics.FindOnScale(xyData, mins, maxs);\n cntEdge=size(xyData, 1)-sum(this.onScale);\n if cntEdge>0\n xyData=xyData(this.onScale, :);\n this.N=this.N-cntEdge;\n end\n \n end\n this.mins=mins;\n this.maxs=maxs;\n this.M =gridSize;\n this.deltas=1/(this.M-1)*(maxs-mins); \n this.xyData=xyData;\n this.h=zeros(1, this.D);\n for i =1:this.D\n if this.N.75\n f=.75/m1;\n colorRangeEnd=colorRangeEnd*f;\n end\n end\n nColors=32;\n colors=zeros(nColors,3);\n colors(1,:)=colorRangeStart;\n colors(nColors,:)=colorRangeEnd;\n gap=zeros(1,3);\n for i=1:3\n gap(i)=colorRangeEnd(i)-colorRangeStart(i);\n end\n for i=2:nColors-1\n for j=1:3\n colors(i,j)=colors(1,j)+(i/nColors*gap(1,j));\n end\n end\n end\n end\n nColors=length(colors);\n try\n levels=this.computeLevels(nColors);\n catch ex\n end\n if size(data,1)<10\n color=colors(1, :);\n plot(ax, data(:,1), data(:,2), 'd',...\n 'markersize', 2, 'MarkerEdgeColor',...\n color, 'LineStyle', 'none');\n if ~wasHeld\n hold(ax);\n end\n return;\n end\n try\n colormap(colors);\n catch ex\n disp('huh');\n end\n densities=this.fmatVector(x1);\n lookup=bsearch(levels,densities);\n eventColors=lookup(x3);\n usedColors=unique(eventColors);\n N2=length(usedColors);\n sz=size(data,1);\n if sz<10000\n marker='d';\n ms=2;\n else\n marker='.';\n ms=2;\n end\n for i=1:N2\n colorIdx=usedColors(i);\n li=eventColors==colorIdx;\n plot(ax, data(li,1), data(li,2), marker,...\n 'markersize', ms, 'MarkerEdgeColor',...\n colors(colorIdx, :), 'LineStyle', 'none');\n end\n if ~wasHeld\n hold(ax);\n end\n end\n end\n \n methods(Access=private) \n \n function computeWeight(this)\n this.ye=zeros(2, this.M);\n pointLL=zeros(this.N,2); %this will be the \"lower left\" gridpoint to each data point\n for ii = 1:2\n this.ye(ii,:) = linspace(this.mins(ii), this.maxs(ii), this.M);\n pointLL(:,ii)=floor((this.xyData(:,ii)-this.mins(ii))./this.deltas(ii)) + 1;\n end\n pointLL(pointLL==this.M)=this.M-1; %this avoids going over grid boundary\n %% assign each data point to its closest grid point\n [this.xgrid, this.ygrid]=meshgrid(this.ye(1,:),this.ye(2,:));\n z=reshape(1:this.M^2, this.M, this.M);\n this.dataBinIdxs=interp2(this.xgrid, this.ygrid,z',...\n this.xyData(:,1),this.xyData(:,2),'nearest'); %this associates each data point with its nearest grid point\n \n %% compute w\n Deltmat=repmat(this.deltas, this.N,1);\n shape=this.M*ones(1,2);\n wmat_=zeros(this.M, this.M);\n for ii=0:1 %number of neighboring gridpoints in 2 dimensions\n for j=0:1\n pointm=pointLL+repmat([j ii],this.N,1); %indices of ith neighboring gridpoints\n pointy=zeros(this.N,2);\n for k=1:2\n pointy(:,k)=this.ye(k,pointm(:,k)); %y-values of ith neighboring gridpoints\n end\n W=prod(1-(abs(this.xyData-pointy)./Deltmat),2); %contribution to w from ith neighboring gridpoint from each datapoint\n wmat_=wmat_+accumarray(pointm,W,shape); %sums contributions for ith gridpoint over data points and adds to wmat\n end\n end\n this.wmat=wmat_;\n \n end\n \n function computeDensity(this)\n Z_=zeros(1, this.D);\n Zin=cell(1, this.D);\n for i =1:this.D\n Z_(i)=min(floor(4*this.h(i)/this.deltas(i)), this.M-1);\n Zin{i}=-Z_(i):Z_(i);\n end\n phi = @(x) 1/sqrt(2*pi)*exp(-x.^2./2);\n [L_{1},L_{2}]=meshgrid(Zin{1},Zin{2});\n Phix=phi(L_{1}*this.deltas(1)./this.h(1))./this.h(1);\n Phiy=phi(L_{2}*this.deltas(2)./this.h(2))./this.h(2);\n Phimat = (Phix.*Phiy)'; \n fMat = 1/this.N*conv2(this.wmat,Phimat,'same');\n this.fmatVector=reshape(fMat,[1, this.M^2]);\n this.fmat=fMat';\n [this.xm, this.ym]=meshgrid(this.ye(1,:),this.ye(2,:));\n end\n \n function levels=computeLevels(this, numberOfLevels)\n T=sort(reshape(this.fmat, 1, this.M^this.D));\n CT=cumsum(T);\n NT=CT/CT(end);\n levels=zeros(1, numberOfLevels);\n for level=1:numberOfLevels\n idx=bsearch(NT, level/numberOfLevels);\n levels(level)=T(idx);\n end\n end\n \n end\n \n methods(Static)\n function Draw(ax, data, doContours, doJetColors, reset, ...\n stretchPerc, contourPerc)\n if nargin<7\n contourPerc=10;\n if nargin<6\n stretchPerc=0;\n if nargin<5\n reset=true;\n if nargin<4\n doJetColors=true;\n if nargin<3\n doContours=true;\n end\n end\n end\n end\n end\n if reset\n cla(ax, 'reset');\n end\n try\n if stretchPerc>0\n pb=ProbabilityDensity2(MatBasics.StretchXyData(...\n data, stretchPerc));\n else\n pb=ProbabilityDensity2(data);\n end\n wasHeld=ishold(ax);\n if ~wasHeld\n hold(ax, 'on');\n end\n if doJetColors\n pb.drawJetColors(ax);\n end\n if doContours\n hContour=pb.drawContours(ax, contourPerc);\n if ~doJetColors\n pb.drawContourOutliers(ax, hContour);\n end\n end\n if ~wasHeld\n hold(ax, 'off');\n end\n catch ex\n ex.getReport\n plot(ax, data(:,1), data(:,2));\n end\n end\n \n function [fncMotion, javaLegend, btns, btnLbls, plots, labelHs]=DrawLabeled(ax, ...\n data, lbls, lblMap, doContours, reset, priorFcn, doubleClicker, ...\n xMargin, yMargin, doJavaLegend, oldJavaBtns, southComponent, ...\n selectedCallback, stretchPerc)\n fncMotion=[];\n javaLegend=[];\n btns=[];\n btnLbls=[];\n plots=[];\n if nargin<15\n stretchPerc=0;\n if nargin<14\n selectedCallback=[];\n if nargin<13\n southComponent=[];\n if nargin<12\n oldJavaBtns=[];\n if nargin<11\n doJavaLegend=false;\n if nargin<10\n yMargin=-0.007;\n if nargin<9\n xMargin=-0.007;\n if nargin<8\n doubleClicker=[];\n if nargin<7\n priorFcn=[];\n if nargin<6\n reset=true;\n if nargin<5\n doContours=10;\n if nargin<4\n lblMap=[];\n end\n end\n end\n end\n end\n end\n end\n end\n end\n end\n end\n end\n [addTrainingHtml, sup1, sup2, trStart, trEnd]=...\n LabelBasics.AddTrainingHtml(lblMap, doJavaLegend);\n [R, C]=size(data);\n assert(C==2, 'data''s 2nd dimension must be size 2!');\n [RL, CL]=size(lbls);\n if RL==1 && CL==R\n else\n assert(CL==1, 'Labels'' 2nd dimension must be size 1!');\n assert(R==RL, 'Labels'' 1st dimension size !- data''s 1st!');\n end\n if stretchPerc>0\n pb=ProbabilityDensity2(...\n MatBasics.StretchXyData(data, stretchPerc));\n else\n pb=ProbabilityDensity2(data);\n end\n if reset\n cla(ax, 'reset');\n end\n try\n if doContours\n ms=1;\n else\n ms=2;\n end\n wasHeld=ishold(ax);\n if ~wasHeld\n hold(ax, 'on');\n end\n u=unique(lbls);\n N=length(u);\n labelHs=zeros(1,N);\n if isempty(lblMap)\n for i=1:N\n l=lbls==u(i);\n clr=Gui.HslColor(i, N);\n labelHs(i)=plot(ax, ...\n data(l,1), data(l,2), '.', 'MarkerSize', ms,...\n 'MarkerEdgeColor', clr, 'LineStyle', 'none');\n end\n else\n names={};\n labelIdxs=[];\n for i=1:N\n [key, keyColor, keyTraining]=LabelBasics.Keys(u(i));\n l=lbls==u(i);\n colorString=char(lblMap.get(keyColor));\n if ~isempty(colorString)\n clr=str2num(colorString);\n if any(clr>1)\n clr=clr/256;\n end\n else\n if u(i)==0\n clr=[.9 .9 .9261];\n else\n clr=Gui.HslColor(i, N);\n end\n colorString=num2str(floor(clr*256));\n lblMap.put(keyColor, colorString);\n end\n labelHs(i)=plot(ax, ...\n data(l,1), data(l,2), '.', 'MarkerSize', ms,...\n 'MarkerEdgeColor', clr, 'LineStyle', 'none');\n name=char(lblMap.get(java.lang.String(key)));\n if addTrainingHtml\n name=[name trStart lblMap.get(keyTraining) trEnd];\n end\n if ~isempty(name)\n if doJavaLegend\n if contains(name, '^{')\n name=strrep(name, '^{', sup1);\n name=strrep(name, '}', sup2);\n end\n end\n names{end+1}=name;\n labelIdxs(end+1)=i;\n else\n if u(i)==0\n names{end+1}='unsupervised';\n else\n if u(i)<0\n names{end+1}=['Subset #' ...\n num2str(0-u(i)) ];\n else\n names{end+1}=['Subset #' char(key)];\n end\n end\n labelIdxs(end+1)=i;\n %disp([id ' NOT found' ]);\n end\n end\n if ~isempty(names)\n [javaLegend, fncMotion, btns, sortI, plots]=...\n Plots.Legend(labelHs,...\n names, labelIdxs, xMargin, yMargin, true,...\n [], priorFcn, doubleClicker, doJavaLegend, ...\n oldJavaBtns, southComponent, selectedCallback);\n btnLbls=u(sortI);\n end\n end\n if (islogical(doContours) && doContours) \n hContour=pb.drawContours(ax, 10, [0 0 0]);\n pb.drawContourOutliers(ax, hContour);\n elseif ~isempty(doContours) && doContours>0\n hContour=pb.drawContours(ax, doContours, [0 0 0]);\n pb.drawContourOutliers(ax, hContour);\n end\n if ~wasHeld\n hold(ax, 'off');\n end\n catch ex\n ex.getReport\n end\n end\n end\nend", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/umap/util/ProbabilityDensity2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6882874708208823}} {"text": "%% Options\n%\n%%\n%\n% Many functions provided by MTEX can be customized by options. An option\n% is passed to a method as a string parameter followed by a value. For\n% example, almost all plotting methods support the option *resolution*\n% followed by a double value specifying the resolution in radians. The code below\n% demonstrates the effect of changing this parameter.\n\nodf = SantaFe\nplotPDF(odf,Miller(1,0,0,odf.CS),'resolution',10*degree,'contour','linewidth',2);\n\n%%\n\nplotPDF(odf,Miller(1,0,0,odf.CS),'resolution',2.5*degree,'contour','linewidth',2);\n\n\n%%\n% Options that are not followed by a value are called flags. In the above\n% example, *contour* is a flag that tells the plotting routine to plot\n% contour lines. Options and flags to a function are always optional and\n% can be passed in any order. If conflicting options or flags are passed,\n% i.e., the resolution is specified twice, the later option in the list is\n% considered to be the right one.\n%\n \n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/GeneralConcepts/GeneralConceptsOptions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.6882551607271561}} {"text": "%% Copyright (C) 2016, 2018 Colin B. Macdonald\n%%\n%% This file is part of OctSymPy.\n%%\n%% OctSymPy is free software; you can redistribute it and/or modify\n%% it under the terms of the GNU General Public License as published\n%% by the Free Software Foundation; either version 3 of the License,\n%% or (at your option) any later version.\n%%\n%% This software is distributed in the hope that it will be useful,\n%% but WITHOUT ANY WARRANTY; without even the implied warranty\n%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See\n%% the GNU General Public License for more details.\n%%\n%% You should have received a copy of the GNU General Public\n%% License along with this software; see the file COPYING.\n%% If not, see .\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @defmethod @@sym polylog (@var{s}, @var{z})\n%% Symbolic polylogarithm function.\n%%\n%% Returns the polylogarithm of order @var{s} and argument @var{z}.\n%%\n%% Example:\n%% @example\n%% @group\n%% syms z s\n%% polylog(s, z)\n%% @result{} ans = (sym) polylog(s, z)\n%% diff(ans, z)\n%% @result{} (sym)\n%% polylog(s - 1, z)\n%% \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n%% z\n%% @end group\n%% @end example\n%%\n%% The polylogarithm satisfies many identities, for example:\n%% @example\n%% @group\n%% syms s positive\n%% polylog (s+1, 1)\n%% @result{} (sym) \u03b6(s + 1)\n%% zeta (s+1)\n%% @result{} (sym) \u03b6(s + 1)\n%% @end group\n%% @end example\n%%\n%% @seealso{@@sym/dilog, @@sym/zeta}\n%% @end defmethod\n\nfunction L = polylog(s, z)\n if (nargin ~= 2)\n print_usage ();\n end\n\n L = elementwise_op ('polylog', sym(s), sym(z));\nend\n\n\n%!assert (isequal (polylog (sym('s'), 0), sym(0)))\n\n%!assert (isequal (double (polylog (1, sym(-1))), -log(2)))\n\n%!assert (isequal (double (polylog (0, sym(2))), -2))\n%!assert (isequal (double (polylog (-1, sym(2))), 2))\n%!assert (isequal (double (polylog (-2, sym(3))), -1.5))\n%!assert (isequal (double (polylog (-3, sym(2))), 26))\n%!assert (isequal (double (polylog (-4, sym(3))), -15))\n\n%!assert (isequal (double (polylog (1, sym(1)/2)), log(2)))\n\n%!test\n%! % round trip\n%! syms s z\n%! f = polylog (s, z);\n%! h = function_handle (f, 'vars', [s z]);\n%! A = h (1.1, 2.2);\n%! B = polylog (1.1, 2.2);\n%! assert (A, B)\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/@sym/polylog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.6882551504964973}} {"text": "function az = azimuth(varargin)\n\n report_this_filefun(mfilename('fullpath'));\n\n %AZIMUTH Calculates azimuth between points on a geoid\n %\n % az = AZIMUTH(lat1,lon1,lat2,lon2) computes the great circle\n % bearing between the two points on the globe. The inputs\n % can be matrices of equal size. The azimuth is reported from\n % 0 to 360 degrees, clockwise from north, by convention.\n %\n % az = AZIMUTH(lat1,lon1,lat2,lon2,geoid) computes the great circle\n % bearing assuming that the points lie on the ellipsoid defined by\n % the input geoid. The geoid vector is of the form\n % [semimajor axes, eccentricity]. If omitted, the unit sphere,\n % geoid = [1 0], is assumed.\n %\n % az = AZIMUTH(lat1,lon1,lat2,lon2,'units') uses the input string 'units'\n % to define the angle units of the input and output data. If\n % 'units' is omitted, 'degrees' is assumed.\n %\n % az = AZIMUTH(lat1,lon1,lat2,lon2,geoid,'units') is a valid calling form.\n %\n % az = AZIMUTH('track',...) uses the input string 'track' to define\n % either a great circle bearing or rhumb line heading. If 'track' = 'gc',\n % then the great circle bearings are computed. If 'track' = 'rh', then\n % the rhumb line headings are computed. If omitted, 'gc' is assumed.\n %\n % az = AZIMUTH(pt1,pt2) uses the input form pt1 = [lat1 lon1] and\n % pt2 = [lat2 lon2], where lat1, lon1, lat2 and lon2 are column vectors.\n %\n % az = AZIMUTH(pt1,pt2,geoid), az = AZIMUTH(pt1,pt2,'units'),\n % az = AZIMUTH(pt1,pt2,geoid,'units') and az = AZIMUTH('track',pt1,...)\n % are all valid calling forms.\n %\n % See also DISTANCE, RECKON\n\n % Copyright (c) 1995 by Systems Planning and Analysis, Inc.\n % Written by: E. Byrns, E. Brown\n % $Revision: 1399 $ $Date: 2006-08-11 11:19:27 +0200 (Fr, 11 Aug 2006) $\n\n if nargin < 1\n error('Incorrect number of arguments')\n else\n if ischar(varargin{1})\n str = varargin{1}; varargin(1) = [];\n else\n str = [];\n end\n end\n\n\n % Test the track string and call the appropriate function\n\n if isempty(str)\n [az,msg] = bearing(varargin{:});\n else\n validstr = ['gc';'rh'];\n indx = strmatch(lower(str),validstr);\n if length(indx) ~= 1\n error('Unrecognized track string')\n elseif indx == 1\n [az,msg] = bearing(varargin{:});\n elseif indx == 2\n [az,msg] = heading(varargin{:});\n end\n end\n\n % Error out if necessary\n\n if ~isempty(msg); error(msg); end\n\n\n %************************************************************************\n %************************************************************************\n %************************************************************************\n\n\nfunction [az,msg] = bearing(in1,in2,in3,in4,in5,in6)\n\n %BEARING: Calculates great circle azimuth between points on a geoid\n %\n % Purpose\n %\n % Computes the great circle bearing between two\n % points on a globe. The default angle input\n % is degrees. The default output is in degrees.\n % The default geoid is a sphere, but this can be\n % redefined to an ellipsoid using the geoid input.\n %\n % Synopsis\n %\n % az = bearing(pt1,pt2)\n % az = bearing(pt1,pt2,geoid)\n % az = bearing(pt1,pt2,'units')\n % az = bearing(pt1,pt2,geoid,'units')\n %\n % az = bearing(lat1,lon1,lat2,lon2)\n % az = bearing(lat1,lon1,lat2,lon2,geoid)\n % az = bearing(lat1,lon1,lat2,lon2,'units')\n % az = bearing(lat1,lon1,lat2,lon2,geoid,'units')\n %\n % [az,errmsg] = bearing(....\n % If two output arguments are supplied, then error condition\n % messages are returned to the calling function for processing.\n\n % REFERENCES:\n % For the ellipsoid: D. H. Maling, Coordinate Systems and\n % Map Projections, 2nd Edition Pergamon Press, 1992, pp. 74-76.\n % This forumula can be shown to be equivalent for a sphere to\n % J. P. Snyder, \"Map Projections - A Working Manual,\" US Geological\n % Survey Professional Paper 1395, US Government Printing Office,\n % Washington, DC, 1987, pp. 29-32.\n\n % Copyright (c) 1995 by Systems Planning and Analysis, Inc.\n % Written by: E. Byrns, E. Brown\n % Revision 1.0: 11/7/95\n % Revision 1.1: 11/26/95 elliptical calcs added EVB\n\n\n % Initialize outputs\n\n if nargout ~= 0; az = []; msg = []; end\n\n % Test inputs\n\n if nargin == 2\n if size(in1,2) == 2 && size(in2,2) == 2 && ...\n ndims(in1) == 2 & ndims(in2) == 2\n lat1 = in1(:,1);\tlon1 = in1(:,2);\n lat2 = in2(:,1);\tlon2 = in2(:,2);\n else\n msg = 'Incorrect latitude and longitude data matrices';\n if nargout < 2; error(msg); end\n return\n end\n\n geoid = []; units = [];\n\n elseif nargin == 3\n if size(in1,2) == 2 && size(in2,2) == 2 && ...\n ndims(in1) == 2 & ndims(in2) == 2\n lat1 = in1(:,1);\tlon1 = in1(:,2);\n lat2 = in2(:,1);\tlon2 = in2(:,2);\n else\n msg = 'Incorrect latitude and longitude data matrices';\n if nargout < 2; error(msg); end\n return\n end\n\n if ischar(in3)\n units = in3; geoid = [];\n else\n units = []; geoid = in3;\n end\n\n elseif nargin == 4\n\n if ischar(in4)\n if size(in1,2) == 2 && size(in2,2) == 2 && ...\n ndims(in1) == 2 & ndims(in2) == 2\n lat1 = in1(:,1);\tlon1 = in1(:,2);\n lat2 = in2(:,1);\tlon2 = in2(:,2);\n else\n msg = 'Incorrect latitude and longitude data matrices';\n if nargout < 2; error(msg); end\n return\n end\n\n geoid = in3; units = in4;\n\n else\n lat1 = in1;\t lon1 = in2;\n lat2 = in3;\t lon2 = in4;\n geoid = []; units = [];\n end\n\n elseif nargin == 5\n\n lat1 = in1;\t lon1 = in2;\n lat2 = in3;\t lon2 = in4;\n if ischar(in5)\n units = in5; geoid = [];\n else\n units = []; geoid = in5;\n end\n\n elseif nargin == 6\n\n lat1 = in1;\t lon1 = in2;\n lat2 = in3;\t lon2 = in4;\n geoid = in5; units = in6;\n\n else\n msg = 'Incorrect number of arguments';\n if nargout < 2; error(msg); end\n return\n end\n\n % Empty argument tests. Allows users to pass in an empty argument\n % and still not crash.\n\n if isempty(units); units = 'degrees'; end\n if isempty(geoid) % Unlike related functions reckongc\n geoid = [1 0]; % and distgc, the first argument of geoid\n elseif geoid(1) == 0 % can not be zero. Calculations blow up\n geoid(1) = 1; % (1/0) if geoid(1) = 0\n end\n\n % Dimension tests\n\n if ~isequal(size(lat1),size(lon1),size(lat2),size(lon2))\n msg = 'Inconsistent dimensions for latitude and longitude';\n if nargout < 2; error(msg); end\n return\n end\n\n % Angle unit conversion\n\n lat1 = angledim(lat1,units,'radians');\n lon1 = angledim(lon1,units,'radians');\n lat2 = angledim(lat2,units,'radians');\n lon2 = angledim(lon2,units,'radians');\n\n % Test the geoid parameter\n\n [geoid,msg] = geoidtst(geoid);\n if ~isempty(msg)\n if nargout < 2; error(msg); end\n return\n end\n\n az = zeros(size(lat1)); % Preallocate memory for output\n epsilon = epsm('radians'); % Set tolerance to the pole\n\n % Identify those cases where a pole is a starting\n % point or a destination, and those cases where it is not\n\n indx1 = find(lat1 >= pi/2-epsilon); % north pole starts\n indx2 = find(lat1 <= epsilon-pi/2); % south pole starts\n indx3 = find(lat2 >= pi/2-epsilon); % north pole ends\n indx4 = find(lat2 <= epsilon-pi/2); % south pole ends\n\n indx=1:numel(az); % All cases,\n indx([indx1;indx2;indx3;indx4])=[]; % less the special ones\n\n % Handle the special cases. For example, anything starting\n % at the north pole must go south (pi). Starting point\n % has priority in degenerate cases; i.e. when going from\n % north pole to north pole, result will be pi, not zero.\n\n if ~isempty(indx4); az(indx4) = pi; end % Arrive going south\n if ~isempty(indx3); az(indx3) = 0; end % Arrive going north\n if ~isempty(indx2); az(indx2) = 0; end % Depart going north\n if ~isempty(indx1); az(indx1) = pi; end % Depart going south\n\n % Compute the bearing for either a spherical or elliptical geoid.\n % Note that for a sphere, ratio = 1, par1 = lat1, par2 = lat2\n % and fact4 = 0.\n\n if ~isempty(indx)\n par1 = geod2par(lat1(indx),geoid,'radians'); % Parametric latitudes\n par2 = geod2par(lat2(indx),geoid,'radians');\n\n ratio = minaxis(geoid) / geoid(1); % Semiminor/semimajor (b/a)\n ratio = ratio^2;\n\n fact1 = cos(lat2(indx)) .* sin(lon2(indx)-lon1(indx));\n fact2 = ratio * cos(lat1(indx)) .* sin(lat2(indx));\n fact3 = sin(lat1(indx)) .* cos(lat2(indx)) .* cos(lon2(indx)-lon1(indx));\n fact4 = (1-ratio) * sin(lat1(indx)) .* cos(lat2(indx)) .* ...\n cos(par1) ./ cos(par2);\n\n az(indx) = atan2(fact1,fact2-fact3+fact4);\n end\n\n % Transform the bearing data to the proper range and units\n\n az = zero22pi(az,'radians','exact');\n az = angledim(az,'radians',units);\n\n\n %************************************************************************\n %************************************************************************\n %************************************************************************\n\n\nfunction [course,msg] = heading(in1,in2,in3,in4,in5,in6)\n\n %HEADING: Calculates rhumb-line direction between points on a geoid\n %\n % Purpose\n %\n % Computes the rhumb line direction between two\n % points on a globe. The rhumb line is a line of\n % constant angular direction, a \"course to steer\".\n % The default angle input is degrees. The default output\n % is in degrees. The default geoid is a sphere, but this\n % can be redefined to an ellipsoid using the geoid input.\n %\n % Synopsis\n %\n % course = heading(pt1,pt2)\n % course = heading(pt1,pt2,geoid)\n % course = heading(pt1,pt2,'units')\n % course = heading(pt1,pt2,geoid,'units')\n %\n % course = heading(lat1,lon1,lat2,lon2)\n % course = heading(lat1,lon1,lat2,lon2,geoid)\n % course = heading(lat1,lon1,lat2,lon2,'units')\n % course = heading(lat1,lon1,lat2,lon2,geoid,'units')\n %\n % [course,errmsg] = heading(....\n % If two output arguments are supplied, then error condition\n % messages are returned to the calling function for processing.\n\n\n % Copyright (c) 1995 by Systems Planning and Analysis, Inc.\n % Written by: E. Brown, E. Byrns\n % Revision 1.0: 11/7/95\n % Revision 1.1: 11/28/95 V5 matrix assignment. Mercalc calls. EVB\n\n\n % Initialize outputs\n\n if nargout ~= 0; course = []; msg = []; end\n\n % Test inputs\n\n if nargin == 2\n if size(in1,2) == 2 && size(in2,2) == 2 && ...\n ndims(in1) == 2 && ndims(in2) == 2\n lat1 = in1(:,1);\tlon1 = in1(:,2);\n lat2 = in2(:,1);\tlon2 = in2(:,2);\n else\n msg = 'Incorrect latitude and longitude data matrices';\n if nargout < 2; error(msg); end\n return\n end\n\n geoid = []; units = [];\n\n elseif nargin == 3\n if size(in1,2) == 2 && size(in2,2) == 2 && ...\n ndims(in1) == 2 && ndims(in2) == 2\n lat1 = in1(:,1);\tlon1 = in1(:,2);\n lat2 = in2(:,1);\tlon2 = in2(:,2);\n else\n msg = 'Incorrect latitude and longitude data matrices';\n if nargout < 2; error(msg); end\n return\n end\n\n if ischar(in3)\n units = in3; geoid = [];\n else\n units = []; geoid = in3;\n end\n\n elseif nargin == 4\n\n if ischar(in4)\n if size(in1,2) == 2 && size(in2,2) == 2 && ...\n ndims(in1) == 2 && ndims(in2) == 2\n lat1 = in1(:,1);\tlon1 = in1(:,2);\n lat2 = in2(:,1);\tlon2 = in2(:,2);\n else\n msg = 'Incorrect latitude and longitude data matrices';\n if nargout < 2; error(msg); end\n return\n end\n\n geoid = in3; units = in4;\n\n else\n lat1 = in1;\t lon1 = in2;\n lat2 = in3;\t lon2 = in4;\n geoid = []; units = [];\n end\n\n elseif nargin == 5\n\n lat1 = in1;\t lon1 = in2;\n lat2 = in3;\t lon2 = in4;\n if ischar(in5)\n units = in5; geoid = [];\n else\n units = []; geoid = in5;\n end\n\n elseif nargin == 6\n\n lat1 = in1;\t lon1 = in2;\n lat2 = in3;\t lon2 = in4;\n geoid = in5; units = in6;\n\n else\n msg = 'Incorrect number of arguments';\n if nargout < 2; error(msg); end\n return\n end\n\n\n % Empty argument tests. Allows users to pass in an empty argument\n % and still not crash.\n\n if isempty(units); units = 'degrees'; end\n if isempty(geoid) % Unlike related functions reckonrh\n geoid = [1 0]; % and distrh, the first argument of geoid\n elseif geoid(1) == 0 % can not be zero. Merccalc always returns\n geoid(1) = 1; % [x,y] = 0 if geoid(1) = 0\n end\n\n\n % Dimension tests\n\n if ~isequal(size(lat1),size(lon1),size(lat2),size(lon2))\n msg = 'Inconsistent dimensions for latitude and longitude';\n if nargout < 2; error(msg); end\n return\n end\n\n % Angle unit conversion\n\n lat1 = angledim(lat1,units,'radians');\n lon1 = angledim(lon1,units,'radians');\n lat2 = angledim(lat2,units,'radians');\n lon2 = angledim(lon2,units,'radians');\n\n % Test the geoid parameter\n\n [geoid,msg] = geoidtst(geoid);\n if ~isempty(msg)\n if nargout < 2; error(msg); end\n return\n end\n\n\n course=zeros(size(lat1)); % Preallocate memory for output\n epsilon=epsm('radians'); % Set tolerance to the pole\n\n\n % Identify those cases where a pole is a starting\n % point or a destination, and those cases where it is not\n\n indx1 = find(lat1 >= pi/2-epsilon); % north pole starts\n indx2 = find(lat1 <= epsilon-pi/2); % south pole starts\n indx3 = find(lat2 >= pi/2-epsilon); % north pole ends\n indx4 = find(lat2 <= epsilon-pi/2); % south pole ends\n\n indx=1:numel(course); % All cases,\n indx([indx1;indx2;indx3;indx4])=[]; % less the special ones\n\n % Handle the special cases. For example, anything starting\n % at the north pole must go south (pi). Starting point\n % has priority in degenerate cases; i.e. when going from\n % north pole to north pole, result will be pi, not zero.\n\n if ~isempty(indx4); course(indx4) = pi; end % Arrive going south\n if ~isempty(indx3); course(indx3) = 0; end % Arrive going north\n if ~isempty(indx2); course(indx2) = 0; end % Depart going north\n if ~isempty(indx1); course(indx1) = pi; end % Depart going south\n\n % Now find the course for the general cases by calculating the\n % heading angle in a Mercator coordinate system. The function\n % MERCCALC handles both spherical and elliptical geoids\n\n if ~isempty(indx)\n [x1,y1] = merccalc(lat1(indx),lon1(indx),'forward','radians',geoid);\n [x2,y2] = merccalc(lat2(indx),lon2(indx),'forward','radians',geoid);\n\n % Find points greater than 180 deg apart. Take shorter distance route\n % Allow for some roundoff error\n\n epsilon = 1E-10;\n shift = find( abs((x2-x1)) > pi*geoid(1)-epsilon);\n if ~isempty(shift)\n x1(shift) = x1(shift) + sign(x2(shift))*2*pi*geoid(1);\n end\n\n course(indx) = atan2(x2-x1, y2-y1);\n end\n\n % Transform the heading data to the proper range and units\n\n course = zero22pi(course,'radians','exact');\n course = angledim(course,'radians',units);\n\n\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/azi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6882335290772121}} {"text": "%{\n Tests total-variation problem\n\n min_x ||x||_TV\ns.t.\n || A(x) - b || <= eps\n\nThe solvers solve a regularized version\n\nsee also test_sBP.m and test_sBPDN_W.m\n\nrequires the image processing toolbox for this demo\n(but the TFOCS solver does not rely on this toolbox)\n\nSee also the TV examples in examples/largescale\n\n%}\n\n% Before running this, please add the TFOCS base directory to your path\n\nmyAwgn = @(x,snr) x + ...\n 10^( (10*log10(sum(abs(x(:)).^2)/length(x(:))) - snr)/20 )*randn(size(x));\n\n% Try to load the problem from disk\nfileName = fullfile('reference_solutions','tv_problem1_smoothed_noisy');\nrandn('state',245);\nrand('state',245);\nn = 32;\nn1 = n;\nn2 = n-1; % testing the code with non-square signals\nN = n1*n2;\nM = round(N/2);\nA = randn(M,N);\nif exist([fileName,'.mat'],'file')\n load(fileName);\n fprintf('Loaded problem from %s\\n', fileName );\nelse\n \n % Generate a new problem\n\n n = max(n1,n2);\n x = phantom(n); \n x = x(1:n1,1:n2);\n x_original = x;\n \n mat = @(x) reshape(x,n1,n2);\n vec = @(x) x(:);\n \n\n b_original = A*vec(x_original);\n snr = 40; % SNR in dB\n b = myAwgn(b_original,snr);\n EPS = norm(b-b_original);\n \n tv = linop_TV( [n1,n2], [], 'cvx' );\n \n mu = .005*norm( tv(x_original) ,Inf);\n x0 = zeros(n1,n2);\n\n % get reference via CVX\n tic\n cvx_begin\n cvx_precision best\n variable xcvx(n1,n2)\n minimize tv(xcvx) + mu/2*sum_square(vec(xcvx)-vec(x0) )\n subject to\n norm(A*vec(xcvx) - b ) <= EPS\n cvx_end\n time_IPM = toc;\n x_ref = xcvx;\n obj_ref = tv(x_ref) + mu/2*sum_square(vec(x_ref)-vec(x0) );\n \n save(fileName,'x_ref','b','x_original','mu',...\n 'EPS','b_original','obj_ref','x0','time_IPM','snr');\n fprintf('Saved data to file %s\\n', fileName);\n \nend\n\nimshow( [x_original, x_ref] );\n\n[M,N] = size(A);\n[n1,n2] = size(x_original);\nnorm_x_ref = norm(x_ref,'fro');\nnorm_x_orig = norm(x_original,'fro');\ner_ref = @(x) norm(vec(x)-vec(x_ref))/norm_x_ref;\ner_signal = @(x) norm(x-x_original)/norm_x_orig;\nresid = @(x) norm(A*vec(x)-b)/norm(b); % change if b is noisy\n\n\n%% Call the TFOCS solver\ner = er_ref; % error with reference solution (from IPM)\nopts = [];\nopts.restart = 1000;\nopts.errFcn = { @(f,dual,primal) er(primal), ...\n @(f,dual,primal) obj_ref - f }; \nopts.maxIts = 1000;\n\nW = linop_TV( [n1,n2] );\nnormW = linop_TV( [n1,n2], [], 'norm' );\nopts.normW2 = normW^2;\nz0 = []; % we don't have a good guess for the dual\ntic;\n[ x, out, optsOut ] = solver_sBPDN_W( A, W, b, EPS, mu, vec(x0), z0, opts );\ntime_TFOCS = toc;\n\nfprintf('Solution has %d nonzeros. Error vs. IPM solution is %.2e\\n',...\n nnz(x), er(x) );\n\n% Check that we are within allowable bounds\nif out.err(end,1) < 1e-4\n disp('Everything is working');\nelse\n error('Failed the test');\nend\n\n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/examples/smallscale/test_sTV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.6882335280652878}} {"text": "function [varargout]=tubeplot(x,y,z,varargin) \n\n% TUBEPLOT - plots a tube r along the space curve x,y,z.\n%\n% tubeplot(x,y,z) plots the basic tube with radius 1\n% tubeplot(x,y,z,r) plots the basic tube with variable radius r (either a vector or a value)\n% tubeplot(x,y,z,r,v) plots the basic tube with coloring dependent on the values in the vector v\n% tubeplot(x,y,z,r,v,s) plots the tube with s tangential subdivisions\n% (default is 6)\n%\n% [X,Y,Z]=tubeplot(x,y,z) returns [Nx3] matrices suitable for mesh or surf\n%\n% Note that the tube may pinch at points where the normal and binormal \n% misbehaves. It is suitable for general space curves, not ones that \n% contain straight sections. Normally the tube is calculated using the\n% Frenet frame, making the tube minimally twisted except at inflexion points.\n%\n% To deal with this problem there is an alternative frame:\n% tubeplot(x,y,z,r,v,s,vec) calculates the tube by setting the normal to\n% the cross product of the tangent and the vector vec. If it is chosen so \n% that it is always far from the tangent vector the frame will not twist unduly\n%\n% Example:\n%\n% t=0:(2*pi/100):(2*pi);\n% x=cos(t*2).*(2+sin(t*3)*.3);\n% y=sin(t*2).*(2+sin(t*3)*.3);\n% z=cos(t*3)*.3;\n% tubeplot(x,y,z,0.14*sin(t*5)+.29,t,10)\n%\n% Written by Anders Sandberg, asa@nada.kth.se, 2005\n\n\n subdivs = 6;\n\n N=size(x,1);\n if (N==1)\n x=x';\n y=y';\n z=z';\n N=size(x,1);\n end\n\n if (nargin == 3)\n r=x*0+1;\n else\n r=varargin{1};\n if (size(r,1)==1 & size(r,2)==1)\n r=r*ones(N,1);\n end\n end\n if (nargin > 5)\n subdivs=varargin{3}+1;\n end\n if (nargin > 6)\n vec=varargin{4};\n [t,n,b]=frame(x,y,z,vec);\n else\n [t,n,b]=frenet(x,y,z);\n end\n\n \n\n \n \n\n\n X=zeros(N,subdivs);\n Y=zeros(N,subdivs);\n Z=zeros(N,subdivs);\n\n theta=0:(2*pi/(subdivs-1)):(2*pi);\n\n for i=1:N\n X(i,:)=x(i) + r(i)*(n(i,1)*cos(theta) + b(i,1)*sin(theta));\n Y(i,:)=y(i) + r(i)*(n(i,2)*cos(theta) + b(i,2)*sin(theta));\n Z(i,:)=z(i) + r(i)*(n(i,3)*cos(theta) + b(i,3)*sin(theta));\n end\n\n if (nargout==0)\n if (nargin > 4)\n V=varargin{2};\n if (size(V,1)==1)\n\tV=V';\n end\n V=V*ones(1,subdivs);\n surf(X,Y,Z,V);\n else\n surf(X,Y,Z);\n end\n else\n varargout(1) = {X}; \n varargout(2) = {Y}; \n varargout(3) = {Z}; \n end\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/plot/tubeplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6882335254111136}} {"text": "function [logp, yhat, res] = tapas_cdfgaussian_obs(r, infStates, ptrans)\n% Calculates the log-probability of response y under a cumulative Gaussian distribution. This\n% model has no free parameters.\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2012-2015 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n% Initialize returned log-probabilities as NaNs so that NaN is\n% returned for all irregualar trials\nn = size(infStates,1);\nlogp = NaN(n,1);\nyhat = NaN(n,1);\nres = NaN(n,1);\n\n% Weed irregular trials out from inferred states and responses\nmu2 = infStates(:,2,3);\nmu2(r.irr) = [];\nsa2 = infStates(:,2,4);\nsa2(r.irr) = [];\ny = r.y(:,1);\ny(r.irr) = [];\n\n% Probability mass for x2 < 0\nx2lt0 = 0.5*(1 +erf((0 -mu2)./(sa2.*sqrt(2))));\n\n% Probability of observed choice\nprobc = y.*(1 -x2lt0) +(1 -y).*x2lt0;\n\n% Calculate log-probabilities for non-irregular trials\n% Note: 8*atan(1) == 2*pi (this is used to guard against\n% errors resulting from having used pi as a variable).\nreg = ~ismember(1:n,r.irr);\nlogp(reg) = log(probc);\nyh = 1 -x2lt0;\nyhat(reg) = yh;\nres(reg) = (y -yh)./sqrt(yh.*(1 -yh));\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_cdfgaussian_obs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.87059725497852, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6882335211146898}} {"text": "%File Description:\n% Unknown parameters in accelerometer error model are calculated using the\n% lm optimization algorithm.\nclose all\nclc\nclear\n\nload AccRaw\n%@ g = 9.8;\nm = length(AccRaw);\n\ny_dat = g*ones(m,1); % expected gravitational acceleration \np0 = [1 1 1 0 0 0]';\np_init = [1.0 1.0 1.0 0.1 0.1 0.1]'; % initial value of unknown parameters\n\n\ny_raw = calFunc(AccRaw, p0); % gravitational acceleration measured by accelerometer\ny_raw = y_raw(:);\nr_raw = y_dat - y_raw;\np_fit = lm('calFunc', p_init, AccRaw, y_dat);\ny_lm = calFunc(AccRaw,p_fit); % gravitational acceleration measured by calibrated accelerometer\ny_lm = y_lm(:);\nr_lm = y_dat - y_lm;\n\nkx = p_fit(1);\nky = p_fit(2);\nkz = p_fit(3);\nbx = p_fit(4);\nby = p_fit(5);\nbz = p_fit(6);\n\nKa1=[kx 0 0;0 ky 0;0 0 kz]\nba1=[bx by bz]'\nsave('calP1','Ka1','ba1')\n\n\nfigure\nbar([r_raw'*r_raw, r_lm'*r_lm])\ngrid on;\nset(gca,'XTickLabel', {'raw','lm'});\nylabel('fa');\n\nt=1:m;\nfigure\ntitle('Accelerometer Calibration')\nplot(t, r_raw, t, r_lm)\nlegend('Uncalibrated', 'Calibrated-LM')\nxlabel('Sampling sequence')\nylabel('Residual')\n", "meta": {"author": "RflySim", "repo": "RflyExpCode", "sha": "7dbec4d8796d6e23ee86c523e4ba5712203b1519", "save_path": "github-repos/MATLAB/RflySim-RflyExpCode", "path": "github-repos/MATLAB/RflySim-RflyExpCode/RflyExpCode-7dbec4d8796d6e23ee86c523e4ba5712203b1519/code/e3/e3.2/calLM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894576856559, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6881648835093594}} {"text": "function [interp_value] = grid_bilin_interp(X_approx, Y_approx, grid, ncols, nrows, cellsize, Xll, Yll, nodata)\n\n% SYNTAX:\n% [interp_value] = grid_bilin_interp(X_approx, Y_approx, grid, ncols, nrows, cellsize, Xll, Yll, nodata);\n%\n% INPUT:\n% X_approx = X coordinate of the interpolation point\n% Y_approx = Y coordinate of the interpolation point\n% grid = matrix containing the grid\n% ncols = number of columns of the grid\n% nrows = number of rows of the grid\n% cellsize = ground size of a cell\n% Xll = X coordinate of the center of the lower left cell\n% Yll = Y coordinate of the center of the lower left cell\n% nodata = value used for cells not containing data\n%\n% OUTPUT:\n% interp_value = interpolated value\n%\n% DESCRIPTION:\n% Function that applies a bilinear interpolation of the four nearest nodes\n% of a georeferenced grid in correspondence of a point of given coordinates.\n\n%--- * --. --- --. .--. ... * ---------------------------------------------\n% ___ ___ ___\n% __ _ ___ / __| _ | __|\n% / _` / _ \\ (_ | _|__ \\\n% \\__, \\___/\\___|_| |___/\n% |___/ v 1.0RC1\n%\n%--------------------------------------------------------------------------\n% Copyright (C) 2021 Geomatics Research & Development srl (GReD)\n% Written by: Mirko Reguzzoni\n% Contributors: ...\n% A list of all the historical goGPS contributors is in CREDITS.nfo\n%--------------------------------------------------------------------------\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%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\n%preparation of the grid axes\nX = (Xll : cellsize : Xll + (ncols - 1) * cellsize)';\nY = (Yll : cellsize : Yll + (nrows - 1) * cellsize)';\n\nif (X_approx <= X(1) | X_approx >= X(end) | Y_approx <= Y(1) | Y_approx >= Y(end))\n interp_value = nodata;\n return\nend\n\n%detection of the grid node nearest to the interpolation point\n[mX, posX] = min(abs(X - X_approx));\n[mY, posY] = min(abs(Y - Y_approx));\n\n%definition of the four grid nodes that sorround the interpolation point\n% (i,j) image coordinates (upper-left origin)\n% (X,Y) ground coordinates (bottom-left origin)\nif (X(posX) > X_approx) | (mX ==0)\n j_left = posX - 1;\n j_right = posX;\n X_left = X(posX - 1);\nelse\n j_left = posX;\n j_right = posX + 1;\n X_left = X(posX);\nend\n\nif (Y(posY) > Y_approx) | (mY ==0)\n i_up = nrows + 1 - posY;\n i_down = i_up + 1;\n Y_down = Y(posY - 1);\nelse\n i_down = nrows + 1 - posY;\n i_up = i_down - 1;\n Y_down = Y(posY);\nend\n\n%if one of the interp_value values of the four sorrounding points is a nodata value, do not interpolate and return nodata value\nif (grid(i_up,j_left) == nodata | grid(i_up,j_right) == nodata | grid(i_down,j_left) == nodata | grid(i_down,j_right) == nodata)\n interp_value = nodata;\n return\nend\n\n%computation of the parameters of the bilinear function\n%f(X, Y) = a*X*Y + b*X + c*Y + d\n\nA = [0 0 cellsize 1; ...\n cellsize^2 cellsize cellsize 1; ...\n 0 0 0 1; ...\n 0 cellsize 0 1];\n\nB = [grid(i_up,j_left);...\n grid(i_up,j_right);...\n grid(i_down,j_left);...\n grid(i_down,j_right)];\n\nbilin_param = A\\B;\n\ni_approx = Y_approx - Y_down;\nj_approx = X_approx - X_left;\n\n%computation of the interpolated value\ninterp_value = bilin_param(1) * j_approx * i_approx + bilin_param(2) * j_approx + bilin_param(3) * i_approx + bilin_param(4);\ninterp_value = double(interp_value);\n", "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/dtm/grid_bilin_interp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715774, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6881230268332412}} {"text": "% NUMDIM - estimate a lower bound on the (minimum) number of discrete sources \n% in the data via their second-order statistics.\n% Usage:\n% >> num = numdim( data );\n%\n% Inputs:\n% data - 2-D data (nchannel x npoints)\n%\n% Outputs:\n% num - number of sources (estimated from second order measures)\n%\n% References:\n% WACKERMANN, J. 1996. Beyond mapping: estimating complexity \n% of multichannel EEG recordings. Acta Neurobiologiae \n% Experimentalis, 56, 197-208.\n% WACKERMANN, J. 1999. Towards a quantitative characterization \n% of functional states of the brain: from non-linear methodology \n% to the global linear description. International Journal of \n% Psychophysiology, 34, 65-80.\n%\n% Author: Arnaud Delorme, CNL / Salk Institute, 23 January 2003\n\n% Copyright (C) 2002 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction lambda = numdim( a )\n \n if nargin < 1\n help numdim;\n return;\n end\n \n% Akaike, Identification toolbox (linear identification)\n\n a = a';\n b = a'*a/100; % correlation\n [v d] = eig(b);\n %det(d-b); % checking\n \n l = diag(d);\n l = l/sum(l);\n lambda = real(exp(-sum(l.*log(l))));\n \n return;\n \n \n % testing by duplicating columns\n a = rand(100,5)*2-1;\n a = [a a];\n numdim( a )\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/numdim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505428129515, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6881230258355348}} {"text": "function [logp, s] = kde(train, test, s)\n\n%KDE Kernel Density Estimation.\n% This function computes a kernel density estimator from a set of examples,\n% by placing Gaussian kernels (with identical masses) on each training data\n% point and adjusting the \"widths\" to maximize the sum of leave-one-out log\n% densities. In multivariate data, either isotropic or diagonal covariance\n% matrix Gaussians are used.\n%\n% usage: [logp, s] = kde(train, test, s)\n%\n% inputs: train (n by D) is a matrix of n training points in D dimensions\n% test (N by D) is a matrix of test points\n% s scalar or (1 by D) is a start guess for std devs (optional)\n%\n% outputs: logp (1 by N) is the vector of test log densities\n% s final std devs\n% \n% The size of the initial guess for s indicates whether isotropic or\n% diagonal covariance is desired. If no initial guess is supplied, diagonal\n% is assumed. The method uses a Newton scheme in the log of s, and usually\n% converges in very few iterations. The Newton steps are checked to ensure\n% that a reasonable fraction (half) of the expected improvement is achieved;\n% otherwise smaller steps are tried. The computational complexity is order\n% (nD)^2 + nND, memory requirement order Dn(N+n). The algorithm may\n% encounter numerical problems if initial guess is too small.\n%\n% (C) Copyright Carl Edward Rasmussen, July 4th 2000.\n\n[N, D] = size(test); [n, D] = size(train); % get number of cases and dimension\nif nargin == 2 % if no start guess is given then\n s = std(train)/(n^(0.5/D)); % use scaled empirical axis aligned std devs\nend\nP = length(s); % number of parameters to fit\n\nt = repmat(train,[1,1,n]);\nif P == 1 % if we are fitting a single width\n c = sum((permute(t,[1,3,2])-permute(t,[3,1,2])).^2,3);\nelse % else multiple parameters\n c = (permute(t,[1,3,2])-permute(t,[3,1,2])).^2;\nend\n\nG = 1; TINY = 1e-10;\nec = exp(-sum(c./repmat(permute(2*s.^2,[1,3,2]),[n,n,1]),3));\nsecd = repmat(sum(ec-eye(n),2),[1,P]);\nf_old = sum(log(secd(:,1)))-n*sum(log(s));\nwhile max(abs(G)) > TINY\n x = shiftdim(sum(repmat(ec,[1,1,P]).*c,1))./secd;\n DE = sum(x,1)./s.^2;\n xx = repmat(x,[1 1 P]);\n for i=1:P % rewriting this loop as matrix expr would cost too much mem\n DDE(i,1:P) = sum(shiftdim(sum(c.*repmat(ec.*c(:,:,i),[1,1,P])))./secd);\n end\n DDE = (DDE - shiftdim(sum(xx.*permute(xx,[1,3,2]))))./(s'*s).^2;\n [v, l] = eig(DDE-2*diag(DE)); % eigs of Hessian\n l = max(abs(diag(l)),min(l(:)/TINY)); % control sign and magnitude of eigs\n G = (n*D/P-DE)*v*diag(-1./l)*v'; % compute Newton step\n G = G/max(1, sqrt(G*G')); % don't take too large a step\n eta = 1; s_old = s;\n while eta == 1 | f_new < f_old - eta*G*(n*D/P-DE')/2 - TINY % improvement?\n s = s_old.*exp(G*eta);\n eta = eta/2; % if we fail, then try smaller step next time around\n ec = exp(-sum(c./repmat(permute(2*s.^2,[1,3,2]),[n,n,1]),3));\n secd = repmat(sum(ec-eye(n),2),[1,P]);\n f_new = sum(log(secd(:,1)))-n*sum(log(s));\n end\n f_old = f_new; % remember function value for next iteration\nend\n\nx = repmat(2*s.^2,[n,D/P]);\nlogp = zeros(N, 1);\nfor i=1:N % rewriting this loop as matrix expr would cost too much mem\n cc = sum((repmat(test(i,:),[n,1])-train).^2./x,2);\n hh = min(cc);\n logp(i) = log(mean(exp(hh-cc)))-hh;\nend\n\nlogp = logp - D*log(2*pi)/2 - D*sum(log(s))/P; % normalize densities\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/common/kde.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6881230248778466}} {"text": "% test for run length coding\n\n% some signal with long cluster of 0/1\nn = 1024*2;\noptions.alpha = 0.1;\nx = load_signal('regular',n,options); \nx = (x-mean(x))>0;\n\noptions.rle_coding_mode = 'shannon';\n[tmp,nb_shannon] = perform_rle_coding(x, +1, options);\ndisp(sprintf('Shannon = %.2f', nb_shannon));\n\noptions.rle_coding_mode = 'arithmetic';\n[tmp,nb_arith] = perform_rle_coding(x, +1, options);\ndisp(sprintf('Arithmetic = %.2f', nb_arith));\n\noptions.rle_coding_mode = 'arithfixed';\n[tmp,nb_arithfixed] = perform_rle_coding(x, +1, options);\ndisp(sprintf('Arithmetic(laplacian) = %.2f', nb_arithfixed));\n\n[tmp,nb_direct] = perform_arithmetic_coding(x, +1);\ndisp(sprintf('Direct(entropy) = %.2f', nb_direct));\n\noptions.rle_coding_mode = 'nocoding';\n[tmp,nb_nocode] = perform_rle_coding(x, +1, options);\ndisp(sprintf('No code = %.2f', nb_nocode));\n\n% test for bijectivity\noptions.rle_coding_mode = 'nocoding';\nstream = perform_rle_coding(x, +1, options);\nxx = perform_rle_coding(stream, -1, options);\ndisp( sprintf('Error (should be 0): %.2f', norme(x-xx)) );\n\noptions.rle_coding_mode = 'arithfixed';\nstream = perform_rle_coding(x, +1, options);\nxx = perform_rle_coding(stream, -1, options);\ndisp( sprintf('Error (should be 0): %.2f', norme(x-xx)) );", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_signal/tests/test_rle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6881230239201577}} {"text": "function out = trigcoeffs(f, N)\n%TRIGCOEFFS Trigonometric Fourier coefficients of a CLASSICFUN.\n% C = TRIGCOEFFS(F) returns the trigonometric Fourier coefficients of F\n% using complex-exponential form. Specifically, for N = length(F)\n% If N is odd\n% F(x) = C(1)*z^(N-1)/2 + C(2)*z^((N-1)/2-1) + ... + C((N+1)/2) + ... \n% + C(N)*z^(-(N-1)/2)\n% If N is even\n% F(x) = C(1)*z^(N/2-1) + C(2)*z^(N/2-2) + ... + C(N/2) + ...\n% + C(N-1)*z^(-N/2-1) + 1/2*C(N)*(z^(N/2) + z^(-N/2))\n% where z = exp(1i*pi*x).\n%\n% A = TRIGCOEFFS(F, N) truncates or pads the vector C so that N coefficients\n% of F are returned.\n%\n% If F is array-valued with M columns, then C is an MxN matrix.\n%\n% See also LEGCOEFFS, CHEBCOEFFS.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( nargin == 1 )\n N = length(f);\nend\n\n% Call TRIGCOEFFS() of the .ONEFUN:\nout = trigcoeffs(f.onefun, N);\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/@classicfun/trigcoeffs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6881230209670568}} {"text": "% Figure 3.4 Feedback Control of Dynamic Systems, 6e\n% Franklin, Powell, Emami\n% script to generate Fig. 3.4\n%% fig3_04.m Example 3.5\nclf;\nk=1;\nnum=1; % form numerator\nden=[1 k]; % form denominator\n% sinusoidal input signal\ndeltaT = 0.001;\nt=0:deltaT:10; % form time vector\nu=sin(10*(t)); % form input\nsys=tf(num,den); % form system\n[y]=lsim(sys,u,t); % linear simulation\n% plot response\nfigure();\nplot(t,y);\nxlabel('Time (sec)');\nylabel('Output');\ntitle('Fig. 3.4 (a): transient response');\npause;\nhold on;\ny1=(10/101)*exp(-t);\nphi=atan(-10);\ny2=(1/sqrt(101))*sin(10*t+phi);\nplot(t,y1,t,y2,t,y1+y2);\n% grid\nnicegrid\nhold off;\npause;\nfigure();\nii=[9001:10001];\nplot(t(ii),y(ii),t(ii),u(ii));\nxlabel('Time (sec)');\nylabel('Output, input');\ntitle('Fig. 3.4 (b): Steady-state response');\ntext(9.4,0.65,'u(t)');\ntext(9.24,0.12,'y(t)');\n% grid\nnicegrid\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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig3_04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6881230209270386}} {"text": "classdef prtPreProcLda < prtPreProcClass\n % prtPreProcLda Linear discriminant analysis processing\n %\n % preProc = prtPreProcLda creates a linear discriminant pre\n % processing object. A prtPreProcLda object projects the input data\n % onto a linear space that best separates class labels\n %\n % A prtPreProcLda object has the following properties:\n %\n % nComponents - The number of dimensions to project the data onto.\n % This must less than or equal to the input data's\n % number of features, and less than or equal to the \n % input data sets number of classes.\n %\n % A prtPreProcLda object also inherits all properties and functions from\n % the prtAction class\n %\n % More information about LDA can be found at the following URL:\n % http://en.wikipedia.org/wiki/Linear_discriminant_analysis\n %\n % Example:\n %\n % dataSet = prtDataGenIris; % Load a dataset\n % dataSet = dataSet.retainFeatures(1:3); % Retain the first 3 features\n % lda = prtPreProcLda; % Create the pre-processor\n %\n % lda = lda.train(dataSet); % Train\n % dataSetNew = lda.run(dataSet); % Run\n %\n % % Plot the results\n % subplot(2,1,1); plot(dataSet);\n % title('Original Data');\n % subplot(2,1,2); plot(dataSetNew);\n % title('LDA Projected Data');\n %\n % See Also: prtPreProc, prtPreProcPca, prtPreProcPls,\n % prtPreProcHistEq, prtPreProcZeroMeanColumns, prtPreProcLda,\n % prtPreProcZeroMeanRows, prtPreProcLogDisc, prtPreProcZmuv,\n % prtPreProcMinMaxRows\n\n\n\n\n\n\n\n properties (SetAccess=private)\n name = 'Linear discriminant analysis' % Linear discriminant analysis\n nameAbbreviation = 'LDA' % LDA\n end\n \n properties\n nComponents = 2; % The number of LDA components\n end\n properties (SetAccess=private)\n projectionMatrix = []; % The projection matrix\n globalMean = []; % The global mean\n end\n \n methods\n \n % Allow for string, value pairs\n function Obj = prtPreProcLda(varargin)\n Obj = prtUtilAssignStringValuePairs(Obj,varargin{:});\n end\n\tend\n \n\tmethods (Hidden = true)\n function featureNameModificationFunction = getFeatureNameModificationFunction(obj) %#ok\n featureNameModificationFunction = prtUtilFeatureNameModificationFunctionHandleCreator('LDA Score #index#');\n end\n\tend\n \n methods\n function Obj = set.nComponents(Obj,nComp)\n if ~prtUtilIsPositiveScalarInteger(nComp)\n error('prt:prtPreProcPca','nComponents must be a positive scalar integer');\n end\n Obj.nComponents = nComp;\n end\n end\n \n methods (Access=protected,Hidden=true)\n \n function Obj = trainAction(Obj,DataSet)\n if Obj.nComponents > DataSet.nClasses\n error('prt:prtPreProcLda','Attempt to train LDA pre-processor with more components (%d) than unique classes in data set (%d)',Obj.nComponents,DataSet.nClasses);\n end\n [Obj.projectionMatrix,Obj.globalMean] = prtUtilLinearDiscriminantAnalysis(DataSet,Obj.nComponents);\n end\n \n function DataSet = runAction(Obj,DataSet)\n \n X = DataSet.getObservations;\n X = bsxfun(@minus,X,Obj.globalMean);\n DataSet = DataSet.setObservations(X*Obj.projectionMatrix);\n end\n \n end\n \nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/preProc/prtPreProcLda.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.6881230042861737}} {"text": "% Test spectrogram\n\nfunction tPlotSpectrogram\n\naddpath('..');\n\n[x, Fs] = wavread('addf8.wav');\n\nOptions = {'BW', 'NB', 'FLim', [500 1500]};\nPlotSpectrogram(x, Fs, Options{:});\ncolormap(SpecColorMap);\ncolorbar;\n\n% Use alternate colour map\nfigure;\n\nOptions = {'NSlice', 450, 'preF', 0.97, 'BW', 'WB'};\nTLen = (length(x)-1)/Fs;\nTLim = [0.3*TLen, 0.4*TLen];\nPlotSpectrogram(x, TLim, Fs, Options{:});\ncolorbar;\n\n% Sine wave test (expect sine wave peak at -6 dBov)\n% Changing fc to 0, gives 0 dBov at dc\nFs = 16000;\nfc = Fs/8;\nNSamp = 5000;\nt = (0:NSamp-1)/Fs;\nAmax = 32767;\nx = Amax * cos(2*pi*t*fc);\n\nPmaxdBSPL = 92; % Max level in dB SPL\nPoffsdB = PmaxdBSPL + 20*log10(2);\ng = 10^(PoffsdB/20);\nAmaxN = Amax/g;\n\nfigure;\nOptions = {'Amax', AmaxN, 'FLim', [0 4000]};\nPlotSpectrogram(x, Fs, Options{:});\ncolormap(SpecColorMap);\ncolorbar;\n\nreturn\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/24321-plotspectrogram/Spectrogram/test/tPlotSpectrogram.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6880751983354505}} {"text": "function [reg_c,rho_c,eta_c] = l_corner(rho,eta,reg_param,U,s,b,method,M)\n%L_CORNER Locate the \"corner\" of the L-curve.\n%\n% [reg_c,rho_c,eta_c] =\n% l_corner(rho,eta,reg_param)\n% l_corner(rho,eta,reg_param,U,s,b,method,M)\n% l_corner(rho,eta,reg_param,U,sm,b,method,M) , sm = [sigma,mu]\n%\n% Locates the \"corner\" of the L-curve in log-log scale.\n%\n% It is assumed that corresponding values of || A x - b ||, || L x ||,\n% and the regularization parameter are stored in the arrays rho, eta,\n% and reg_param, respectively (such as the output from routine l_curve).\n%\n% If nargin = 3, then no particular method is assumed, and if\n% nargin = 2 then it is issumed that reg_param = 1:length(rho).\n%\n% If nargin >= 6, then the following methods are allowed:\n% method = 'Tikh' : Tikhonov regularization\n% method = 'tsvd' : truncated SVD or GSVD\n% method = 'dsvd' : damped SVD or GSVD\n% method = 'mtsvd' : modified TSVD,\n% and if no method is specified, 'Tikh' is default. If the Spline Toolbox\n% is not available, then only 'Tikh' and 'dsvd' can be used.\n%\n% An eighth argument M specifies an upper bound for eta, below which\n% the corner should be found.\n\n% Per Christian Hansen, IMM, July 26, 2007.\n\n% Set default regularization method.\nif (nargin <= 3)\n method = 'none';\n if (nargin==2), reg_param = (1:length(rho))'; end\nelse\n if (nargin==6), method = 'Tikh'; end\nend\n\n% Set this logical variable to 1 (true) if the corner algorithm\n% should always be used, even if the Spline Toolbox is available.\nalwayscorner = 0;\n\n% Set threshold for skipping very small singular values in the\n% analysis of a discrete L-curve.\ns_thr = eps; % Neglect singular values less than s_thr.\n\n% Set default parameters for treatment of discrete L-curve.\ndeg = 2; % Degree of local smooting polynomial.\nq = 2; % Half-width of local smoothing interval.\norder = 4; % Order of fitting 2-D spline curve.\n\n% Initialization.\nif (length(rho) < order)\n error('Too few data points for L-curve analysis')\nend\nif (nargin > 3)\n [p,ps] = size(s); [m,n] = size(U);\n beta = U'*b;\n if (m>n), b0 = b - U*beta; end\n if (ps==2)\n s = s(p:-1:1,1)./s(p:-1:1,2);\n beta = beta(p:-1:1);\n end\n xi = beta./s;\nend\n\n% Restrict the analysis of the L-curve according to M (if specified).\nif (nargin==8)\n index = find(eta < M);\n rho = rho(index); eta = eta(index); reg_param = reg_param(index);\nend\n\nif (strncmp(method,'Tikh',4) | strncmp(method,'tikh',4))\n\n % The L-curve is differentiable; computation of curvature in\n % log-log scale is easy.\n\n % Compute g = - curvature of L-curve.\n g = lcfun(reg_param,s,beta,xi);\n\n % Locate the corner. If the curvature is negative everywhere,\n % then define the leftmost point of the L-curve as the corner.\n [gmin,gi] = min(g);\n reg_c = fminbnd('lcfun',...\n reg_param(min(gi+1,length(g))),reg_param(max(gi-1,1)),...\n optimset('Display','off'),s,beta,xi); % Minimizer.\n kappa_max = - lcfun(reg_c,s,beta,xi); % Maximum curvature.\n\n if (kappa_max < 0)\n lr = length(rho);\n reg_c = reg_param(lr); rho_c = rho(lr); eta_c = eta(lr);\n else\n f = (s.^2)./(s.^2 + reg_c^2);\n eta_c = norm(f.*xi);\n rho_c = norm((1-f).*beta);\n if (m>n), rho_c = sqrt(rho_c^2 + norm(b0)^2); end\n end\n\nelseif (strncmp(method,'tsvd',4) | strncmp(method,'tgsv',4) | ...\n strncmp(method,'mtsv',4) | strncmp(method,'none',4))\n\n % Use the adaptive pruning algorithm to find the corner, if the\n % Spline Toolbox is not available.\n if ~exist('splines','dir') | alwayscorner\n %error('The Spline Toolbox in not available so l_corner cannot be used')\n reg_c = corner(rho,eta);\n rho_c = rho(reg_c);\n eta_c = eta(reg_c);\n return\n end\n\n % Othersise use local smoothing followed by fitting a 2-D spline curve\n % to the smoothed discrete L-curve. Restrict the analysis of the L-curve\n % according to s_thr.\n if (nargin > 3)\n if (nargin==8) % In case the bound M is in action.\n s = s(index,:);\n end\n index = find(s > s_thr);\n rho = rho(index); eta = eta(index); reg_param = reg_param(index);\n end\n\n % Convert to logarithms.\n lr = length(rho);\n lrho = log(rho); leta = log(eta); slrho = lrho; sleta = leta;\n\n % For all interior points k = q+1:length(rho)-q-1 on the discrete\n % L-curve, perform local smoothing with a polynomial of degree deg\n % to the points k-q:k+q.\n v = (-q:q)'; A = zeros(2*q+1,deg+1); A(:,1) = ones(length(v),1);\n for j = 2:deg+1, A(:,j) = A(:,j-1).*v; end\n for k = q+1:lr-q-1\n cr = A\\lrho(k+v); slrho(k) = cr(1);\n ce = A\\leta(k+v); sleta(k) = ce(1);\n end\n\n % Fit a 2-D spline curve to the smoothed discrete L-curve.\n sp = spmak((1:lr+order),[slrho';sleta']);\n pp = ppbrk(sp2pp(sp),[4,lr+1]);\n\n % Extract abscissa and ordinate splines and differentiate them.\n % Compute as many function values as default in spleval.\n P = spleval(pp); dpp = fnder(pp);\n D = spleval(dpp); ddpp = fnder(pp,2);\n DD = spleval(ddpp);\n ppx = P(1,:); ppy = P(2,:);\n dppx = D(1,:); dppy = D(2,:);\n ddppx = DD(1,:); ddppy = DD(2,:);\n\n % Compute the corner of the discretized .spline curve via max. curvature.\n % No need to refine this corner, since the final regularization\n % parameter is discrete anyway.\n % Define curvature = 0 where both dppx and dppy are zero.\n k1 = dppx.*ddppy - ddppx.*dppy;\n k2 = (dppx.^2 + dppy.^2).^(1.5);\n I_nz = find(k2 ~= 0);\n kappa = zeros(1,length(dppx));\n kappa(I_nz) = -k1(I_nz)./k2(I_nz);\n [kmax,ikmax] = max(kappa);\n x_corner = ppx(ikmax); y_corner = ppy(ikmax);\n\n % Locate the point on the discrete L-curve which is closest to the\n % corner of the spline curve. Prefer a point below and to the\n % left of the corner. If the curvature is negative everywhere,\n % then define the leftmost point of the L-curve as the corner.\n if (kmax < 0)\n reg_c = reg_param(lr); rho_c = rho(lr); eta_c = eta(lr);\n else\n index = find(lrho < x_corner & leta < y_corner);\n if ~isempty(index)\n [dummy,rpi] = min((lrho(index)-x_corner).^2 + (leta(index)-y_corner).^2);\n rpi = index(rpi);\n else\n [dummy,rpi] = min((lrho-x_corner).^2 + (leta-y_corner).^2);\n end\n reg_c = reg_param(rpi); rho_c = rho(rpi); eta_c = eta(rpi);\n end\n\nelseif (strncmp(method,'dsvd',4) | strncmp(method,'dgsv',4))\n\n % The L-curve is differentiable; computation of curvature in\n % log-log scale is easy.\n\n % Compute g = - curvature of L-curve.\n g = lcfun(reg_param,s,beta,xi,1);\n\n % Locate the corner. If the curvature is negative everywhere,\n % then define the leftmost point of the L-curve as the corner.\n [gmin,gi] = min(g);\n reg_c = fminbnd('lcfun',...\n reg_param(min(gi+1,length(g))),reg_param(max(gi-1,1)),...\n optimset('Display','off'),s,beta,xi,1); % Minimizer.\n kappa_max = - lcfun(reg_c,s,beta,xi,1); % Maximum curvature.\n\n if (kappa_max < 0)\n lr = length(rho);\n reg_c = reg_param(lr); rho_c = rho(lr); eta_c = eta(lr);\n else\n f = s./(s + reg_c);\n eta_c = norm(f.*xi);\n rho_c = norm((1-f).*beta);\n if (m>n), rho_c = sqrt(rho_c^2 + norm(b0)^2); end\n end\n\nelse\n error('Illegal method')\nend", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/external/regu/regu/l_corner.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.6880751884224701}} {"text": "function dq = linevel2dq(v,r,vp,rp)\n\n% LINEVEL2DQ Transforms a line velocity expressed in vector notation \n% into its dual quaternion representation.\n%\n% DQ = LINE2DQ(V,R,VP,RP) transforms the line position, specified by:\n% - the line orientation V\n% - the position of any point of the line, R.\n% - the line orientation rate of change, VP\n% - the velocity component (orthogonal to the line orientation V)\n% of point P, RP\n% V does not need to be unitary, but VP must be orthogonal to V. If\n% RP has a component in the V orientation, it does not matter, since\n% it does not change the expression of the resulting dual quaternion\n% DQ.\n% V,R,VP and RP must have the same size. The inputs (V,R,VP,RP) are\n% either a vector of size 3 or an array of size 3*N (column i \n% represents the input component of Line velocity i) where N is the\n% number of lines. DQ is either a vector of size 8, either an array \n% of size (8*N) depending on the input format. Each column of DQ \n% represents the dual quaternion representation of the corresponding\n% line position velocity.\n%\n% See also POS2DQ, VEL2DQ, LINE2DQ\n\nsv = size(v);\nsr = size(r);\nsvp = size(vp);\nsrp = size(rp);\nif sv == [1 3], v = v.'; sv = size(v); end\nif sr == [1 3], r = r.'; sr = size(r); end\nif svp == [1 3], vp = vp.'; svp = size(vp); end\nif srp == [1 3], rp = rp.'; srp = size(rp); end\n\n% check that all inputs have the same size\ntab_s = [sv; sr; svp; srp];\nif max(tab_s) ~= min(tab_s)\n error('DualQuaternion:linevel2dquat:sizesDoNotMatch',...\n 'Arrays v, r, vp and r should be the same size. Size of \\n - v is [%d %d] \\n - r is [%d %d] \\n - vp is [%d %d] \\n - rp is [%d %d]',...\n sv(1),sv(2),sr(1),sr(2),svp(1),svp(2),srp(1),srp(2)); \nend\n\n% if the format is wrong\nif sv(1) ~= 3 \n error('DualQuaternion:linevel2dquat:wrongsize',...\n '%d rows in the V,R,VP and RP arrays. It should be 3. ',sv(1));\nend\n \n% normalization of the axis vector (if necessary)\nn = length(v(1,:));\nn2 = sum(v.^2).^0.5;\nn2 = repmat(n2,3,1);\nv=v./n2;\nvp=vp./n2;\n\n% construction of the line velocity dual quaternion\ndq = sym(zeros(8,n));\ndq(2:4,:) = vp;\ndq(6:8,:) = cross(r,vp)+cross(rp,v);\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/43393-dual-quaternion-symbolic-toolbox/Dual quaternion symbolic toolbox/linevel2dq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6880751864439401}} {"text": "function cheby_u_poly_test ( )\n\n%*****************************************************************************80\n%\n%% CHEBY_U_POLY_TEST tests CHEBY_U_POLY.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 January 2015\n%\n% Author:\n%\n% John Burkardt\n%\n n_max = 12;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHEBY_U_POLY_TEST:\\n' );\n fprintf ( 1, ' CHEBY_U_POLY evaluates the Chebyshev T polynomial.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N X Exact F U(N)(X)\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, n, x, fx ] = cheby_u_poly_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fx2 = cheby_u_poly ( 1, n, x );\n\n fprintf ( 1, ' %6d %8f %12f %12f\\n', n, x, fx, fx2(n+1) );\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/cheby_u_poly_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.6880751733133066}} {"text": "clear;\nclc;\nclose all;\n\nA = [1 1 1 1; 2 5 7 8]';\nB = [1 2 3 3]';\n\nX = inv((A'*A))*A'*B\n\nX = pinv(A)*B\n\n[U,S,V] = svd(A);\nPINV_A = V*pinv(S)*U';\nX = PINV_A*B\n\nX = U*U'*B\n\n\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/study/linear_algebra/pseudoinverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6880247453654309}} {"text": "function [imgOut,SH] = DiffuseConvolutionSH(img, falloff)\n%\n%\n% [imgOut,SH]=DiffuseConvolutionSH(img,falloff)\n%\n%\n% Input:\n% -img: an environment map in the latitude-longitude mapping\n% -falloff: a flag. If it is set 1, it means that fall-off will\n% be taken into account\n%\n% Output:\n% -imgOut: a diffuse convolved version of img\n% -SH: a [3,9] vector where spherical harmonics for img are\n% encoded\n%\n% Copyright (C) 2011 Francesco Banterle\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%\n\nif(~exist('falloff', 'var'))\n falloff = 0;\nend\n\n%falloff compensation\nif(falloff)\n img = FallOffEnvMap(img);\nend\n\n[r,c,col]=size(img);\n\nSH = zeros(col, 9);\n\n%projection constants\ny00 = 0.282095;\ny1x = 0.488603;\ny2x = 1.092548;\ny20 = 0.315392;\ny22 = 0.546274;\n\n%generation of directions\n\n[X,Y] = meshgrid(1:c, 1:r);\nphi = pi * 2 * (X / c);\ntheta = pi * (Y / r);\nsinTheta = sin(theta);\n\nDx = cos(phi) .* sinTheta;\nDy = cos(theta);\nDz = sin(phi) .* sinTheta;\n\nfor i=1:col\n img(:,:,i) = img(:,:,i) .* sinTheta;\nend\n\n%Environment projection on SH\nfor i=1:col\n %SH 0 \n SH(i,1) = mean(mean(img(:,:,i) .* y00));\n %SH 1 -1 y\n SH(i,2) = mean(mean(img(:,:,i) .* Dy * y1x));\n %SH 1 0 z\n SH(i,3) = mean(mean(img(:,:,i) .* Dz * y1x));\n %SH 1 1 x\n SH(i,4) = mean(mean(img(:,:,i) .* Dx * y1x));\n %SH 2 -2 xy\n SH(i,5) = mean(mean(img(:,:,i) .* Dx .* Dy * y2x));\n %SH 2 -1 yz\n SH(i,6) = mean(mean(img(:,:,i) .* Dy .* Dz * y2x));\n %SH 2 1 xz\n SH(i,7) = mean(mean(img(:,:,i) .* Dx .* Dz * y2x));\n %SH 2 0 3z^2-1 \n SH(i,8) = mean(mean(img(:,:,i) .* (3 * (Dz.^2) - 1) * y20));\n %SH 2 2 x^2-y^2\n SH(i,9) = mean(mean(img(:,:,i) .* (Dx.^2 - Dy.^2) * y22)); \nend\n\n%scaling\nSH = SH * pi * pi * 2;\n\n%convolution\nimgOut = EvaluationSH(SH, Dx, Dy, Dz);\n\nend", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/IBL/DiffuseConvolutionSH.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802373309982, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6880218064281092}} {"text": "function [psnr,ssim_val]=compute_psnr(im1,im2,shave_border)\nif size(im1, 3) == 3,\n im1 = rgb2ycbcr(im1);\n im1 = im1(:, :, 1);\nend\n\nif size(im2, 3) == 3,\n im2 = rgb2ycbcr(im2);\n im2 = im2(:, :, 1);\nend\n\nimdff = double(im1) - double(im2);\nif shave_border > 0\n imdff = shave(imdff,[shave_border,shave_border]);\nend\nimdff = imdff(:);\nim1 = shave(im1,[shave_border,shave_border]);\nim2 = shave(im2,[shave_border,shave_border]);\nssim_val = ssim_index(im1,im2);\nrmse = sqrt(mean(imdff.^2));\npsnr = 20*log10(255/rmse);", "meta": {"author": "huangzehao", "repo": "caffe-vdsr", "sha": "5a839232d179c10736ed94e7142068b168b61cf6", "save_path": "github-repos/MATLAB/huangzehao-caffe-vdsr", "path": "github-repos/MATLAB/huangzehao-caffe-vdsr/caffe-vdsr-5a839232d179c10736ed94e7142068b168b61cf6/Test/utils/compute_psnr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6880170237943625}} {"text": "function [out] = naturallabel(n)\n% Returns a natural label `idv` of `n` carbons.\n% Assumes 1.1% C13\n%\n% USAGE:\n%\n% [out] = naturallabel(n)\n%\n% INPUT:\n% n: size of label\n%\n% OUTPUT:\n% out: natural label idv of n carbons\n\nif n <= 0\n out = 1;\n return;\nend\n\nout = zeros(2^n,1);\nfor i = 0:(2^n-1)\n t = dec2bin(i,n);\n c13 = sum(t-48); % subtract 48 for the '0' offset.\n c12 = n-c13;\n out(i+1) = .989^c12*.011^c13;\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/dataIntegration/fluxomics/naturallabel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6880170184097395}} {"text": "% This is material illustrating the methods from the book\n% Financial Modelling - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors: Joerg Kienitz\n% Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\nfunction [pathS1, pathS2] = MC_B_path(S0,r,d,sigmaB, sigmaBS,T,Z)\n%\n% Simulate a path within the Bachelier model model\n%\n% S0 spot price\n% K the strike price\n% r the riskless rate\n% d the dividend yield\n% sigma the volatility\n% T the maturity\n% NTime number of timesteps\n% NSim number of simulations\n\n\nNSim = size(Z,1);\nNTime = size(Z,2);\nDelta = T/NTime; % The discretisation step\n\nlnS1 = zeros(NSim,NTime+1); % init the logspot price path\nlnS1(:,1)=log(S0*exp(-d*T)); % adjust due to dividend yield\nS1 = zeros(NSim,NTime+1);\nS1(:,1) = S0;\n\n%dW = randn(NSim,NTime); % precompute all randoms\n\nfor i=1:NTime\n lnS1(:,i+1) = lnS1(:,i) + (r-d) * Delta + sigmaBS* sqrt(Delta)*Z(:,i);\n S1(:,i+1) = S1(:,i) + (r-d) * Delta + sigmaB * sqrt(Delta) * Z(:,i);\nend\n \npathS1 = exp(lnS1);\npathS2 = S1;\nclear dW;\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/37618-monte-carlo-simulation-and-derivatives-pricing/StandardMonteCarlo/MC_B_path.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6880170184097394}} {"text": "function ompspeedtest\n%OMPSPEEDTEST Test the speed of the OMP functions.\n% OMPSPEEDTEST invokes the three operation modes of OMP and compares\n% their speeds. The function automatically selects the number of signals\n% for the test based on the speed of the system.\n%\n% To run the test, type OMPSPEEDTEST from the Matlab prompt.\n%\n% See also OMPDEMO.\n\n\n% Ron Rubinstein\n% Computer Science Department\n% Technion, Haifa 32000 Israel\n% ronrubin@cs\n%\n% August 2009\n\n\n\n% random dictionary %\n\nn = 512;\nL = 1000;\nT = 8;\n\nD = randn(n,L);\nD = D*diag(1./sqrt(sum(D.*D))); % normalize the dictionary\n\n\n% select signal number according to computer speed %\n\nx = randn(n,20);\ntic; omp(D,x,[],T,'messages',-1); t=toc;\nsignum = ceil(20/(t/20)); % approximately 20 seconds of OMP-Cholesky\n\n\n% generate random signals %\n\nX = randn(n,signum);\n\n\n% run OMP %\n\nprintf('\\nRunning OMP-Cholesky...');\ntic; omp(D,X,[],T,'messages',4); t1=toc;\n\nprintf('\\nRunning Batch-OMP...');\ntic; omp(D,X,D'*D,T,'messages',1); t2=toc;\n\nprintf('\\nRunning Batch-OMP with D''*X specified...');\ntic; omp(D'*X,D'*D,T,'messages',1); t3=toc;\n\n\n% display summary %\n\nprintf('\\n\\nSpeed summary for %d signals, dictionary size %d x %d:\\n', signum, n, L);\nprintf('Call syntax Algorithm Total time');\nprintf('--------------------------------------------------------');\nprintf('OMP(D,X,[],T) OMP-Cholesky %5.2f seconds', t1);\nprintf('OMP(D,X,G,T) Batch-OMP %5.2f seconds', t2);\nprintf('OMP(DtX,G,T) Batch-OMP with D''*X %5.2f seconds\\n', t3);\n", "meta": {"author": "tiepvupsu", "repo": "DICTOL", "sha": "1a0361aa35c32d70525d06910d0e9b87997ff246", "save_path": "github-repos/MATLAB/tiepvupsu-DICTOL", "path": "github-repos/MATLAB/tiepvupsu-DICTOL/DICTOL-1a0361aa35c32d70525d06910d0e9b87997ff246/LCKSVD/OMPbox/ompspeedtest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.6879707153970885}} {"text": "function [CIJkcore,kn,peelorder,peellevel] = kcore_bu(CIJ,k)\n%KCORE_BU K-core\n%\n% [CIJkcore,kn,peelorder,peellevel] = kcore_bu(CIJ,k);\n%\n% The k-core is the largest subnetwork comprising nodes of degree at\n% least k. This function computes the k-core for a given binary\n% undirected connection matrix by recursively peeling off nodes with\n% degree lower than k, until no such nodes remain.\n%\n% input: CIJ, connection/adjacency matrix (binary, undirected)\n% k, level of k-core\n%\n% output: CIJkcore, connection matrix of the k-core. This matrix\n% only contains nodes of degree at least k.\n% kn, size of k-core\n% peelorder, indices in the order in which they were\n% peeled away during k-core decomposition\n% peellevel, corresponding level - nodes at the same\n% level were peeled away at the same time\n%\n% 'peelorder' and 'peellevel' are similar the the k-core sub-shells\n% described in Modha and Singh (2010).\n%\n% References: e.g. Hagmann et al. (2008) PLoS Biology\n%\n% Olaf Sporns, Indiana University, 2007/2008/2010/2012\n\n%#ok<*AGROW>\n\npeelorder = [];\npeellevel = [];\niter = 0;\n\nwhile 1 \n\n % get degrees of matrix\n [deg] = degrees_und(CIJ);\n\n % find nodes with degree 0));\n \n % if none found -> stop\n if (isempty(ff)) break; end; %#ok\n\n % peel away found nodes\n iter = iter+1;\n CIJ(ff,:) = 0;\n CIJ(:,ff) = 0;\n \n peelorder = [peelorder; ff']; \n peellevel = [peellevel; iter.*ones(1,length(ff))'];\n \nend;\n\nCIJkcore = CIJ;\nkn = sum(deg>0);\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/bct/kcore_bu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951025545425, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.6879707089958123}} {"text": "function runs = contiguous(A,varargin)\n% RUNS = CONTIGUOUS(A,NUM) returns the start and stop indices for contiguous \n% runs of the elements NUM within vector A. A and NUM can be vectors of \n% integers or characters. Output RUNS is a 2-column cell array where the ith \n% row of the first column contains the ith value from vector NUM and the ith \n% row of the second column contains a matrix of start and stop indices for runs \n% of the ith value from vector NUM. These matrices have the following form:\n% \n% [startRun1 stopRun1]\n% [startRun2 stopRun2]\n% [ ... ... ]\n% [startRunN stopRunN]\n%\n% Example: Find the runs of '0' and '2' in vector A, where\n% A = [0 0 0 1 1 2 2 2 0 2 2 1 0 0]; \n% \n% runs = contiguous(A,[0 2])\n% runs = \n% [0] [3x2 double]\n% [2] [2x2 double]\n%\n% The start/stop indices for the runs of '0' are given by runs{1,2}:\n%\n% 1 3\n% 9 9\n% 13 14\n%\n% RUNS = CONTIGUOUS(A) with only one input returns the start and stop\n% indices for runs of all unique elements contained in A.\n%\n% CONTIGUOUS is intended for use with vectors of integers or characters, and \n% is probably not appropriate for floating point values. You decide. \n%\n\nif prod(size(A)) ~= length(A),\n error('A must be a vector.')\nend\n\nif isempty(varargin),\n num = unique(A);\nelse\n num = varargin{1};\n if prod(size(num)) ~= length(num),\n error('NUM must be a scalar or vector.')\n end\nend\n\nfor numCount = 1:length(num),\n \n indexVect = find(A(:) == num(numCount));\n shiftVect = [indexVect(2:end);indexVect(end)];\n diffVect = shiftVect - indexVect;\n \n % The location of a non-one is the last element of the run:\n transitions = (find(diffVect ~= 1));\n \n runEnd = indexVect(transitions);\n runStart = [indexVect(1);indexVect(transitions(1:end-1)+1)];\n \n runs{numCount,1} = num(numCount);\n runs{numCount,2} = [runStart runEnd];\n \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/5658-contiguous-start-and-stop-indices-for-contiguous-runs/contiguous.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.6879707084081392}} {"text": "function [p,t,pfun,tfun] = fixmesh(p,t,pfun,tfun)\n\n%*****************************************************************************80\n%\n% FIXMESH: Ensure that triangular mesh data is consistent.\n%\n% [p,t,pfun,tfun] = fixmesh(p,t,pfun,tfun);\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; n21,n22,n23;\n% etc]\n% pfun : (Optional) NxK array of nodal function values. Each column in\n% PFUN corresponds to a dependent function, PFUN(:,1) = F1(P),\n% PFUN(:,2) = F2(P) etc, defined at the nodes.\n% tfun : (Optional) MxK array of triangle function values. Each column in\n% TFUN corresponds to a dependent function, TFUN(:,1) = F1(T),\n% TFUN(:,2) = F2(T) etc, defined on the triangles.\n%\n% The following checks are performed:\n%\n% 1. Nodes not refereneced in T are removed.\n% 2. Duplicate nodes are removed.\n% 3. Triangles are ordered counter-clockwise.\n% 4. Triangles with an area less than 1.0e-10*eps*norm(A,'inf')\n% are removed\n%\n% Author:\n%\n% Darren Engwirda\n%\n\nTOL = 1.0e-10;\n\nif (nargin<4)\n tfun = [];\n if (nargin<3)\n pfun = [];\n if nargin<2\n error('Wrong number of inputs');\n end\n end\nelseif (nargin>4)\n error('Wrong number of inputs');\nend\nif (nargout>4)\n error('Wrong number of outputs');\nend\nif (numel(p)~=2*size(p,1))\n error('P must be an Nx2 array');\nend\nif (numel(t)~=3*size(t,1))\n error('T must be an Mx3 array');\nend\nif (any(t(:))<1) || (max(t(:))>size(p,1))\n error('Invalid T');\nend\nif ~isempty(pfun)\n if (size(pfun,1)~=size(p,1)) || (ndims(pfun)~=2)\n error('PFUN must be an NxK array');\n end\nend\nif ~isempty(tfun)\n if (size(tfun,1)~=size(t,1)) || (ndims(tfun)~=2)\n error('TFUN must be an Mxk array');\n end\nend\n\n% Remove duplicate nodes\n[i,i,j] = unique(p,'rows');\nif ~isempty(pfun)\n pfun = pfun(i,:);\nend\np = p(i,:);\nt = reshape(j(t),size(t));\n\n% Triangle area\nA = triarea(p,t);\nAi = A<0.0;\nAj = abs(A)>TOL*norm(A,'inf');\n\n% Flip node numbering to give a counter-clockwise order\nt(Ai,[1,2]) = t(Ai,[2,1]);\n\n% Remove zero area triangles\nt = t(Aj,:);\nif ~isempty(tfun)\n tfun = tfun(Aj,:);\nend\n\n% Remove un-used nodes\n[i,j,j] = unique(t(:));\nif ~isempty(pfun)\n pfun = pfun(i,:);\nend\np = p(i,:);\nt = reshape(j,size(t));\n\nend % fixmesh()\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/meshfaces/fixmesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024554, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.6879706912296017}} {"text": "function [mod_res_apx exp_res_apx]=exp_approx2(dboun, exp_par1, exp_par2,show_res)\nnexp=size(exp_par1,1);\nexp_res_apx=zeros(nexp,3);\nmod_res_apx=zeros(nexp,3);\n\nfor i=1:nexp\n dind=(dboun(i,1):dboun(i,2));\n \n Y=(exp_par1(i,1).^dind*exp_par1(i,2)-exp_par2(i,1).^dind*exp_par2(i,2))';\n p1=exp_par1(i,1);\n p2=exp_par2(i,1);\n sr_a=p1/(1-p1^2)/(p1-p2)/(1-p1*p2);\n sr_b=p2/(1-p2^2)/(p2-p1)/(1-p1*p2);\n H=[sr_a*p1.^dind'+sr_b*p2.^dind'];\n \n N_est=inv(H'*H)*H'*Y;\n \n exp_res_apx(i,:)=[p1,p2,sqrt(N_est)];\n mod_res_apx(i,:)=[p1+p2,-p1*p2,sqrt(N_est)];\nend\n\n\nif (show_res==1)\n for i=1:nexp\n dind=0:dboun(i,2);\n val_a=exp_par1(i,1).^dind*exp_par1(i,2);\n val_b=exp_par2(i,1).^dind*exp_par2(i,2);\n p1=exp_res_apx(i,1);\n p2=exp_res_apx(i,2);\n N=exp_res_apx(i,3)^2;\n sr_a=N*p1/(1-p1^2)/(p1-p2)/(1-p1*p2);\n sr_b=N*p2/(1-p2^2)/(p2-p1)/(1-p1*p2);\n val_c=sr_a*p1.^dind'+sr_b*p2.^dind';\n figure;\n plot(dind,val_a-val_b);grid;\n hold on\n plot(dind,val_c,'r');\n end\nend", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/IMUModeling/exp_approx2_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6879479661657061}} {"text": "function [ AF ] = AutoCorrelationF( X,m )\nAF=zeros(m,1);\n\nfor i=1:length(AF)\nX1=X(1:end-i);\nX1=X1-mean(X1);\n \nX2=X(i+1:end);\nX2=X2-mean(X2);\nAF(i)=mean(X1.*X2)/sqrt((var(X1)*var(X2)));\nend\n\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/43172-auto-correlation-partial-auto-correlation-cross-correlation-and-partial-cross-correlation-function/AutoCorrelationF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6879479632724174}} {"text": "function j = computecost(x, Y, Theta)\n\nn = length(Y); % Number of training examples.\n \nj = 0;\n\nj = (1 / (2 * n)) * sum(((x * Theta) - Y).^2); \n\nend", "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/machine_learning/Linear-Regression/computecost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6879479628129008}} {"text": "function [dists, wh] = canlab_fast_euclidean_distance(X, C, varargin)\n% dists = canlab_fast_euclidean_distance(X, C)\n%\n% X = obs x variables (dimensions, n) for Set 1\n% C = obs x variables (dimensions, n) for Set 2\n%\n% dists\n%\n% Adapted (largely just borrowed) from:\n%%=========================================================\n% Fast Euclidean Distance Calculation\n%\n% This script demonstrates the use of matrix multiplication to quickly\n% calculate the Euclidean distance between a large number of vectors.\n%\n% $Author: ChrisMcCormick $ $Date: 2014/08/22 22:00:00 $ $Revision: 1.0 $\n%\n% NOTE: (Tor): \n% Dot product is SLOWER if n < 6, but gets dramatically faster\n% with n = 6 or more. But in some tests it is about equally fast...\n% Matrix with fewer observations should be C when using loop (sum sq diffs)\n% approach.\n%\n%%=========================================================\n%\n% Optional arguments:\n%\n% 'tracktime' Track and report time using both matrix and SSD method\n% 'target_distance' Distance that counts as \"close enough\"\n% 'squared_distance' Distance returned is squared - saves computation time\n% Also assumes that target_distance is squared\n\ndotracktime = true;\ndosqrt = true; % save more time by comparing squares to squared dist target\n% don't do final sqrt if false, return squared distance\n\n[m, n] = size(X);\nk = size(C, 1);\n\n%% Sum-of-squared-differences approach\n%%=========================================================\n\nif dotracktime\n % Measure the time.\n tic();\nend\n\n% Create a matrix to hold the distances between each data point and\n% each model.\ndists = zeros(m, k);\n\n% For each model...\nfor (i = 1 : k)\n \n % Subtract model i from all data points.\n diffs = bsxfun(@minus, X, C(i, :));\n \n % Take the square root of the sum of squared differences.\n dists(:, i) = sqrt(sum(diffs.^2, 2));\nend\n\nif dotracktime\n elapsed = toc();\n fprintf('Sum-of-squared-differences took %.3f seconds.\\n', elapsed);\n if (exist('OCTAVE_VERSION')) fflush(stdout); end\n \n dists1 = dists;\n \nend\n\n\n\n%%=========================================================\n%% Matrix-multiply approach\n%%=========================================================\n\nif dotracktime\n tic();\nend\n\n% Calculate the sum of squares for all input vectors and\n% for all cluster centers / models.\n%\n% Matrix dimensions:\n% X [m x n]\n% XX [m x 1]\n% C [k x n]\n% CC [1 x k]\nXX = sum(X.^2, 2);\nCC = sum(C.^2, 2)';\n\n% Calculate the dot product between each input vector and\n% each cluster center / model.\n%\n% Matrix dimensions:\n% X [m x n]\n% C [k x n]\n% C' [n x k]\n% XC [m x k]\nXC = X * C';\n\n% Calculate the Euclidean distance between all input vectors in X\n% and all clusters / models in C using the following equation:\n%\n% z = sqrt(||x||^2 - 2xc' + ||c||^2)\n%\n% Step 1: Subtract the column vector XX from every column of XC.\n% Step 2: Add the row vector CC to every row of XC.\n%\n% Matrix dimensions:\n% XX [m x 1]\n% XC [m x k]\n% CC [1 x k]\n% dists [m x k]\n%\ndists = sqrt(bsxfun(@plus, CC, bsxfun(@minus, XX, 2*XC)));\n\nif dotracktime\n \n elapsed = toc();\n fprintf('Dot-product took %.3f seconds.\\n', elapsed);\n \n \n dists2 = dists;\n \n % Make sure the resulting distances are nearly identical.\n fprintf('Difference in result: %f\\n', sum(abs(dists1(:) - dists2(:))));\n if (exist('OCTAVE_VERSION')) fflush(stdout); end\n \n \nend\n\nend % function\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/canlab_fast_euclidean_distance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.6879395983542393}} {"text": "function p = high_card_fun ( m, n )\n\n%*****************************************************************************80\n%\n%% HIGH_CARD_FUN estimates the value of breaking the deck at location K.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 May 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of cards in the deck.\n%\n% Input, integer N, the number of trials.\n%\n% Output, real P(M), the estimated probability of picking the correct\n% high card by discarding so many cards and taking the next card that\n% is higher.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HIGH_CARD_FUN\\n' );\n fprintf ( 1, ' Using N=%d cards and T=%d trials,\\n', m, n );\n fprintf ( 1, ' estimate the chances of correctly picking the highest card\\n' );\n fprintf ( 1, ' by looking at cards 0 through K-1, and then taking the first\\n' );\n fprintf ( 1, ' subsequent card that is bigger.\\n' );\n\n p = zeros ( m, 1 );\n\n parfor i = 1 : m\n\n p(i) = high_card_simulation ( m, n, i - 1 );\n\n end\n\n return\nend\nfunction p = high_card_simulation ( deck_size, trial_num, skip_num )\n\n%*****************************************************************************80\n%\n%% HIGH_CARD_SIMULATION simulates a game of choosing the highest card in a deck.\n%\n% Discussion:\n%\n% You are given a deck of DECK_SIZE cards.\n%\n% Your goal is to select the high card. For convenience, we can assume \n% the cards are a permutation of the integers from 1 to DECK_SIZE, but in\n% fact the user mustn't see such values or else it's obvious which is the\n% largest card.\n%\n% However, your choice is made under the following rules: You may turn over\n% one card at a time. When a card is turned over, you may declare that to be\n% your choice, or else turn over another card. If you have not chosen a card\n% by the end, then your choice is the final card.\n%\n% If you have no idea what to do, and simply decide in advance to pick\n% a card \"at random\", that is, for example, you decide to pick the 15th card\n% before having seen any cards, then your probability of winning is 1/DECK_SIZE.\n%\n% The question is, can you do better than that?\n%\n% Your strategy is as follows: always look at the first SKIP_NUM cards without\n% choosing them. Then choose the very next card you encounter that is larger\n% than the cards you skipped.\n%\n% Using this program, you can easily see that skipping 5 cards is much better\n% than picking one at random, skipping 10 is even better, and so on. Of course,\n% you can't skip too many cards, and in fact, the results seem to be best for\n% somewhere around 30 to 35 cards skipped. For problems like this, the\n% optimal value is somewhere around 1 / e, where E is the base of the natural\n% logarithm system.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DECK_SIZE, the number of cards in the deck.\n% 2 <= DECK_SIZE. Default value is 52;\n%\n% Input, integer TRIAL_NUM, the number of times we will simulate this process.\n% Default value is 100.\n%\n% Input, integer SKIP_NUM, the number of initial cards you plan to examine\n% but will NOT select. If SKIP_NUM is 0, you don't look at any cards first.\n% 0 <= SKIP_NUM < DECK_SIZE. Default value is DECK_SIZE/3.\n%\n% Output, real P, the estimated probability that your strategy of skipping\n% SKIP_NUM cards and then selecting the next card that is bigger, will\n% result in choosing the highest card.\n%\n if ( nargin < 3 )\n trial_num = 100;\n end\n\n if ( nargin < 2 )\n skip_num = deck_size / 3;\n end\n\n if ( nargin < 1 )\n deck_size = 52;\n end\n%\n% Make sure we got integers.\n%\n deck_size = floor ( deck_size );\n skip_num = floor ( skip_num );\n trial_num = floor ( trial_num );\n%\n% Check values.\n%\n if ( deck_size < 2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HIGH_CARD_SIMULATION - Fatal error!\\n' );\n fprintf ( 1, ' DECK_SIZE must be at least 2.\\n' );\n fprintf ( 1, ' Your value was %d\\n', deck_size );\n error ( 'HIGH_CARD_SIMULATION - Fatal error!' );\n end\n\n if ( skip_num < 0 )\n skip_num = 0;\n end\n\n if ( deck_size <= skip_num )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HIGH_CARD_SIMULATION - Fatal error!\\n' );\n fprintf ( 1, ' SKIP_NUM must be less than DECK_SIZE.\\n' );\n fprintf ( 1, ' Your values were DECK_SIZE = %d, SKIP_NUM = %d\\n', deck_size, skip_num );\n error ( 'HIGH_CARD_SIMULATION - Fatal error!' );\n end\n\n if ( trial_num < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HIGH_CARD_SIMULATION - Fatal error!\\n' );\n fprintf ( 1, ' TRIAL_NUM must be at least 1.\\n' );\n fprintf ( 1, ' Your value was %d\\n', trial_num );\n error ( 'HIGH_CARD_SIMULATION - Fatal error!' );\n end\n\n correct = 0;\n\n for trial = 1 : trial_num\n\n cards = permutation_random ( deck_size );\n\n if ( 1 <= skip_num )\n skip_max = max ( cards(1:skip_num) );\n else\n skip_max = -Inf;\n end\n\n true_max = max ( cards(1:deck_size) );\n%\n% In case you don't encounter a card larger than SKIP_MAX,\n% we'll assume you pick the last card in the deck, even though\n% you know it's a loser.\n%\n choice = cards(deck_size);\n%\n% Turn over the remaining cards in the deck, but stop\n% immediately when you find one bigger than SKIP_MAX.\n%\n for card = skip_num + 1 : deck_size\n if ( skip_max < cards(card) )\n choice = cards(card);\n break;\n end\n end\n%\n% Record successful choices.\n%\n if ( choice == true_max )\n correct = correct + 1;\n end\n\n end\n%\n% Estimate the probability.\n%\n p = correct / trial_num;\n\n return\nend\nfunction p = permutation_random ( n )\n\n%*****************************************************************************80\n%\n%% PERMUTATION_RANDOM returns a random permutation.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of objects to permute.\n%\n% Output, integer P(N), a permutation of the integers from 1 to N.\n%\n p = ( 1 : n );\n\n for i = 1 : n - 1\n\n k = i4_random ( i, n );\n\n p1 = p(i);\n p(i) = p(k);\n p(k) = p1;\n\n end\n\n return\nend\nfunction value = i4_random ( lo, hi )\n\n%*****************************************************************************80\n%\n%% I4_RANDOM returns a random integer between LO and HI.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer LO, HI, the limits.\n%\n% Output, integer VALUE, the random integer.\n%\n r = ( hi + 1 - lo ) * rand ( );\n value = lo + floor ( 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/high_card_parfor/high_card_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321843145405, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.6879395918818596}} {"text": "function sin_degree_values_test ( )\n\n%*****************************************************************************80\n%\n%% SIN_DEGREE_VALUES_TEST demonstrates the use of SIN_DEGREE_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 January 2015\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SIN_DEGREE_VALUES_TEST:\\n' );\n fprintf ( 1, ' SIN_DEGREE_VALUES stores values of \\n' );\n fprintf ( 1, ' the sine function.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X FX\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, x, fx ] = sin_degree_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %12f %24.16f\\n', x, fx );\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/test_values/sin_degree_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.6879395893944471}} {"text": "classdef OnlineNaiveBayes < handle\n \n properties\n \n means;\n s_temp;\n std2s;\n counts;\n forward_bias;\n first;\n normpdf = @(x, mu, sigma)exp(-0.5 * ((x - mu)./sigma).^2) ./ (sqrt(2*pi) .* sigma);\n \n end\n \n methods\n \n function a = OnlineNaiveBayes(forward_bias)\n %Naive Bayes with a forward bias for online learning.\n %forward_bias = 0 (default) is standard naive bayes.\n \n if (nargin < 1)\n forward_bias = 0;\n end\n a.forward_bias = forward_bias;\n a.counts = ones(1, 3) * 2;\n a.first = true;\n \n end\n \n function train(a, inputs, outputs)\n \n arrayfun(@(x)a.online_train(inputs(x, :), outputs(x)), 1:size(inputs, 1));\n \n end\n \n function online_train(a, input, output)\n \n if (a.first)\n features = size(input, 2);\n a.means = zeros(3, features);\n a.s_temp = ones(3, features);\n a.std2s = ones(3, features);\n a.first = false;\n end\n output = (output + 3) / 2;\n indices = [output; 3];\n input = repmat(input, 2, 1);\n a.counts(indices) = a.counts(indices) + 1;\n r_counts = repmat(a.counts(indices), size(input, 2), 1)';\n new_means = a.means(indices, :) + ...\n (1 + (a.forward_bias * (a.counts(3) > 5))) .* ...\n (input - a.means(indices, :)) ./ r_counts;\n a.s_temp(indices, :) = a.s_temp(indices, :) + abs((input - a.means(indices, :)) .* (input - new_means));\n a.std2s(indices, :) = sqrt(a.s_temp(indices, :) ./ (r_counts - 1));\n a.means(indices, :) = new_means;\n \n end\n \n function outputs = test(a, inputs)\n \n probs = cell2mat(arrayfun(@(x)prod(a.normpdf(inputs, ...\n repmat(a.means(x, :), size(inputs, 1), 1), ...\n repmat(a.std2s(x, :), size(inputs, 1), 1)), 2) ...\n * (a.counts(x) / a.counts(3)), 1:2, 'UniformOutput', false));\n [v i] = max(probs(:, 1:2), [], 2);\n outputs = (i * 2) - 3;\n \n end\n \n function margins = margins(a, inputs)\n \n probs = cell2mat(arrayfun(@(x)prod(a.normpdf(inputs, ...\n repmat(a.means(x, :), size(inputs, 1), 1), ...\n repmat(a.std2s(x, :), size(inputs, 1), 1)), 2) ...\n * (a.counts(x) / a.counts(3)), 1:2, 'UniformOutput', false));\n [v i] = max(probs(:, 1:2), [], 2);\n margins = ((i * 2) - 3) .* (v ./ sum(probs(:, 1:2), 2));\n \n end\n \n function inputs = generate(a, outputs)\n \n index = (outputs == -1) + 1;\n mean = a.means(index, :);\n std = a.std2s(index, :);\n inputs = normrnd(mean, std);\n \n end\n \n end\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/ensemble/boosting_toolbox/boosting_demo/OnlineNaiveBayes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6878981951735383}} {"text": "function [W,D,E] = cubic_winding_number(C,V,ispoly)\n % CUBIC_WINDING_NUMBER Cubic the winding number of points in V with respect to\n % a cubic Bezier curve in C\n %\n % [W,D,E] = cubic_winding_number(C,V)\n %\n % Inputs:\n % C 4 by 2 list of control points\n % V #V by 2 list of query points\n % Outputs:\n % W #V list of winding number values\n % D #V list of max-depths of recursive algorithm \n % E #V list of total evaluations of recursive algorithm\n % \n\n function I = inpolygon_convex(V,C);\n %I = inpolygon(V(:,1),V(:,2),C(:,1),C(:,2));\n %I = abs(winding_number(C,[1:size(C,1);2:size(C,1) 1]',V))>0.5;\n %% Geez, this is barely faster than winding_number\n %Nx = C([2:end 1],2)-C(:,2);\n %Ny = C(:,1)-C([2:end 1],1);\n %S = (V(:,1)-C(:,1)').*Nx' + (V(:,2)-C(:,2)').*Ny';\n %I = all(S<0,2);\n % Oh, matlab, why:\n I = all(((V(:,1)-C(:,1)').*(C([2:end 1],2)-C(:,2))' + (V(:,2)-C(:,2)').*(C(:,1)-C([2:end 1],1))')<0,2);\n end\n\n if nargin<3 || isempty(ispoly)\n ispoly = false;\n end\n\n max_depth = 40;\n W = zeros(size(V,1),1);\n D = zeros(size(V,1),1);\n E = zeros(size(V,1),1);\n k = 0;\n % \"queue\"\n Q = {{C,(1:size(V,1))',1}};\n while ~isempty(Q)\n % Pop off back: faster but uglier traversal for animation\n Qi = Q{end};\n Ci = Qi{1};\n Ji = Qi{2};\n depth = Qi{3};\n Q = Q(1:end-1);\n %% Pop off front: better looking traversal for animation, but slower\n %Qi = Q{1};\n %Ci = Qi{1};\n %Ji = Qi{2};\n %depth = Qi{3};\n %Q = Q(2:end);\n D(Ji) = max(D(Ji),depth);\n E(Ji) = E(Ji)+1;\n if depth >= max_depth\n %warning('spline_winding_number exceeded max depth (%d)\\n',max_depth);\n continue;\n end\n if size(Ci,1)<3\n I = false(numel(Ji),1);\n else\n H = convhull(Ci);\n I = inpolygon_convex(V(Ji,:),Ci(H(1:end-1),:));\n end\n Wi = winding_number(Ci,[size(Ci,1) 1],V(Ji(~I),:));\n W(Ji(~I)) = W(Ji(~I)) - Wi;\n %WW = zeros(size(W));\n %WW(Ji(~I)) = -Wi;\n %ss = [915 938];\n %surf( ...\n % reshape(V(:,1),ss), ...\n % reshape(V(:,2),ss), ...\n % reshape(0*V(:,2),ss), ...\n % 'CData', ...\n % reshape(WW,ss), fphong, 'EdgeColor', 'none');\n %hold on\n %[pe,p] = plot_cubic(C);\n %set(p,'Color',0.75*[1 1 1]);\n %arrayfun(@(p) set(p,'Color',1+0.5*(get(p,'Color')-1)),pe);\n %plot_cubic(Ci);\n %plot_edges(Ci,[1 4],':','LineWidth',2,'Color',0.4*[1 1 1]);\n %hold off;\n %view(2);\n %axis equal;\n %axis tight;\n %caxis([-1 1])\n %colormap((flipud(cbrewer('RdBu',45))))\n %set(gca,'YDir','reverse');\n %set(gcf,'color','w');\n %set(gca,'Visible','off','Position',[0 0 1 1]);\n %figpng(sprintf('cubic-winding_number-%02d.png',k));\n %k=k+1;\n\n Ki = Ji(I);\n if ~isempty(Ki)\n if ispoly\n s = ceil(size(Ci,1)/2);\n C1 = Ci(1:s,:);\n C2 = Ci(s:end,:);\n Q{end+1} = {C1,Ki,Qi{3}+1};\n Q{end+1} = {C2,Ki,Qi{3}+1};\n else\n [C1,C2] = cubic_split(Ci,0.5);\n Q{end+1} = {C1,Ki,Qi{3}+1};\n Q{end+1} = {C2,Ki,Qi{3}+1};\n end\n end\n end\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/cubic_winding_number.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6878981936727085}} {"text": "function a=ighmap(b)\n%IGHMAP Single-level inverse discrete 2-D multiwavelet transform.\n% IGHMAP performs a single-level 2-D multiwavelet reconstruction\n% using GHM multiwavelet with four multi-filters\n%\n% Y = IGHMAP(X) computes the original matrix from the approximation\n% coefficients matrix LL and details coefficients matrices \n% LH, HL, HH, obtained by a multiwavelet decomposition of the \n% original input matrix and puts the result in Y.\n%\n% The size of Y is the same as that of X which should be\n% a square matrix of size NxN where N is power of 2 since\n% X is de-vectorized by critical sampling preprocessing.\n% The postprocessing filter is of order 2 degree 1.\n% LL, LH, HL, and HH should have the size N/2xN/2.\n%\n% X should be arranged as [LL,LH;HL,HH].\n%\n% See also GHM, IGHM, GHMAP, GHMAP2, IGHMAP2, WAVEDEC2, WAVEINFO.\n\n% Auth: Dr. Bessam Z. Hassan\n% Last Revision: 27-Feb-2004.\n% Copyright 1995-2002 The MathWorks, Inc.\n% $Revision: 1.0 $\n\nif nargin == 0,\n\terror('Not enough input arguments.');\nend\nif isempty(b)\n a = [];\n return\nend\nH0=[3/(5*sqrt(2)),4/5;-1/20,-3/(10*sqrt(2))];\nH1=[3/(5*sqrt(2)),0;9/20,1/sqrt(2)];\nH2=[0,0;9/20,-3/(10*sqrt(2))];\nH3=[0,0;-1/20,0];\nG0=[-1/20,-3/(10*sqrt(2));1/(10*sqrt(2)),3/10];\nG1=[9/20,-1/sqrt(2);-9/(10*sqrt(2)),0];\nG2=[9/20,-3/(10*sqrt(2));9/(10*sqrt(2)),-3/10];\nG3=[-1/20,0;-1/(10*sqrt(2)),0];\n[N,M]=size(b);\nif N~=2^round(log(N)/log(2))\n error('size of the input should be power of 2');\nend\nif M~=N\n error('the input matrix must be square');\nend\nw=[H0,H1,H2,H3;G0,G1,G2,G3];\nfor i=1:N/4-1\n W(4*(i-1)+1:4*i,4*i-3:4*i+4)=w;\nend\nW=[W;[[H2,H3;G2,G3],zeros(4,N-8),[H0,H1;G0,G1]]];\np=[];X=[];\n\n% shuffle\n\nN=N/2;\nb1=b(1:N,1:N);b2=b(1:N,N+1:2*N);b3=b(N+1:2*N,1:N);b4=b(N+1:2*N,N+1:2*N);\nb1=b1';b2=b2';b3=b3';b4=b4';\nT(1:2:N,:)=b1(1:N/2,:);T(2:2:N,:)=b1(N/2+1:N,:);T=T';b1(1:2:N,:)=T(1:N/2,:);b1(2:2:N,:)=T(N/2+1:N,:);\nT(1:2:N,:)=b2(1:N/2,:);T(2:2:N,:)=b2(N/2+1:N,:);T=T';b2(1:2:N,:)=T(1:N/2,:);b2(2:2:N,:)=T(N/2+1:N,:);\nT(1:2:N,:)=b3(1:N/2,:);T(2:2:N,:)=b3(N/2+1:N,:);T=T';b3(1:2:N,:)=T(1:N/2,:);b3(2:2:N,:)=T(N/2+1:N,:);\nT(1:2:N,:)=b4(1:N/2,:);T(2:2:N,:)=b4(N/2+1:N,:);T=T';b4(1:2:N,:)=T(1:N/2,:);b4(2:2:N,:)=T(N/2+1:N,:);\nb=[b1,b2;b3,b4];\np=b';\n\n%column vector permutation\n\nii=0:4:2*N-1;jj=sort([ii+1,ii+2]);kk=sort([ii+3,ii+4]);\nz(jj,:)=p(1:N,:);z(kk,:)=p(N+1:2*N,:);\nN=N*2;\n\n%inverse column transform\n\nX=W'*z;\n\n%postprocess columns\n\naa(2:2:N,:)=X(2:2:N,:)/(sqrt(2)-1);\naa(1:2:N,:)=(X(1:2:N,:)-0.11086198019724*aa(2:2:N,:)-0.11086198019724*[zeros(1,N);aa(2:2:N-1,:)])/0.37361535735427;\np=aa';N=N/2;\n\n%row vector permutation\n\nii=0:4:2*N-1;jj=sort([ii+1,ii+2]);kk=sort([ii+3,ii+4]);z=[];\nz(jj,:)=p(1:N,:);z(kk,:)=p(N+1:2*N,:);\n\n%inverse row transform\n\nX=W'*z;N=N*2;\n\n%postprocess rows\n\na(2:2:N,:)=X(2:2:N,:)/(sqrt(2)-1);\na(1:2:N,:)=(X(1:2:N,:)-0.11086198019724*a(2:2:N,:)-0.11086198019724*[zeros(1,N);a(2:2:N-1,:)])/0.37361535735427;\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/11105-multiwavelet-tools/IGHMAP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6878981861876424}} {"text": "function channels = PW(N, beta)\nm = log2(N);\nchannels = zeros(N, 1);\nfor i = 0 : N - 1\n bin_seq = dec2bin(i, m);\n sum = 0;\n for j = 1 : m\n if bin_seq(j) == '1'\n sum = sum + beta^(m - j);\n end\n end\n channels(i + 1) = sum;\nend\nend", "meta": {"author": "YuYongRun", "repo": "PolarCodeDecodersInMatlab", "sha": "f1b512d10bf057e83f18685ea012d242bdaaf6ac", "save_path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab", "path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab/PolarCodeDecodersInMatlab-f1b512d10bf057e83f18685ea012d242bdaaf6ac/PolarFastSCL/PolarizaedChannelsPartialOrder/PW.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.6878818347160802}} {"text": "function out = gaussian_kernel(x,d1,d2,bandWidth)\n\n% taken from a reference on the web to generate a Gaussian kernal\nns = 1000; % resolution \nxs1 = linspace(0,bandWidth(1,1),ns+1); % spatial\nxs2 = linspace(0,bandWidth(1,2),ns+1); %range\nkfun1 = exp(-(xs1.^2)/(2*bandWidth(1,1)^2));\nkfun2 = exp(-(xs2.^2)/(2*bandWidth(1,2)^2));\nw1 = kfun1(1,1:size(d1)).*(round(d1/bandWidth(1,1)*ns)+1);\nw2=kfun2(1,1:size(d2)).*(round(d2/bandWidth(1,2)*ns)+1);\nw=w1+w2;\nw = w/sum(w); % normalise\nout = sum( bsxfun(@times, x, w ), 2 );\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u5272\u7b97\u6cd5/Mean-Shift-Algorithm-for-Image-Segmentation-master/gaussian_kernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6878818211062581}} {"text": "function signal = toneBurst(sample_freq, signal_freq, num_cycles, varargin)\n%TONEBURST Create an enveloped single frequency tone burst.\n%\n% DESCRIPTION:\n% toneBurst creates an enveloped single frequency tone burst for use\n% in ultrasound simulations. If an array is given for the optional\n% input 'SignalOffset', a matrix of tone bursts is created where each\n% row corresponds to a tone burst for particular value of the\n% 'SignalOffset'. If a value for the optional input 'SignalLength' is\n% given, the tone burst/s are zero padded to this length (in\n% samples).\n%\n% USAGE:\n% signal = toneBurst(sample_freq, signal_freq, num_cycles)\n% signal = toneBurst(sample_freq, signal_freq, num_cycles, ...)\n%\n% INPUTS:\n% sample_freq - sampling frequency [Hz]\n% signal_freq - frequency of the tone burst signal [Hz]\n% num_cycles - number of sinusoidal oscillations\n%\n% OPTIONAL INPUTS:\n% Optional 'string', value pairs that may be used to modify the\n% default computational settings.\n%\n% 'Envelope' - envelope used to taper the tone burst, can be set to \n% either 'Gaussian' (default) or 'Rectangular'\n% 'Plot' - Boolean controlling whether the created tone\n% burst is plotted\n% 'SignalLength' - signal length in number of samples, if longer\n% than the tone burst length, the signal is\n% appended with zeros.\n% 'SignalOffset' - signal offset before the tone burst starts in\n% number of samples\n%\n% OUTPUTS:\n% signal - created tone burst\n%\n% ABOUT:\n% author - Bradley Treeby\n% date - 4th December 2009\n% last update - 21st December 2011\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 gaussian\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% set usage defaults\nnum_req_input_variables = 3;\nenvelope = 'Gaussian';\nsignal_length = [];\nsignal_offset = 0;\nplot_signal = false;\n\n% replace with user defined values if provided\nif nargin < num_req_input_variables\n error('Incorrect number of inputs');\nelseif ~isempty(varargin)\n for input_index = 1:2:length(varargin)\n switch varargin{input_index}\n case 'Envelope'\n envelope = varargin{input_index + 1};\n case 'Plot'\n plot_signal = varargin{input_index + 1}; \n case 'SignalOffset'\n signal_offset = varargin{input_index + 1};\n signal_offset = round(signal_offset); % force integer\n case 'SignalLength'\n signal_length = varargin{input_index + 1};\n signal_length = round(signal_length); % force integer\n otherwise\n error('Unknown optional input');\n end\n end\nend\n\n% calculate the temporal spacing\ndt = 1/sample_freq;\n\n% create the tone burst\ntone_length = num_cycles/(signal_freq);\ntone_t = 0:dt:tone_length;\ntone_burst = sin(2*pi*signal_freq*tone_t);\ntone_index = round(signal_offset);\n\n% create the envelope\nswitch envelope\n case 'Gaussian'\n x_lim = 3;\n window_x = -x_lim:2*x_lim/(length(tone_burst)-1):x_lim;\n window = gaussian(window_x, 1, 0, 1);\n case 'Rectangular'\n window = ones(size(tone_burst));\n otherwise\n error(['Unknown envelope ' envelope]);\nend \n\n% apply the envelope\ntone_burst = tone_burst.*window;\n\n% force the ends to be zero by applying a second window\ntone_burst = tone_burst.*(getWin(length(tone_burst), 'Tukey', 'Param', 0.05).');\n\n% % calculate the expected FWHM in the frequency domain\n% t_var = tone_length/(2*x_lim);\n% w_var = 1/(4*pi^2*t_var);\n% fw = 2 * sqrt(2 * log(2) * w_var)\n\n% create the signal with the offset tone burst\nif isempty(signal_length)\n signal = zeros(length(tone_index), max(signal_offset(:)) + length(tone_burst));\nelse\n signal = zeros(length(tone_index), signal_length);\nend\nfor offset = 1:length(tone_index)\n signal(offset, tone_index(offset) + 1:tone_index(offset) + length(tone_burst)) = tone_burst;\nend\n\n% plot the signal if required\nif plot_signal\n \n % compute suitable axis scaling\n time_axis = (0:length(signal)-1)*dt;\n [t_sc, scale, prefix] = scaleSI(max(time_axis(:))); \n \n % create figure\n figure;\n if numel(signal_offset) == 1\n plot(time_axis*scale, signal, 'k-');\n else\n plot(time_axis*scale, signal + repmat(2*max(signal(:))*(1:length(signal_offset)).', 1, length(time_axis)), 'k-');\n end\n xlabel(['Time [' prefix 's]']);\n ylabel('Signal Amplitude');\n axis tight;\n\nend\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/K-wave/k-Wave/toneBurst.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6878632169968146}} {"text": "function precisions = precision_plot(positions, ground_truth, title, show)\n%PRECISION_PLOT\n% Calculates precision for a series of distance thresholds (percentage of\n% frames where the distance to the ground truth is within the threshold).\n% The results are shown in a new figure if SHOW is true.\n%\n% Accepts positions and ground truth as Nx2 matrices (for N frames), and\n% a title string.\n%\n% Joao F. Henriques, 2014\n% http://www.isr.uc.pt/~henriques/\n\n\t\n\tmax_threshold = 50; %used for graphs in the paper\n\t\n\t\n\tprecisions = zeros(max_threshold, 1);\n\t\n\tif size(positions,1) ~= size(ground_truth,1),\n% \t\tfprintf('%12s - Number of ground truth frames does not match number of tracked frames.\\n', title)\n\t\t\n\t\t%just ignore any extra frames, in either results or ground truth\n\t\tn = min(size(positions,1), size(ground_truth,1));\n\t\tpositions(n+1:end,:) = [];\n\t\tground_truth(n+1:end,:) = [];\n\tend\n\t\n\t%calculate distances to ground truth over all frames\n\tdistances = sqrt((positions(:,1) - ground_truth(:,1)).^2 + ...\n\t\t\t\t \t (positions(:,2) - ground_truth(:,2)).^2);\n\tdistances(isnan(distances)) = [];\n\n\t%compute precisions\n\tfor p = 1:max_threshold,\n\t\tprecisions(p) = nnz(distances <= p) / numel(distances);\n\tend\n\t\n\t%plot the precisions\n\tif show == 1,\n\t\tfigure('NumberTitle','off', 'Name',['Precisions - ' title])\n\t\tplot(precisions, 'k-', 'LineWidth',2)\n\t\txlabel('Threshold'), ylabel('Precision')\n\tend\n\t\nend\n\n", "meta": {"author": "thias15", "repo": "Context-Aware-CF-Tracking", "sha": "2b1198a24aea6420d28987f68622f50a2970ffac", "save_path": "github-repos/MATLAB/thias15-Context-Aware-CF-Tracking", "path": "github-repos/MATLAB/thias15-Context-Aware-CF-Tracking/Context-Aware-CF-Tracking-2b1198a24aea6420d28987f68622f50a2970ffac/MOSSE_CA/precision_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6877630541554679}} {"text": "function HTotal=spherAngUvCrossHessian(uv,systemType,Ms,Muv)\n%%SPHERANGUVCROSSHESSIAN Determine second partial derivative matrices of 3D\n% spherical angular components with respect to u-v direction\n% cosines.\n%\n%INPUTS: uv A 2XN or 3XN (if the third components of the unit vector) set\n% of direction [u;v;w] cosines values in 3D. If the third\n% component of the unit vector is omitted, it is assumed to be\n% positive.\n% systemType An optional parameter specifying the axes from which the\n% angles for the spherical coordinate system are measured in\n% radians. Possible vaues are\n% 0 (The default if omitted) Azimuth is measured counterclockwise\n% from the x-axis in the x-y plane. Elevation is measured up\n% from the x-y plane (towards the z-axis). This is consistent\n% with common spherical coordinate systems for specifying\n% longitude (azimuth) and geocentric latitude (elevation).\n% 1 Azimuth is measured counterclockwise from the z-axis in the\n% z-x plane. Elevation is measured up from the z-x plane\n% (towards the y-axis). This is consistent with some spherical\n% coordinate systems that use the z axis as the boresight\n% direction of the radar.\n% 2 This is the same as 0 except instead of being given\n% elevation, one desires the angle away from the z-axis, which\n% is (pi/2-elevation).\n% Ms,Muv If either the spherical coordinate system or the u-v coordinate\n% system is rotated compared to the global Cartesian coordinate\n% system, these optional 3X3 matrices provide the rotations. Ms\n% is a 3X3 matrix to go from the alignment of a global\n% Cartesian coordinate system to that in which the spherical\n% coordinates are computed. Similarly, Muv is a rotation matrix\n% to go from the alignment of a global Cartesian cordinate system\n% to that in which the u-v(-w) coordinates are computed. If\n% either of these in omitted or an empty matrix is passed, then\n% the missing one is replaced with the identity matrix.\n%\n%OUTPUTS: HTotal A 2X2X2XN matrix of second derivatives where\n% HTotal(:,:,i,j) is the Hessian matrix of the ith\n% component of [azimuth;elevation] evaluated at the jth\n% point in uv. The ordering of the second derivatives in the\n% i,jth Hessian matrix is [d/du^2, d/(dudv);\n% d/(dudv), d/dv^2]\n%\n%EXAMPLE:\n%Here, we verify that the Hessian matrix computed by this function is close\n%to the computed using forward differencing of the gradient.\n% systemType=0;\n% uv=[0.1;-0.2];\n% \n% H=spherAngUvCrossHessian(uv,systemType);\n% J=spherAngUvCrossGrad(uv,systemType);\n% epsVal=1e-8;\n% uv1=uv+[epsVal;0];\n% J1=spherAngUvCrossGrad(uv1,systemType);\n% dAz=(J1-J)/epsVal;\n% \n% uv1=uv+[0;epsVal];\n% J1=spherAngUvCrossGrad(uv1,systemType);\n% dEl=(J1-J)/epsVal;\n% \n% HNumDiff=zeros(2,2,2,1);\n% \n% %Derivatives of azimuth\n% HNumDiff(1,1,1)=dAz(1,1);%dAz/du^2\n% HNumDiff(1,2,1)=dAz(1,2);%dAz/(dudv)\n% HNumDiff(2,1,1)=HNumDiff(1,2,1);\n% HNumDiff(2,2,1)=dEl(1,2);%dAz/dv^2\n% \n% %Derivatives of elevation\n% HNumDiff(1,1,2)=dAz(2,1);%dEl/du^2\n% HNumDiff(1,2,2)=dAz(2,2);%dEl/(dudv)\n% HNumDiff(2,1,2)=HNumDiff(1,2,2);\n% HNumDiff(2,2,2)=dEl(2,2);%dEl/dv^2\n% \n% max(abs(HNumDiff(:)-H(:)))\n%One will see that the difference between the true Hessian and the Hessian\n%from numeric differentiation is on the order of 8e-7, which indicates good\n%agreement.\n%\n%June 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<4||isempty(Muv))\n Muv=eye(3,3);\nend\n\nif(nargin<3||isempty(Ms))\n Ms=eye(3,3);\nend\n\nif(nargin<2||isempty(systemType))\n systemType=0; \nend\n\nhasW=size(uv,1)>2;\nN=size(uv,2);\n\nM=Ms*Muv';\nm11=M(1,1);\nm12=M(1,2);\nm13=M(1,3);\nm21=M(2,1);\nm22=M(2,2);\nm23=M(2,3);\nm31=M(3,1);\nm32=M(3,2);\nm33=M(3,3);\n\nHTotal=zeros(2,2,2,N);\nfor curPoint=1:N\n if(hasW==false)\n uvwCur=[uv(:,curPoint);sqrt(1-uv(1,curPoint)^2-uv(2,curPoint)^2)];\n else\n uvwCur=uv(:,curPoint);\n end\n u=uvwCur(1);\n v=uvwCur(2);\n w=uvwCur(3);\n\n uvwCur=M*uvwCur;\n u1=uvwCur(1);\n v1=uvwCur(2);\n w1=uvwCur(3);\n\n %First derivatives\n du1du=m11-m13*u/w;\n du1dv=m12-m13*v/w;\n dv1du=m21-m23*u/w;\n dv1dv=m22-m23*v/w;\n dw1du=m31-m33*u/w;\n dw1dv=m32-m33*v/w;\n\n w3=w^3;\n %Second derivatives\n d2u1dudu=m13*(v^2-1)/w3;\n d2u1dudv=-m13*u*v/w3;\n d2u1dvdv=m13*(u^2-1)/w3;\n d2v1dudu=m23*(v^2-1)/w3;\n d2v1dudv=-m23*u*v/w3;\n d2v1dvdv=m23*(u^2-1)/w3;\n d2w1dudu=m33*(v^2-1)/w3;\n d2w1dudv=-m33*u*v/w3;\n d2w1dvdv=m33*(u^2-1)/w3;\n\n switch(systemType)\n case 0\n denom1=(u1^2+v1^2)^2;\n denom2=sqrt(1-w1^2)^3;\n\n dazdu2=(-2*u1*(2*du1du*dv1du*u1-du1du^2*v1+dv1du^2*v1)+(2*du1du*dv1du+d2v1dudu*u1-d2u1dudu*v1)*(u1^2+v1^2))/denom1;\n dazdudv=(d2v1dudv*u1^3+v1^2*(du1dv*dv1du+du1du*dv1dv-d2u1dudv*v1)-u1^2*(du1dv*dv1du+du1du*dv1dv+d2u1dudv*v1)+u1*v1*(2*du1du*du1dv-2*dv1du*dv1dv+d2v1dudv*v1))/denom1;\n dazdv2=(-2*u1*(2*du1dv*dv1dv*u1-du1dv^2*v1+dv1dv^2*v1)+(2*du1dv*dv1dv+d2v1dvdv*u1-d2u1dvdv*v1)*(u1^2+v1^2))/denom1;\n deldu2=(d2w1dudu+dw1du^2*w1-d2w1dudu*w1^2)/denom2;\n deldudv=(d2w1dudv+dw1du*dw1dv*w1-d2w1dudv*w1^2)/denom2;\n deldv2=(d2w1dvdv+dw1dv^2*w1-d2w1dvdv*w1^2)/denom2;\n\n%If there were no rotations, it would be:\n% u2v2=u^2+v^2;\n% dazdu2=(2*u*v)/u2v2^2;\n% dazdudv=(-u^2+v^2)/u2v2^2;\n% dazdv2=-((2*u*v)/u2v2^2);\n% deldu2=-((u^4+v^2-v^4)/(w*sqrt(u2v2))^3);\n% deldudv=-((u*v*(-1+2*u^2+2*v^2))/(w*sqrt(u2v2))^3);\n% deldv2=-((u^2-u^4+v^4)/(w*sqrt(u2v2))^3);\n case 1\n denom1=(u1^2+w1^2)^2;\n denom2=sqrt(1-v1^2)^3;\n\n dazdu2=(2*u1*(2*du1du*dw1du*u1-du1du^2*w1+dw1du^2*w1)+(-2*du1du*dw1du-d2w1dudu*u1+d2u1dudu*w1)*(u1^2+w1^2))/denom1;\n dazdudv=(u1^2*(du1dv*dw1du+du1du*dw1dv-d2w1dudv*u1)+u1*(-2*du1du*du1dv+2*dw1du*dw1dv+d2u1dudv*u1)*w1-(du1dv*dw1du+du1du*dw1dv+d2w1dudv*u1)*w1^2+d2u1dudv*w1^3)/denom1;\n dazdv2=(2*u1*(2*du1dv*dw1dv*u1-du1dv^2*w1+dw1dv^2*w1)+(-2*du1dv*dw1dv-d2w1dvdv*u1+d2u1dvdv*w1)*(u1^2+w1^2))/denom1;\n deldu2=(d2v1dudu+dv1du^2*v1-d2v1dudu*v1^2)/denom2;\n deldudv=(d2v1dudv+dv1du*dv1dv*v1-d2v1dudv*v1^2)/denom2;\n deldv2=(d2v1dvdv+dv1dv^2*v1-d2v1dvdv*v1^2)/denom2;\n\n%If there were no rotations, it would be:\n% dazdu2=u/w^3;\n% dazdudv=v/w^3;\n% dazdv2=-((u*(-1+u^2+(-1+u^2)*v^2+2*v^4))/(w^3*(-1+v^2)^2));\n% deldu2=0;\n% deldudv=0;\n% deldv2=v/(1-v^2)^(3/2);\n case 2\n denom1=(u1^2+v1^2)^2;\n denom2=sqrt(1-w1^2)^3;\n\n dazdu2=(-2*u1*(2*du1du*dv1du*u1-du1du^2*v1+dv1du^2*v1)+(2*du1du*dv1du+d2v1dudu*u1-d2u1dudu*v1)*(u1^2+v1^2))/denom1;\n dazdudv=(d2v1dudv*u1^3+v1^2*(du1dv*dv1du+du1du*dv1dv-d2u1dudv*v1)-u1^2*(du1dv*dv1du+du1du*dv1dv+d2u1dudv*v1)+u1*v1*(2*du1du*du1dv-2*dv1du*dv1dv+d2v1dudv*v1))/denom1;\n dazdv2=(-2*u1*(2*du1dv*dv1dv*u1-du1dv^2*v1+dv1dv^2*v1)+(2*du1dv*dv1dv+d2v1dvdv*u1-d2u1dvdv*v1)*(u1^2+v1^2))/denom1;\n deldu2=(-dw1du^2*w1+d2w1dudu*(-1+w1^2))/denom2;\n deldudv=(-dw1du*dw1dv*w1+d2w1dudv*(-1+w1^2))/denom2;\n deldv2=(-dw1dv^2*w1+d2w1dvdv*(-1+w1^2))/denom2;\n\n%If there were no rotations, it would be:\n% u2v2=u^2+v^2;\n% dazdu2=(2*u*v)/u2v2^2;\n% dazdudv=(-u^2+v^2)/u2v2^2;\n% dazdv2=-((2*u*v)/u2v2^2);\n% deldu2=(u^4+v^2-v^4)/(w*sqrt(u2v2))^3;\n% deldudv=(u*v*(-1+2*u^2+2*v^2))/(w*sqrt(u2v2))^3;\n% deldv2=(u^2-u^4+v^4)/(w*sqrt(u2v2))^3;\n case 3\n denom1=(u1^2+v1^2)^2;\n denom2=sqrt(1-w1^2)^3;\n\n dazdu2=(2*u1*(2*du1du*dv1du*u1-du1du^2*v1+dv1du^2*v1)+(-2*du1du*dv1du-d2v1dudu*u1+d2u1dudu*v1)*(u1^2+v1^2))/denom1;\n dazdudv=(u1^2*(du1dv*dv1du+du1du*dv1dv-d2v1dudv*u1)+u1*(-2*du1du*du1dv+2*dv1du*dv1dv+d2u1dudv*u1)*v1-(du1dv*dv1du+du1du*dv1dv+d2v1dudv*u1)*v1^2+d2u1dudv*v1^3)/denom1;\n dazdv2=(2*u1*(2*du1dv*dv1dv*u1-du1dv^2*v1+dv1dv^2*v1)+(-2*du1dv*dv1dv-d2v1dvdv*u1+d2u1dvdv*v1)*(u1^2+v1^2))/denom1;\n deldu2=(d2w1dudu+dw1du^2*w1-d2w1dudu*w1^2)/denom2;\n deldudv=(d2w1dudv+dw1du*dw1dv*w1-d2w1dudv*w1^2)/denom2;\n deldv2=(d2w1dvdv+dw1dv^2*w1-d2w1dvdv*w1^2)/denom2;\n\n%If there were no rotations, it would be:\n% u2v2=u^2+v^2;\n% dazdu2=-(2*u*v)/u2v2^2;\n% dazdudv=(u-v)*(u+v)/u2v2^2;\n% dazdv2=(2*u*v)/u2v2^2;\n% deldu2=-((u^4+v^2-v^4)/(w*sqrt(u2v2))^3);\n% deldudv=-((u*v*(-1+2*u^2+2*v^2))/(w*sqrt(u2v2))^3);\n% deldv2=-((u^2-u^4+v^4)/(w*sqrt(u2v2))^3);\n otherwise\n error('Invalid system type specified.')\n end\n\n H=zeros(2,2,2);\n %Derivatives of azimuth\n H(1,1,1)=dazdu2;\n H(1,2,1)=dazdudv;\n H(2,1,1)=H(1,2,1);\n H(2,2,1)=dazdv2;\n %Derivatives of elevation\n H(1,1,2)=deldu2;\n H(1,2,2)=deldudv;\n H(2,1,2)=H(1,2,2);\n H(2,2,2)=deldv2;\n \n HTotal(:,:,:,curPoint)=H;\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/Coordinate_Systems/Hessians/Cross_Hessians/spherAngUvCrossHessian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.6877630446629799}} {"text": "function vr = rotateVector(v, angle)\n%ROTATEVECTOR Rotate a vector by a given angle.\n%\n% VR = rotateVector(V, THETA)\n% Rotate the vector V by an angle THETA, given in radians.\n%\n% Example\n% rotateVector([1 0], pi/2)\n% ans = \n% 0 1\n%\n% See also \n% vectors2d, transformVector, createRotation\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2011-04-14, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011-2022 INRA - Cepia Software Platform\n\n% precomputes angles\ncot = cos(angle);\nsit = sin(angle);\n\n% compute rotated coordinates\nvr = [cot * v(:,1) - sit * v(:,2) , sit * v(:,1) + cot * v(:,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/rotateVector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6877630319330493}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Solve the following exercises:\n% A) Exercise A: Use the Runge-Kutta 4 algorithm to integrate the\n% differential equation:\n% dy/dt = 2*t\n% Integrate from t0=0, to tfinal = 10 s.\n% Compare the solution with the algebraic integration.\n% B) Exercise B: Use the Runge-Kutta 4 algorithm to integrate the\n% second order differential equation:\n% d2y/dt^2+5*dy/dt + 4*y(t) = 0\n%\n% C) Exercise C: Use the Runge-Kutta 4 algorithm to simulate the movement\n% of a 1 dof robot arm with friction under the effect of gravity and with\n% zero torque applied.\n%\n% D) Exercise D: Use the Runge-Kutta 4 algorithm to simulate the movement\n% of a 2 dof robot arm with friction under the effect of gravity and with\n% zero torques applied.\n%\n% Help: Function prototype\n% [y, t] = runge_kutta(f, y0, [t0 tfinal], timestep)\n% where f is the function being integrated as dy/dt = f(t, y).\n% y0 are the initial conditions\n% t0: initial time\n% tfinal: final time.\n% h: time step for the calculations.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction runge_kutta_exercises()\nclose all;\n\n%uncomment to execute each of the exercises\n%exerciseA()\n%exerciseB()\n%exerciseC()\nexerciseD()\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Integrate a simple time function. dy/dt = 2*t\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction exerciseA()\nt0 = 0;\ntfinal = 10;\n% TODO: define the line function below.\n[t, y] = runge_kutta(@line, 0, [t0 tfinal], 0.1);\n\n%Compare with the integral of 2*t\n%error = y-t.^2';\n%mean(error)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Use Runge-Kutta to integrate a second order equation of the form.\n% d2y/dt^2+5*dy/dt + 4*y(t) = 0\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction exerciseB()\nt0 = 0;\ntfinal = 10;\n[t, y] = runge_kutta(@second_order_system, [10 1], [t0 tfinal], 0.1);\n\n%plot results\nplot(t, y)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Now use Runge-kutta to integrate the movement of a 1 dof robot arm\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction exerciseC()\n%these variables are shared by the forward_dynamic_robot1 function defined\n%below\nglobal robot tau g\nt0 = 0;\ntfinal = 10;\nrobot = load_robot('example','1dofplanar')\nrobot.dynamics.friction=0\ntau = [0];\ng = [0 -9.81 0]';\n[t, y] = runge_kutta(@forward_dynamic_robot1, [0 0]', [t0 tfinal], 0.01);\n\n% Animate the movement. Change speed from 1-30-100-200\nspeed = 10\nanimate(robot,[y(1,1:speed:length(y))])\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Now use Runge-Kutta to simulate the movement of a 2 DOF robot arm.\nfunction exerciseD()\nglobal robot tau g\nt0 = 0;\ntfinal = 10;\nrobot = load_robot('example','2dofplanar')\nrobot.dynamics.friction=1\ntau = [0 0];\ng = [0 -9.81 0]';\n[t, y] = runge_kutta(@forward_dynamic_robot2, [0 0 0 0]', [t0 tfinal], 0.001);\n%speed, change to 10, 30, 50, 100\nspeed = 50\nanimate(robot,[y(1,1:speed:length(y)); y(2,1:speed:length(y))])\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Helper function.\n% The function returns dy/dt = 2*t. Function called from exerciseA()\n%\n% Integrate a line in time. dy/dt = 2*t. Obviously, the integration should\n% yield. y(t) = t^2\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction dy = line(t, y)\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Helper function to solve a second order differential equation.\n% Called from function exerciseB()\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction xd = second_order_system(t, y)\n\nreturn\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Helper function to simulate the movement of a 1 DOF robot\n% Called from function exerciseC()\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction xd = forward_dynamic_robot1(t, y)\nglobal tau g robot\n\nqdd = accel(robot, y(1), y(2), tau, g);\n%return qd, qdd\nxd = [y(2); qdd];\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Helper function to simulate the movement of a 2 DOF robot\n% Called from function exerciseD()\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction xd = forward_dynamic_robot2(t, y)\nglobal tau g robot\n%we must return the solution of\n% [dx1/dt; dx2/dt]\nt\nqdd=forwarddynamics_2dofplanar(robot, y(1:2,1), y(3:4,1), tau', 9.81, [0 0 0 0 0 0]);\n%return qd, qdd\nxd = [y(3:4,1); qdd];\n\n\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/exercises/simulation/runge_kutta_exercises.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.687763025678003}} {"text": "function pass = test_pchip(pref)\n\n% Test a scalar function:\nx = 0:10; \ny = sin(x);\nf = chebfun.pchip(x, y);\ntol = 10*eps;\npass(1) = norm(feval(f, x) - y) < tol;\npass(2) = numel(f.funs) == 10;\npass(3) = length(f) == 40;\n\n% Test an array-valued function:\nx = (0:10)'; \ny = [sin(x), cos(x)];\nf = chebfun.pchip(x, y);\ntol = 10*eps;\npass(4) = norm(feval(f, x) - y) < tol;\npass(5) = numel(f.funs) == 10;\npass(6) = length(f) == 40;\n\n% Test a different domain:\ndom = [.01, 10.01];\nx = (0:10)'; \ny = [sin(x), cos(x)];\nf = chebfun.pchip(x, y, dom);\ntol = 10*eps;\npass(7) = all(f.domain == [dom(1), 1:10, dom(2)]);\npass(8) = norm(feval(f, x(2:end)) - y(2:end,:)) < tol;\npass(9) = numel(f.funs) == 11;\npass(10) = length(f) == 44;\n\n% Test the example from the m-file:\nx = -3:3;\ny = [-1 -1 -1 0 1 1 1];\nf = chebfun.pchip(x, y);\ntol = 10*eps;\npass(11) = norm(feval(f, x) - y) < tol;\npass(12) = numel(f.funs) == 6;\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/tests/chebfun/test_pchip.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6877630249865468}} {"text": "function [rad] = deg2rad(deg)\n%deg2rad Summary of this function goes here\n% Detailed explanation goes here\n rad=deg*(pi/180);\nend\n\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/math/deg2rad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.7853085758631158, "lm_q1q2_score": 0.6877630249865467}} {"text": "% [INPUT]\n% data = A float t-by-2 matrix (-Inf,Inf) representing the model input.\n% e = A float (0,2] representing the exponent of the euclidean distance used to calculate the Distance Correlation (optional, default=1).\n%\n% [OUTPUT]\n% dcor = A float [0,1] representing the Distance Correlation.\n% rmss = A float [0,1] representing the RMS Similarity.\n\nfunction [dcor,rmss] = similarity_statistics(varargin)\n\n persistent ip;\n\n if (isempty(ip))\n ip = inputParser();\n ip.addRequired('data',@(x)validateattributes(x,{'double'},{'real' 'finite' '2d' 'nonempty' 'size' [NaN 2]}));\n end\n\n ip.parse(varargin{:});\n\n ipr = ip.Results;\n data = validate_input(ipr.data);\n\n nargoutchk(2,2);\n\n [dcor,rmss] = similarity_statistics_internal(data);\n\nend\n\nfunction [dcor,rmss] = similarity_statistics_internal(data)\n\n x1 = data(:,1);\n x2 = data(:,2);\n\n dcor = calculate_dcor(x1,x2);\n rmss = calculate_rmss(x1,x2);\n\nend\n\nfunction dcor = calculate_dcor(x1,x2)\n\n d1 = sqrt(bsxfun(@minus,x1,x1.').^2);\n m1 = mean(d1,1);\n k1 = bsxfun(@minus,bsxfun(@minus,d1,m1.'),m1) + mean(mean(d1));\n\n d2 = sqrt(bsxfun(@minus,x2,x2.').^2);\n m2 = mean(d2,1);\n k2 = bsxfun(@minus,bsxfun(@minus,d2,m2.'),m2) + mean(mean(d2));\n\n v1 = sqrt(mean(mean(k1 .* k1)));\n v2 = sqrt(mean(mean(k2 .* k2)));\n v = sqrt(v1 * v2);\n\n dcov = sqrt(mean(mean(k1 .* k2)));\n\n if (v > 0)\n dcor = dcov / v;\n else\n dcor = 0;\n end\n\nend\n\nfunction rmss = calculate_rmss(x1,x2)\n\n s = 1 - (abs(x1 - x2) ./ (abs(x1) + abs(x2)));\n rmss = sqrt(mean(s.^2,'omitnan'));\n\nend\n\nfunction data = validate_input(data)\n\n t = size(data,1);\n\n if (t < 5)\n error('The value of ''data'' is invalid. Expected input to be a matrix with at least 5 rows.');\n end\n\nend\n", "meta": {"author": "TommasoBelluzzo", "repo": "SystemicRisk", "sha": "f5e9b4823eabab2130974e535d13762c0cb3e4bf", "save_path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk", "path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk/SystemicRisk-f5e9b4823eabab2130974e535d13762c0cb3e4bf/ScriptsModels/similarity_statistics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.6876684108926332}} {"text": "function indx = r8vec_indexed_heap_d ( n, a, indx )\n\n%*****************************************************************************80\n%\n%% R8VEC_INDEXED_HEAP_D creates a descending heap from an indexed R8VEC.\n%\n% Discussion:\n%\n% An R8VEC is a vector of R8's.\n%\n% An indexed R8VEC is an R8VEC of data values, and an R8VEC of N indices,\n% each referencing an entry of the data vector.\n%\n% The function adjusts the index vector INDX so that, for 1 <= J <= N/2,\n% we have:\n% A(INDX(2*J)) <= A(INDX(J))\n% and\n% A(INDX(2*J+1)) <= A(INDX(J))\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 August 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Albert Nijenhuis, Herbert Wilf,\n% Combinatorial Algorithms for Computers and Calculators,\n% Academic Press, 1978,\n% ISBN: 0-12-519260-6,\n% LC: QA164.N54.\n%\n% Parameters:\n%\n% Input, integer N, the size of the index array.\n%\n% Input, real A(*), the data vector.\n%\n% Input, integer INDX(N), the index array.\n% Each entry of INDX must be a valid index for the array A.\n%\n% Output, integer INDX(N), the indices have been reordered into a \n% descending heap.\n%\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 = indx(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 larger of the two values,\n% and update M if necessary.\n%\n if ( a(indx(m)) < a(indx(m+1)) )\n m = m + 1;\n end\n\n end\n%\n% If the large descendant is larger 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 ( a(indx(m)) <= a(key) )\n break\n end\n\n indx(ifree) = indx(m);\n ifree = m;\n\n end\n%\n% Once there is no more shifting to do, KEY moves into the free spot IFREE.\n%\n indx(ifree) = key;\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/r8lib/r8vec_indexed_heap_d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.6876684072853213}} {"text": "function b = subset_complement ( n, a )\n\n%*****************************************************************************80\n%\n%% SUBSET_COMPLEMENT computes the complement of a set.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 August 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Donald Kreher, Douglas Simpson,\n% Combinatorial Algorithms,\n% CRC Press, 1998,\n% ISBN: 0-8493-3988-X,\n% LC: QA164.K73.\n%\n% Parameters:\n%\n% Input, integer N, the order of the master set, of which A is\n% a subset. N must be positive.\n%\n% Input, integer A(N), a subset of the master set.\n% A(I) = 0 if the I-th element is in the subset A, and is\n% 1 otherwise.\n%\n% Output, integer B(N), the complement of A.\n%\n\n%\n% Check.\n%\n subset_check ( n, a );\n\n b(1:n) = 1 - a(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/combo/subset_complement.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.6876684030288432}} {"text": "%{\n Tests the Dantzig Selector\n\n min_x ||x||_1\ns.t.\n || D*A'*(A*x - b) || <= delta\n\nThe solvers solve a regularized version, using\n ||x||_1 + mu/2*||x-x_0||_2^2\n\nsee also test_sDantzig.m\n\nThis demo shows three formulations of the Dantzig selector\nInstead of calling a pre-built solver, we show how to call\ntfocs_SCD directly.\n\n%}\n\n% Before running this, please add the TFOCS base directory to your path\n\n% Try to load the problem from disk\nmu = 0;\nfileName = fullfile('reference_solutions','dantzig_problem1_smoothed_noisy');\nrandn('state',34324);\nrand('state',34324);\nN = 1024;\nM = round(N/2);\nK = round(M/5);\nA = randn(M,N);\nif exist([fileName,'.mat'],'file')\n load(fileName);\n fprintf('Loaded problem from %s\\n', fileName );\nelse\n disp('Please run test_sDantzig.m to setup the file');\nend\n\n\n[M,N] = size(A);\nK = nnz(x_original);\nnorm_x_ref = norm(x_ref);\nnorm_x_orig = norm(x_original);\ner_ref = @(x) norm(x-x_ref)/norm_x_ref;\ner_signal = @(x) norm(x-x_original)/norm_x_orig;\nresid = @(x) norm(A*x-b)/norm(b); % change if b is noisy\n\nfprintf('\\tA is %d x %d, original signal has %d nonzeros\\n', M, N, K );\nfprintf('\\tl1-norm solution and original signal differ by %.2e (mu = %.2e)\\n', ...\n norm(x_ref - x_original)/norm(x_original),mu );\n\n%% Call the TFOCS solver\ner = er_ref; % error with reference solution (from IPM)\nopts = [];\nopts.restart = 500;\nopts.errFcn = { @(f,dual,primal) er(primal), ...\n @(f,dual,primal) obj_ref - f }; \nopts.maxIts = 1000;\nopts.printEvery = 100;\nz0 = []; % we don't have a good guess for the dual\n\n\n%% Method 1: use the epigraph of the l_infinity norm as the cone\n% Note: this is equivalent to calling:\n% [ x, out, optsOut ] = solver_sDantzig( {A,D}, b, delta, mu, x0, z0, opts );\n\nDAtb = D.*(A'*b);\nDD = @(x) D.*(x);\nobjectiveF = prox_l1;\naffineF = {linop_matrix(diag(D)*(A'*A)), -DAtb };\ndualproxF = prox_l1( delta );\n[ x, out, opts ] = tfocs_SCD( objectiveF, affineF, dualproxF, mu, x0, z0, opts );\nx1 = x;\nout1 = out;\n\nfprintf('Solution has %d nonzeros. Error vs. IPM solution is %.2e\\n',...\n nnz(x), er(x) );\n\n% Check that we are within allowable bounds\nif out.err(end,1) < 1e-3\n disp('Everything is working');\nelse\n error('Failed the test');\nend\n%% Method 2: use the LP formulation\n% Instead of the constraint ||Ax-b||_infty <= delta\n% (where \"A\" is really DA'A),\n% think of it as\n% -(Ax-b) + delta >= 0\n% (Ax-b) + delta >= 0\n\nobjectiveF = prox_l1;\naffineF = {linop_matrix(-diag(D)*(A'*A)), DAtb + delta;...\n linop_matrix( diag(D)*(A'*A)), -DAtb + delta; };\n\ndualproxF = { proj_Rplus; proj_Rplus };\n[ x, out, opts ] = tfocs_SCD( objectiveF, affineF, dualproxF, mu, x0, z0, opts );\nx2 = x;\nout2 = out;\n\n% Check that we are within allowable bounds\nif out.err(end,1) < 1e-3\n disp('Everything is working');\nelse\n error('Failed the test');\nend\n%% Method 3: put objective into constraint\n% This is the trick we do with solver_sDantzig_W, to deal with ||Wx||_1\n% Instead of minimizing ||x||_1, we minimize t,\n% with the constraint that ||x||_1 <= t\n% This version has some scaling considerations -- if we \n% are careful about scaling, the dual problem will be solved much faster.\n\n% Note: we still have to deal with the original constraints. We\n% can use either method 1 or method 2 above. Here, we'll use\n% method 1.\n\n\nobjectiveF = []; % tfocs_SCD recognizes this special objective\nnormA2 = norm( diag(D)*A'*A )^2;\nscale = 1/sqrt(normA2);\naffineF = {linop_matrix(diag(D)*(A'*A)), -DAtb; linop_scale(1/scale), 0 };\ndualproxF = { prox_l1(delta); proj_linf(scale) };\n[ x, out, opts ] = tfocs_SCD( objectiveF, affineF, dualproxF, mu, x0, z0, opts );\nx3 = x;\nout3 = out;\n\n% Check that we are within allowable bounds\nif out.err(end,1) < 1e-2\n disp('Everything is working');\nelse\n error('Failed the test');\nend\n%% plot\nfigure;\nsemilogy( out1.err(:,1) );\nhold all\nsemilogy( out2.err(:,1) );\nsemilogy( out3.err(:,1) );\nlegend('Method 1 (epigraph cone)','Method 2 (LP)','Method 3 (W=I)' );\n\n%% close all plots\nclose all\n\n\n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/examples/smallscale/test_sDantzig_3methods.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.7931059438487662, "lm_q1q2_score": 0.6876512119036163}} {"text": "%% Copyright (C) 2014, 2016, 2019 Colin B. Macdonald\n%%\n%% This file is part of OctSymPy.\n%%\n%% OctSymPy is free software; you can redistribute it and/or modify\n%% it under the terms of the GNU General Public License as published\n%% by the Free Software Foundation; either version 3 of the License,\n%% or (at your option) any later version.\n%%\n%% This software is distributed in the hope that it will be useful,\n%% but WITHOUT ANY WARRANTY; without even the implied warranty\n%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See\n%% the GNU General Public License for more details.\n%%\n%% You should have received a copy of the GNU General Public\n%% License along with this software; see the file COPYING.\n%% If not, see .\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @defmethod @@sym laplacian (@var{f})\n%% @defmethodx @@sym laplacian (@var{f}, @var{x})\n%% Symbolic Laplacian of symbolic expression.\n%%\n%% The Laplacian of a scalar expression @var{f} is\n%% the scalar expression:\n%% @example\n%% @group\n%% syms f(x, y, z)\n%% laplacian(f)\n%% @result{} (sym)\n%% 2 2 2\n%% \u2202 \u2202 \u2202\n%% \u2500\u2500\u2500(f(x, y, z)) + \u2500\u2500\u2500(f(x, y, z)) + \u2500\u2500\u2500(f(x, y, z))\n%% 2 2 2\n%% \u2202x \u2202y \u2202z\n%% @end group\n%% @end example\n%%\n%% @var{x} can be a scalar, vector or cell list. If omitted,\n%% it is determined using @code{symvar}.\n%%\n%% Example:\n%% @example\n%% @group\n%% syms x y\n%% laplacian(x^3 + 5*y^2)\n%% @result{} (sym) 6\u22c5x + 10\n%% @end group\n%% @end example\n%%\n%% Note: assumes @var{x} is a Cartesian coordinate system.\n%%\n%% @seealso{@@sym/divergence, @@sym/gradient, @@sym/curl, @@sym/jacobian,\n%% @@sym/hessian}\n%% @end defmethod\n\n\nfunction g = laplacian(f,x)\n\n assert (isscalar(f), 'laplacian: only scalar functions supported')\n\n if (nargin == 1)\n x = symvar(f);\n if (isempty(x))\n x = sym('x');\n end\n elseif (nargin == 2)\n % no-op\n else\n print_usage ();\n end\n\n if (~iscell(x) && isscalar(x))\n x = {x};\n end\n\n cmd = { '(f, x) = _ins'\n 'g = 0'\n 'for y in x:'\n ' g = g + f.diff(y, 2)'\n 'return g,' };\n\n g = pycall_sympy__ (cmd, sym(f), x);\n\nend\n\n\n%!shared x,y,z\n%! syms x y z\n\n%!test\n%! % 1D\n%! f = x^2;\n%! g = diff(f,x,x);\n%! assert (isequal (laplacian(f), g))\n%! assert (isequal (laplacian(f,{x}), g))\n%! assert (isequal (laplacian(f,[x]), g))\n%! assert (isequal (laplacian(f,x), g))\n\n%!test\n%! % const\n%! f = sym(1);\n%! g = sym(0);\n%! assert (isequal (laplacian(f), g))\n%! assert (isequal (laplacian(f,x), g))\n%! f = sym('c');\n%! assert (isequal (laplacian(f,x), g))\n\n%!test\n%! % double const\n%! f = 1;\n%! g = sym(0);\n%! assert (isequal (laplacian(f,x), g))\n\n%!test\n%! % 1D fcn in 2d/3d\n%! f = sin(2*y);\n%! g = -4*f;\n%! assert (isequal (laplacian(f), g))\n%! assert (isequal (laplacian(f, {x,y}), g))\n%! assert (isequal (laplacian(f, {x,y,z}), g))\n\n%!test\n%! % 2d fcn in 2d/3d\n%! f = sin(exp(x)*y);\n%! g = diff(f,x,x) + diff(f,y,y);\n%! assert (isequal (laplacian(f), g))\n%! assert (isequal (laplacian(f, {x,y}), g))\n\n%!test\n%! % 2d fcn in 2d/3d\n%! f = sin(exp(x)*y+sinh(z));\n%! gr2 = gradient(f, {x,y});\n%! divgr2 = divergence(gr2, {x,y});\n%! l2 = laplacian(f,{x,y});\n%! gr3 = gradient(f, {x,y,z});\n%! divgr3 = divergence(gr3, {x,y,z});\n%! l3 = laplacian(f,{x,y,z});\n%! assert (isAlways (l2 == divgr2))\n%! assert (isAlways (l3 == divgr3))\n\n%!error laplacian(sym('x'), sym('x'), 42)\n%!error laplacian([sym('x'), sym('x')])\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/@sym/laplacian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6876512091787}} {"text": "function stroud_test02 ( )\n\n%*****************************************************************************80\n%\n%% TEST02 tests BALL_MONOMIAL_ND.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 06 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n n = 3;\n\n r = 2.0;\n xc(1:n) = [ 0.0, 0.0, 0.0 ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST02\\n' );\n fprintf ( 1, ' For the integral of a monomial in a ball in ND:\\n' );\n fprintf ( 1, ' BALL_MONOMIAL_ND approximates the integral.\\n' );\n fprintf ( 1, ' BALL_F1_ND, which can handle general integrands,\\n' );\n fprintf ( 1, ' will be used for comparison.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial dimension N = %d\\n', n );\n fprintf ( 1, ' Ball radius = %f\\n', r )\n fprintf ( 1, ' Ball volume = %f\\n', ball_volume_nd ( n, r ) );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Rule:\t MONOMIAL\t BALL_F1_ND\\n' );\n fprintf ( 1, ' F(X)\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : 4\n\n if ( i == 1 )\n string = '1';\n p = [ 0, 0, 0 ];\n result2 = ball_f1_nd ( 'mono_000_3d', n, xc, r );\n elseif ( i == 2 )\n string = 'xyz';\n p = [ 1, 1, 1 ];\n result2 = ball_f1_nd ( 'mono_111_3d', n, xc, r );\n elseif ( i == 3 )\n string = 'x^2z^2';\n p = [ 2, 0, 2 ];\n result2 = ball_f1_nd ( 'mono_202_3d', n, xc, r );\n elseif ( i == 4 )\n string = 'x^4y^2z^2';\n p = [ 4, 2, 2 ];\n result2 = ball_f1_nd ( 'mono_422_3d', n, xc, r );\n end\n\n result1 = ball_monomial_nd ( n, p, r );\n\n fprintf ( 1, ' %10s %14f %14f\\n', string, result1, result2 );\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/stroud/stroud_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.6876389658123837}} {"text": "% orientation filtering function(Eq.(9)in the paper)\nfunction K = angfilter(I,Theta,angle,sigma)\n\nb = angle;\nc = sigma;\n[m,n] = size(Theta);\n\nX = 0:180;\nf = (1/(sqrt(2*pi)*c))*exp(-(((X-b).^2)/(2*(c^2))));\n\nfor i=1:m \n for j=1:n\n T(i,j)=f(Theta(i,j));\n end\nend\n\nK = I.*T;\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/30253-blood-cells-tracking-and-measurement-by-using-spatiotemporal-images-analysis/BloodCellsTracking/angfilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.6876013121823704}} {"text": "function SDP = chordal_relax_mesh_registration(problem)\n%% Apply a chordal sparse second-order relaxation to mesh registration\n%% Generate SDP relaxations with multiple smaller blocks\n%% This relaxation is likely to be looser than the single block relaxation\n%% Depending on multivariate polynomial package SPOT\n%% Heng Yang, July 28, 2021\n\nfprintf('\\n===================================================================')\nfprintf('\\nApplying Chordal SDP relaxation to mesh registration')\nfprintf('\\n===================================================================\\n')\nt0 = tic;\n\n%% define POP variables\nN = problem.N;\nnormalM = problem.normalM;\nnormalP = problem.normalP;\npointM = problem.pointM;\npointP = problem.pointP;\npointNoiseBoundSq = problem.pointNoiseBoundSq;\nnormalNoiseBoundSq = problem.normalNoiseBoundSq;\ntBound = problem.translationBound;\ntBoundSq = tBound^2; % t'*t <= tBoundSq\nbarc2 = 1.0;\n\nnrPrimalVars = 9 + 3 + N;\np = msspoly('p',nrPrimalVars);\nr = p(1:9);\nR = reshape(r,3,3);\ncol1 = r(1:3);\ncol2 = r(4:6);\ncol3 = r(7:9);\nt = p(10:12);\ntheta = p(13:nrPrimalVars);\nx = [r;t];\n\n%% compute the cost function\nresiduals = [];\nfor i = 1:N\n pointM_i = pointM(:,i);\n pointP_i = pointP(:,i);\n normalM_i = normalM(:,i);\n normalP_i = normalP(:,i);\n residual_point_i = ( normalM_i' * (R*pointP_i - pointM_i + t) )^2;\n residual_normal_i = normalP_i'*normalP_i + normalM_i'*normalM_i - 2*normalP_i'*R'*normalM_i;\n residuals = [residuals;...\n (residual_point_i/pointNoiseBoundSq + residual_normal_i/normalNoiseBoundSq)/2];\nend\nf_cost = [];\nfor i = 1:N \n f_cost = [f_cost;(1+theta(i))/2 * residuals(i) + (1-theta(i))/2 * barc2];\nend\n\n%% Define the equality and inequality constraints\nh_x = [1.0-col1'*col1;...\n 1.0-col2'*col2;...\n 1.0-col3'*col3;... % columns unit length\n col1'*col2;...\n col2'*col3;...\n col3'*col1;... % colums orthogonal\n cross(col1,col2) - col3;...\n cross(col2,col3) - col1;...\n cross(col3,col1) - col2]; % columns righthandedness\n \nh_theta = [];\nfor i = 1:N \n h_theta =[h_theta; 1-theta(i)^2];\nend\n\ng_x = tBoundSq - t'*t; % Translation bounded\n\n%% Formulate the chordal sparse second-order relaxation\n%% the 0-th block [1;x] * [1;x]'\nbasis0 = [1;x];\nn0 = length(basis0);\nbasis_x0 = 1;\n\npop0 = [mykron(basis_x0,h_x);...\n mykron(basis0,basis0)];\n[~,degmat,coef_all] = decomp(pop0);\ncoef_all = coef_all';\ndim_loc0 = length(basis_x0) * length(h_x);\nn0delta = triangle_number(n0);\nnterms = size(degmat,1); \nm_mom0 = n0delta - nterms;\n\nassert(m_mom0==0,'The zero-th blk should have 0 moment constraints.')\n\ncoef_mom = coef_all(:,dim_loc0+1:end);\ncoef_mom = coef_mom';\nB = {};\nB_normalize = {};\n\nfor i = 1:nterms\n [row,~,~] = find(coef_mom(:,i));\n SDP_coli = floor((row-1)./n0) + 1;\n SDP_rowi = mod(row-1,n0) + 1;\n nnz = length(SDP_rowi);\n \n Bi = sparse(SDP_rowi,SDP_coli,ones(nnz,1),n0,n0);\n B{end+1} = Bi;\n B_normalize{end+1} = Bi/nnz;\nend\n\ncoef_loc0 = coef_all(:,1:dim_loc0);\nA0_local = {};\n\nfor i = 1:dim_loc0\n [rowi,~,vi] = find(coef_loc0(:,i));\n Ai = sparse(n0,n0);\n for j = 1:length(rowi)\n Ai = Ai + vi(j) * B_normalize{rowi(j)};\n end\n A0_local = [A0_local;{Ai}];\nend\nA0_0 = sparse([1],[1],[1],n0,n0);\n% The first block satisfies A0(X0) = b0;\nA0 = [{A0_0};A0_local];\nb0 = sparse(1,1,1,length(A0),1);\n\n%% the 1-N blocks [1;x;theta(i);theta(i)*x]' * [1;x;theta(i);theta(i)*x]\n%% Since there is an inequality constraint too, it will generate 2*N blocks\nAall = {};\nA1all = {};\nball = [];\nCall = {};\nA0append = {};\nfor blkidx = 1:N\n basis = [1;x;theta(blkidx);theta(blkidx)*x];\n n = length(basis);\n basis_x = monomials(theta(blkidx),1:2);\n basis_theta = monomials(x,0:2);\n basis_g = [1;theta(blkidx)];\n \n out = gen_chordal_subblk_pcr(...\n basis,basis_x,h_x,basis_theta,h_theta(blkidx),g_x,basis_g,f_cost(blkidx));\n Acell = out.A;\n A1 = out.A1;\n b = out.b;\n C = out.C;\n \n % add constraint that the top-left [1;x]*[1;x]' block is the same as\n % the 0-th block\n A0blk = {};\n for i = 1:n0\n for j = i:n0\n if i == j\n A0i = sparse(i,j,-1,n0,n0);\n Ai = sparse(i,j,1,n,n);\n else\n A0i = sparse([i,j],[j,i],[-0.5,-0.5],n0,n0);\n Ai = sparse([i,j],[j,i],[0.5,0.5],n,n);\n end\n A0blk = [A0blk;{A0i}];\n Acell = [Acell;{Ai}];\n end\n end\n \n ball = [ball;b;sparse(n0delta,1)];\n A0append{end+1} = A0blk;\n Aall{end+1} = Acell;\n Call = [Call;C];\n A1all{end+1} = A1;\nend\n\n%% Convert to standard SDPT3 format\nb = [b0;ball];\nblk = cell(2*N+1,2);\nblk{1,1} = 's'; blk{1,2} = n0;\nn1 = out.blk{2,2};\nn1delta = triangle_number(n1);\nfor i = 1:N\n blk{2*i,1} = 's';\n blk{2*i,2} = n;\n blk{2*i+1,1} = 's';\n blk{2*i+1,2} = n1;\nend\n\n\nA0t = sparsesvec(blk(1,:),A0);\nfor i = 1:N\n A0t = [A0t,...\n sparse(n0delta,out.m),...\n sparsesvec(blk(1,:),A0append{i})];\nend\nndelta = triangle_number(n);\nAt = {A0t};\nfor i = 1:N\n Ait = [sparse(ndelta,length(b0)),...\n sparse(ndelta,(i-1)*length(Aall{i})),...\n sparsesvec(blk(2*i,:),Aall{i}),...\n sparse(ndelta,(N-i)*length(Aall{i}))];\n \n A1it = [sparse(n1delta,length(b0)),...\n sparse(n1delta,(i-1)*length(Aall{i})),...\n sparse(n1delta,out.m_mom+out.m_loc),...\n sparsesvec(blk(2*i+1,:),A1all{i}),...\n sparse(n1delta,n0delta),...\n sparse(n1delta,(N-i)*length(Aall{i}))];\n At = [At;{Ait};{A1it}];\nend\n\nSDP.blk = blk;\nSDP.At = At;\nSDP.n = n;\nSDP.m = length(b);\nSDP.C = [{sparse(n0,n0)};Call];\nSDP.b = b;\n\ntf = toc(t0);\nfprintf('\\nDone in %g seconds.\\n',tf);\nfprintf('===================================================================\\n')\n\n%% Convert to sedumi\nfprintf('Convert to sedumi')\nt0 = tic;\n\nsK.s = [n0];\nfor i = 1:N\n sK.s = [sK.s,n,n1];\nend\n\nA0t = sparsevec(blk(1,:),A0);\nn0sq = n0^2;\nfor i = 1:N\n A0t = [A0t,...\n sparse(n0sq,out.m),...\n sparsevec(blk(1,:),A0append{i})];\nend\n\nnsq = n^2;\nn1sq = n1^2;\nAt = {A0t};\nfor i = 1:N\n Ait = [sparse(nsq,length(b0)),...\n sparse(nsq,(i-1)*length(Aall{i})),...\n sparsevec(blk(2*i,:),Aall{i}),...\n sparse(nsq,(N-i)*length(Aall{i}))];\n \n A1it = [sparse(n1sq,length(b0)),...\n sparse(n1sq,(i-1)*length(Aall{i})),...\n sparse(n1sq,out.m_mom+out.m_loc),...\n sparsevec(blk(2*i+1,:),A1all{i}),...\n sparse(n1sq,n0delta),...\n sparse(n1sq,(N-i)*length(Aall{i}))];\n At = [At;{Ait};{A1it}];\nend\n\nsdata.K = sK;\nsdata.At = cat(1,At{:});\nsdata.b = b;\n\nsc = [];\nfor i = 1:length(SDP.C)\n sc = [sc;sparsevec(blk(i,:),SDP.C(i))];\nend\nsdata.c = sc;\n\nSDP.sedumi = sdata;\n\ntf = toc(t0);\nfprintf('\\nDone in %g seconds.\\n',tf);\nfprintf('===================================================================\\n')\n\nend", "meta": {"author": "MIT-SPARK", "repo": "CertifiablyRobustPerception", "sha": "dd149d0c54093cfb72a8f912f4ae807635db6f3b", "save_path": "github-repos/MATLAB/MIT-SPARK-CertifiablyRobustPerception", "path": "github-repos/MATLAB/MIT-SPARK-CertifiablyRobustPerception/CertifiablyRobustPerception-dd149d0c54093cfb72a8f912f4ae807635db6f3b/MeshRegistration/solvers/chordal_relax_mesh_registration.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6876013099837327}} {"text": "% project the 3D points to generate 2D points according to the viewpoint\nfunction xproj = projectp3d(x3d, object)\n\nif isfield(object, 'viewpoint') == 1\n % project the 3D points\n viewpoint = object.viewpoint;\n a = viewpoint.azimuth*pi/180;\n e = viewpoint.elevation*pi/180;\n d = viewpoint.distance;\n f = viewpoint.focal;\n theta = viewpoint.theta*pi/180;\n principal = [viewpoint.px viewpoint.py];\n viewport = viewpoint.viewport;\nelse\n xproj = [];\n return;\nend\n\nif d == 0\n xproj = [];\n return;\nend\n\n% camera center\nC = zeros(3,1);\nC(1) = d*cos(e)*sin(a);\nC(2) = -d*cos(e)*cos(a);\nC(3) = d*sin(e);\n\n% Rotate coordinate system by theta is equal to rotating the model by -theta.\na = -a;\ne = -(pi/2-e);\n\n% rotation matrix\nRz = [cos(a) -sin(a) 0; sin(a) cos(a) 0; 0 0 1]; %rotate by a\nRx = [1 0 0; 0 cos(e) -sin(e); 0 sin(e) cos(e)]; %rotate by e\nR = Rx*Rz;\n\n% perspective project matrix\n% however, we set the viewport to 3000, which makes the camera similar to\n% an affine-camera. Exploring a real perspective camera can be a future work.\nM = viewport;\nP = [M*f 0 0; 0 M*f 0; 0 0 -1] * [R -R*C];\n% project\nx = P*[x3d ones(size(x3d,1), 1)]';\ndist = max(x(1,:))-min(x(1,:));\nx(1,:) = x(1,:) ./ x(3,:);\nx(2,:) = x(2,:) ./ x(3,:);\nnew_dist = max(x(1,:))-min(x(1,:));\n%x(1,:) = x(1,:) / mean(x(3,:));\n%x(2,:) = x(2,:) / mean(x(3,:));\nxz = x(3,:)*(M*f)*new_dist/dist;\nx = x(1:2,:);\n% rotation matrix 2D\nR2d = [cos(theta) -sin(theta); sin(theta) cos(theta)];\nx = (R2d * x)';\n% x = x';\n\n% transform to image coordinates\nx(:,2) = -1 * x(:,2);\nx = x + repmat(principal, size(x,1), 1);\nxz = (xz-mean(xz))';\nxproj = [x xz];\n", "meta": {"author": "akar43", "repo": "CategoryShapes", "sha": "55c9dab2293bcaceaaa3bf5fea782fdbf930fadb", "save_path": "github-repos/MATLAB/akar43-CategoryShapes", "path": "github-repos/MATLAB/akar43-CategoryShapes/CategoryShapes-55c9dab2293bcaceaaa3bf5fea782fdbf930fadb/utils/projectp3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6876013009898672}} {"text": "function radius = computeRadiusFromTrueAEcc(tru, sma, ecc)\n%computeRadiusFromTrueAEcc Summary of this function goes here\n% Detailed explanation goes here\n p = sma.*(1-ecc.^2);\n radius = p./(1+ecc.*cos(tru)); \nend\n\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/astrodynamics/computeRadiusFromTrueAEcc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6875560966647546}} {"text": "function [fmin,xmin]=ConjugateGradientMethod(x0)\n\n% initialization\nxk=x0;\ngk=grad_obj(xk);\ndk=-gk;\n\n% iteration\nfor i=1:length(x0)\n % line search\n alphak=fminbnd(@(alpha) phi(alpha,xk,dk),0,10);\n % update xk\n tempgk=gk;\n tempxk=xk;\n tempdk=dk;\n xk=tempxk+alphak*tempdk;\n gk=grad_obj(xk);\n tempbetak=(gk'*(gk-tempgk))/(dk'*(gk-tempgk));\n dk=-gk+tempbetak*tempdk;\nend\nxmin=xk;\nfmin=obj(xk);\n\n", "meta": {"author": "QiangLong2017", "repo": "Optimization-Theory-and-Algorithm", "sha": "13becd67be377356c221367ffbc7c90a1aabd917", "save_path": "github-repos/MATLAB/QiangLong2017-Optimization-Theory-and-Algorithm", "path": "github-repos/MATLAB/QiangLong2017-Optimization-Theory-and-Algorithm/Optimization-Theory-and-Algorithm-13becd67be377356c221367ffbc7c90a1aabd917/code/10_3ConjugateGradientMethod/ConjugateGradientMethod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.687556086738796}} {"text": "function [label, energy] = knKmeansPred(model, Xt)\n% Prediction for kernel kmeans clusterng\n% Input:\n% model: trained model structure\n% Xt: d x n testing data\n% Ouput:\n% label: 1 x n predict label\n% engery: optimization target value\n% Written by Mo Chen (sth4nth@gmail.com).\nX = model.X;\nt = model.label;\nkn = model.kn;\n\nn = size(X,2);\nk = max(t);\nE = sparse(t,1:n,1,k,n,n);\nE = bsxfun(@times,E,1./sum(E,2));\nZ = bsxfun(@minus,E*kn(X,Xt),diag(E*kn(X,X)*E')/2);\n[val, label] = max(Z,[],1);\nenergy = sum(kn(Xt))-2*sum(val);\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/clustering/knkmeans/knKmeansPred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6875560844098124}} {"text": "%%% Example script showing how to perform a 3D Total-Variation filtering with proxTV\n\nclear all\nclose all\n\n% Load color image (3 dimensions: length, width and color)\nX = imread('colors.png');\n\n% Introduce noise\nnoiseLevel = 0.2;\nN = double(imnoise(X,'gaussian',0,noiseLevel));\n\n% Filter using 3D TV-L1: for 3D one needs to invoke prox_TVgen\nlambda=100;\ndisp('Filtering image...');\ntic;\nF = prox_TVgen(N, [lambda lambda], [1 2], [1 1]);\n% Image | Penalty in each dimension | Dimensions to penalize | Norms to use\ntoc;\n\n% Any dimension can be penalized under any norm. By also penalizing the color dimension under TV-L2 we get a \"decolored\" image\nlambda2=5;\ndisp('Color filtering...');\ntic;\nF2 = prox_TVgen(N, [lambda lambda lambda2], [1 2 3], [1 1 2]);\n% Image | Penalty in each dimension | Dimensions to penalize | Norms to use \ntoc;\n\n% Plot results\nfigure();\nsubplot(2,2,1);\nimshow(X);\ntitle('Original');\nsubplot(2,2,2);\nimshow(uint8(N));\ntitle('Noisy');\nsubplot(2,2,3);\nimshow(uint8(F));\ntitle('Filtered');\nsubplot(2,2,4);\nimshow(uint8(F2));\ntitle('Color filtered');\n\n\n", "meta": {"author": "beckel", "repo": "nilm-eval", "sha": "83a2cd5fb911299cc267bd9998636934af781915", "save_path": "github-repos/MATLAB/beckel-nilm-eval", "path": "github-repos/MATLAB/beckel-nilm-eval/nilm-eval-83a2cd5fb911299cc267bd9998636934af781915/Matlab/lib/proxTV-1.0/demos/filter_image_color.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570318, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6875398792206617}} {"text": "function[Q1,Q2,Q3,Q4,Q]=divgeom(varargin)\n%DIVGEOM Geometric decomposition of eddy vorticity flux divergence.\n%\n% [F1,F2,F3,F4]=DIVGEOM(DX,DY,K,L,THETA) returns the geometric decomposition\n% of eddy vorticity flux divergence associated with variance ellipses \n% having kinetic energy K, anisotropy L, and orientation THETA.\n%\n% K, L, and THETA are matrices of the same size. These are defined on an\n% X-Y grid with x oriented in *columns* and y oriented in *rows*. DX and\n% DY are the sampling intervals in the X and Y directions, respectively.\n%\n% Note that K and L are related to ellipse parameters KAPPA and LAMBDA\n% used elsewhere in JLAB by K=KAPPA^2 and L=LAMBDA*KAPPA^2.\n%\n% F1, F2, F3, and F4 are four different contributions to the eddy \n% vorticity flux divergence, as follows:\n% \n% F1 Quadratic variations in the linear energy L\n% F2 Product of linear variations in THETA and L\n% F3 Quadratic variations in the orientation THETA\n% F4 Product of linear variations in orientation THETA\n%\n% For details, see Waterman and Lilly (2015), Geometric decomposition of\n% eddy-mean flow feedbacks in barotropic systems, J. Phys. Oceanogr. \n%\n% [F1,F2,F3,F4,F]=DIVGEOM(...) also returns the total eddy flux \n% divergence F, calculated directly, with F1+F2+F3+F4 = F apart from \n% numerical error.\n%\n% By default, DIVGEOM calculates derivates with repeated applications of\n% a first central difference. DIVGEOM(...,'arakawa') alternately uses a \n% modified first central difference appropriate for models that employ an\n% Awakawa advection scheme. \n% __________________________________________________________________\n%\n% Usage: [f1,f2,f3,f4]=divgeom(dx,dy,K,L,theta);\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2013--2015 J.M. Lilly --- type 'help jlab_license' for details\n\nif strcmpi(varargin{1}, '--f')\n % 'divgeom --f' generates a sample figure. XX not currently working\n %divgeom_figure,return\nend\n\n%Divgeom does run tests, but these are hidden because it involves mat-files\n%not distributed as a part of JLAB\n%if strcmpi(varargin{1},XXX)\n% divgeom_test,return\n%end\n\n\n\n\n% Do I do this? \n% Filtering\n% \n% DIVGEOM can optionally filter the second-order derivative terms, F1,\n% F3, and F to reduce small-scale noise.\n%\n% [F1,F2,F3,F4,F]=DIVGEOM(...,N) smooths F1, F3, and F with an N point\n% boxcar filter in both the X and Y directions. N should be odd.\n% __________________________________________________________________\n%\n\ndiffstr='cartesian';\nstr='second';\n\nfor i=1:2\n if ischar(varargin{end})\n if strcmpi(varargin{end}(1:3),'car')||strcmpi(varargin{end}(1:3),'ara')\n diffstr=varargin{end};\n elseif strcmpi(varargin{end}(1:3),'dir')||strcmpi(varargin{end}(1:3),'sec')\n str=varargin{end};\n end\n varargin=varargin(1:end-1);\n end\nend\n\ndx=varargin{1};\ndy=varargin{2};\nK=varargin{3};\nL=varargin{4};\ntheta=varargin{5};\n\nif length(varargin)==6\n N=varargin{6};\nelse\n N=0;\nend\n\n%[x,y] = meshgrid([1:size(K,2)]*dx,[1:size(K,1)]*dx);\n\n\n%/************************************************\n%Compute gradients\nLx=divgeom_vdiff(dx,L,2,diffstr);\nLy=divgeom_vdiff(dy,L,1,diffstr);\n\nthetax=divgeom_vdiff(dx,frac(1,2)*unwrap(2*theta,[],2),2,diffstr);\nthetay=divgeom_vdiff(dy,frac(1,2)*unwrap(2*theta,[],1),1,diffstr);\n\ncos2x=divgeom_vdiff(dx,cos(2*theta),2,diffstr);\ncos2y=divgeom_vdiff(dy,cos(2*theta),1,diffstr);\n\nsin2x=divgeom_vdiff(dx,sin(2*theta),2,diffstr);\nsin2y=divgeom_vdiff(dy,sin(2*theta),1,diffstr);\n\nM=L.*cos(2*theta);\nN=L.*sin(2*theta);\n\nNx=divgeom_vdiff(dx,N,2,diffstr);\nNy=divgeom_vdiff(dy,N,1,diffstr);\n\nQM=divgeom_mixederiv(dx,dy,divgeom_vdiff(dx,M,2,diffstr),divgeom_vdiff(dy,M,1,diffstr),diffstr);\nQN=divgeom_vdiff(dx,Nx,2,diffstr)-divgeom_vdiff(dy,Ny,1,diffstr);\n\nQ=QN-QM;\n%\\************************************************\n\n% \n% cx=L;\n% cx=vdiff(dx,cx,2)+sqrt(-1)*vdiff(dx,cx,1);\n% cx=vdiff(dx,cx,2)+sqrt(-1)*vdiff(dx,cx,1);\n% Q1=-imag(rot(-2*theta).*cx);\n\n \nQ1a=-cos(2*theta).*divgeom_mixederiv(dx,dy,Lx,Ly,diffstr);\nQ1b= sin(2*theta).*(divgeom_vdiff(dx,Lx,2,diffstr)-divgeom_vdiff(dy,Ly,1,diffstr));\nQ1=Q1a+Q1b;\n\n%vsize(L,theta,thetax,thetay)\nQ3a= 2*L.*cos(2*theta).*(divgeom_vdiff(dx,thetax,2,diffstr)-divgeom_vdiff(dy,thetay,1,diffstr));\nQ3b= 2*L.*sin(2*theta).*divgeom_mixederiv(dx,dy,thetax,thetay,diffstr);\nQ3=Q3a+Q3b;\n\n\nif findstr(str,'dir')\n Q2a= 4*cos(2*theta).*(thetax.*Lx-thetay.*Ly);\n Q2b= 4*sin(2*theta).*(thetax.*Ly+thetay.*Lx);\n Q2=Q2a+Q2b;\n \n Q4a= 4*L.*cos(2*theta).*(2*thetax.*thetay);\n Q4b= -4*L.*sin(2*theta).*(thetax.^2-thetay.^2);\n Q4=Q4a+Q4b;\nelse\n dkdsin2=L.*(divgeom_vdiff(dx,sin2x,2,diffstr)-divgeom_vdiff(dy,sin2y,1,diffstr));\n dldcos2=L.*divgeom_mixederiv(dx,dy,divgeom_vdiff(dx,cos(2*theta),2,diffstr),...\n divgeom_vdiff(dy,cos(2*theta),1,diffstr),diffstr);\n \n Q2a=QN-Q1b-dkdsin2;\n Q2b=-(QM+Q1a-dldcos2);\n Q2=Q2a+Q2b;\n \n Q4a=-dldcos2-Q3b;\n Q4b=dkdsin2-Q3a;\n Q4=Q4a+Q4b;\nend\n\n\nfunction[df]=divgeom_vdiff(dx,f,dim,schemestr);\n%This is basically just to implement what I think is the way the Arakawa\n%advection scheme takes derivatives. Taken from PSI2FIELDS\n\nf0ca=f(:,1,:,:);\nf0cb=f(:,end,:,:);\nf0ra=f(1,:,:,:);\nf0rb=f(end,:,:,:);\n\nif strcmpi(schemestr(1:3),'ara')\n if dim==1\n dim2=2;\n elseif dim==2\n dim2=1;\n end\n f=frac(1,4)*(2*f + vshift(f,1,dim2) + vshift(f,-1,dim2));\n if dim==1\n %size(f),dim,size(frac(1,3)*(2*f + vshift(f,1,dim2)))\n %f(:,1,:,:)=0;\n %f(:,end,:,:)=0;\n f(:,1,:,:)=frac(1,3)*(2*f0ca + vshift(f0ca,1,dim2));\n f(:,end,:,:)=frac(1,3)*(2*f0cb + vshift(f0cb,-1,dim2));\n %f(:,end,:,:)=f0(:,end,:,:);\n elseif dim==2\n %f(1,:,:,:)=0;\n %f(end,:,:,:)=0;\n f(1,:,:,:)=frac(1,3)*(2*f0ra + vshift(f0ra,1,dim2));\n f(end,:,:,:)=frac(1,3)*(2*f0rb + vshift(f0rb,-1,dim2));\n %f(end,:,:,:)=f0(end,:,:,:);\n end\nend\n% dim\n% size(f)\n% edgestr\ndf=vdiff(dx,f,dim);\n\n\nfunction[gxy]=divgeom_mixederiv(dx,dy,fx,fy,diffstr)\n%Correction for two possible forms of mixed derivative\n\ngxy= divgeom_vdiff(dy,fx,1,diffstr);\ngyx= divgeom_vdiff(dx,fy,2,diffstr);\ngxy=gxy+gyx;\n\n%bool=abs(gyx)-1,1,'first');\n\n%No more than 15% of the data has the error ratio > 1/10\nreporttest('DIVGEOM Q2 direct and implicit forms agree',index/length(rat)>0.85);\n\nrat=abs(frac(q4-q4d,q4+q4d));\nrat=sort(rat(:));\nindex=find(log10(rat)>-1,1,'first');\n\n%No more than 15% of the data has the error ratio > 1/10\nreporttest('DIVGEOM Q4 direct and implicit forms agree',index/length(rat)>0.85);\n\n\n\nfunction[]=divgeom_figure\nload jetellipses_highres\nuse jetellipses\n \n[q1,q2,q3,q4,q]=divgeom(x(2)-x(1),x(2)-x(1),kappabar,lambdabar,thetabar,5);\n\nfigure\nsubplot(2,2,1),jpcolor(x,y,q1),axis equal,axis tight\nsubplot(2,2,2),jpcolor(x,y,q2),axis equal,axis tight\nsubplot(2,2,3),jpcolor(x,y,q3),axis equal,axis tight\nsubplot(2,2,4),jpcolor(x,y,q4),axis equal,axis tight\nfor i=1:4\n subplot(2,2,i),%caxis([-.2 .2]/16)\n hold on,%contour(x,y,lambdabar,[0.1 0.1]);\n %linestyle k\nend\npackfig(2,2)\n\n\n%[q1b,q2b,q3b,q4b,qb]=divgeom(x(2)-x(1),kappabar,lambdabar,thetabar,5,'arakawa');\n\n\nfigure\nsubplot(2,1,1),jpcolor(x,y,q1+q2+q3+q4),axis equal,axis tight\nsubplot(2,1,2),jpcolor(x,y,q),axis equal,axis tight\nfor i=1:2\n subplot(2,1,i),caxis([-.2 .2]/16)\n hold on,contour(x,y,lambdabar,[0.1 0.1]);\n linestyle k\nend\npackfig(2,1)\n\nfunction[]=divgeom_figure2\n\nfilename='/Users/lilly/Data/early/QGBetaPlaneTurbulenceFloats_experiment_04.nc';\nii=425:675;\n[u,v]=vzeros(length(ii),1024,1001);\nfor k=1:1001\n k\n [utemp,vtemp]=FieldsFromTurbulenceFile(filename,k, 'u','v');\n u(:,:,k)=utemp(ii,:);\n v(:,:,k)=vtemp(ii,:);\nend\n\nu2=u;\nv2=v;\n\nfor k=1:251\n k\n u2(k,:,:)=anatrans(u(k,:,:),3,'periodic');\n v2(k,:,:)=anatrans(v(k,:,:),3,'periodic');\nend\n\n\n\n", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jOceans/divgeom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6875398751443159}} {"text": "% Fig. 8.10 Feedback Control of Dynamic Systems, 6e \n% Franklin, Powell, Emami\n%\n\nclear all;\n%close all;\nclf\n\nnumG=1;\ndenG=[1 0 0];\n\nnumD=[1 .2];\ndenD=[1 2];\n\nnum=conv(numG,numD);\nden=conv(denG,denD);\npoles=roots(den);\nzeros=roots(num);\n\n\nK1=0:.05:1.22;\nK2=[1.25 1.28]; % K for break-in and break-away points\nK3=1.5:5:100;\nK=[K1 K2 K3];\nKo=.81;\n\nr=rlocus(num,den,K);\nro=rlocus(num,den,Ko);\n\nplot(r,'-'),\naxis('square')\naxis([-2.5 .5 -1.5 1.5])\nhold on\nplot(ro,'k*')\nplot(-.2,0,'o')\nplot(-2,0,'x')\nplot(0,.01,'x')\nplot(0,-.01,'x')\ntitle('Fig. 8.10 s-plane locus vs. K')\nxlabel('Re(s)')\nylabel('Im(s)')\ntext(-2.3,-.7,'* K_c = 0.81') \nnicegrid\nhold off\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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig8_10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6875398718379083}} {"text": "function [f,bandwidth] = calcDensity(x,varargin)\n% kernel density estimation from real valued data\n%\n% Syntax\n% f = calcDensity(x)\n% f = calcDensity(x,'range',[xmin;xmax])\n%\n% f = calcDensity([x,y],'range',[xmin,ymin;xmax,ymax])\n% f = calcDensity([x,y,z],'range',[xmin,ymin,zmin;xmax,ymax,zmax])\n%\n% Input\n% x,y,z - random samples as n x 1 vectors\n% \n% Output\n% f - density as \n%\n% See also\n% vector3d/calcDensity orientation/calcDensity\n\nif check_option(varargin,'periodic')\n\n f = calcS1Density(x,varargin{:});\n return\nend\n\nrange = get_option(varargin,'range',[min(x);max(x)]);\nvarargin = delete_option(varargin,'range',1);\n\n% the one dimensional case\nif length(x) == numel(x)\n\n [bandwidth,density,grid] = kde(x,2^14,range(1),range(2),varargin{:});\n grid = {grid};\n \nelse % the multidimensional case\n \n dim = size(x,2);\n N = round(1000000^(1/dim));\n for d = 1:dim\n gs{d} = linspace(range(1,d),range(2,d),N);\n end\n \n [gs{:}] = ndgrid(gs{:});\n grid = gs;\n \n gs = cellfun(@(y) y(:),gs,'UniformOutput',false); \n density = reshape(kdeN(x,[gs{:}]),size(grid{1}));\n \nend\n\nf = griddedInterpolant(grid{:},density,'spline');", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/tools/statistic_tools/calcDensity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6875398687581521}} {"text": "function [edges,weights] = spm_vb_edgeweights(vxyz,img)\n% Compute edge set and edge weights of a graph\n% FORMAT [edges,weights]= spm_vb_edgeweights(vxyz,img)\n% \n% vxyz list of neighbouring voxels (see spm_vb_neighbors)\n% img image defined on the node set, e.g. wk_ols. The edge weights \n% are uniform if this is not given, otherwise they are a function\n% of the distance in physical space and that between the image\n% at neighoring nodes\n\n% edges [Ne x 2] list of neighboring voxel indices\n% weights [Ne x 1] list of edge weights \n% Ne number of edges (cardinality of edges set)\n% N number of nodes (cardinality of node set)\n%__________________________________________________________________________\n% Copyright (C) 2008-2014 Wellcome Trust Centre for Neuroimaging\n\n% Lee Harrison\n% $Id: spm_vb_edgeweights.m 6079 2014-06-30 18:25:37Z spm $\n\nN = size(vxyz,1);\n[r,c,v] = find(vxyz');\nedges = [c,v];\n% undirected graph, so only need store upper [lower] triangle\ni = find(edges(:,2) > edges(:,1));\nedges = edges(i,:);\nif nargin < 2,\n weights = ones(size(edges,1),1);\n return\nelse\n ka = 16;\n M = mean(img,2)*ones(1,N);\n C = (1/N)*(img-M)*(img-M)';\n Hf = inv(C);\n A = spm_vb_incidence(edges,N);\n dB = img*A'; % spatial gradients of ols estimates\n dg2 = sum((dB'*Hf).*dB',2); % squared norm of spatial gradient of regressors\n ds2 = 1 + dg2; % squared distance in space is 1 as use only nearest neighbors\n weights = exp(-ds2/ka); % edge weights\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_vb_edgeweights.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6875398634135728}} {"text": " function xs = wls_grpr(x, G, W, yi, D, xmin, xmax, niter)\n%function xs = wls_grpr(x, G, W, yi, D, xmin, xmax, niter)\n%\n%\tweighted least squares with constraint xmin <= x <= xmax\n%\tusing gradient projection method (polyak:87 p. 207)\n%\t\txnew = max(xmin, xold + D * \\nabla J(xold))\n%\tcost function: J(x) = (y-Gx) W (y-Gx) / 2\n%\tin\n%\t\tx\t[np,1]\t\tinitial estimate\n%\t\tG\t[nd,np]\t\tsystem matrix\n%\t\tW\t[nd,nd]\t\tweighting matrix\n%\t\tyi\t[nd,1]\t\tnoisy measurements (e.g. sinogram)\n%\t\tD\t[np,np]\t\tpreconditioning / step size matrix\n%\t\txmin\t\t\tminimum allowable x value\n%\t\txmax\t\t\tmaximum allowable x value\n%\t\tniter\t\t\t# of iterations\n%\tout\n%\t\txs\t[np,niter+1]\titerates\n%\n%\tCopyright Dec. 2000,\tJeff Fessler, University of Michigan\n\nif nargin < 2, ir_usage, end\n\nif ~isvar('W') || isempty(W)\n\tW = 1;\nend\nif ~isvar('niter') || isempty(niter)\n\tniter = 1;\nend\nif ~isvar('D') || isempty(D)\n\tD = 1;\nend\nif ~isvar('xmin') || isempty(xmin), xmin = 0; end\nif ~isvar('xmax') || isempty(xmax), xmax = inf; end\n\n\n% loop over iterations\nxs = zeros(length(x), niter);\nxs(:,1) = x;\nfor iter = 2:niter\n%\tprintf('WLS-PG iteration %d', iter-1)\n\n\tif ~rem(iter,2)\n\t\tlgrad = G' * (W .* (yi - G * x));\n\n\t\tx = x + D * lgrad;\t% the update!\n\telse\n\n\t\tx = max(x,xmin);\t% lower bound\n\t\tx = min(x,xmax);\t% upper bound\n\tend\n\n\txs(:,iter) = x;\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/wls/wls_grpr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6875398606054607}} {"text": "function [H,WtW,WtX] = nnls_fpgm(X,W,options) \n\n% Computes an approximate solution of the following nonnegative least\n% squares problem (NNLS)\n%\n% min_{H >= 0} ||X-WH||_F^2\n% \n% using a fast gradient method; \n% See Nesterov, Introductory Lectures on Convex Optimization: A Basic \n% Course, Kluwer Academic Publisher, 2004. \n% \n% Input / Output; see nnls_input_output.m \n% \n% + options.proj allows to use a contraints on the columns or rows of H so \n% that the entries in each column/row sum to at most one \n% options.proj = 0: no projection (default). \n% options.proj = 1: projection of the columns on {x|x>=0, sum(x) <= 1} \n% options.proj = 2: projection of the rows {x|x>=0, sum(x) = 1} \n% \n% + options.alpha0 is the FPGM extrapolation parameter (default=0.05)\n%\n% Code modified from https://sites.google.com/site/nicolasgillis/code\n%\n% This file has been ported from \n% nnls_FPGM.m at https://gitlab.com/ngillis/nmfbook/-/tree/master/algorithms\n% by Nicolas Gillis (nicolas.gillis@umons.ac.be)\n\n\n if nargin <= 2\n options = [];\n end\n if ~isfield(options,'delta')\n options.delta = 1e-6; % Stopping condition depending on evolution of the iterate V:\n % Stop if ||V^{k}-V^{k+1}||_F <= delta * ||V^{0}-V^{1}||_F\n % where V^{k} is the kth iterate.\n end\n if ~isfield(options,'inner_max_epoch')\n options.inner_max_epoch = 500; \n end\n if ~isfield(options,'proj') % Projection on the unit simplex and the origin\n options.proj = 0; \n end\n if ~isfield(options,'alpha0') % Parameter for FPGM ~ extrapolation parameter\n options.alpha0 = 0.05; \n end\n\n W = full(W); \n [m, n] = size(X);\n [m, r] = size(W);\n WtW = W'*W;\n WtX = W'*X;\n\n % If no initial matrices are provided, H is initialized as follows: \n if ~isfield(options,'init') || isempty(options.init)\n H = nnls_init(X,W,WtW,WtX); \n else\n H = options.init; \n end\n\n % Hessian and Lipschitz constant \n L = norm(WtW,2); \n % Linear term \n WtX = W'*X; \n alpha0 = options.alpha0; % Parameter of FPGM, can be tuned. \n % If options.alpha0 = 0 --> no acceleration, PGM\n alpha(1) = alpha0;\n if options.proj == 1\n H = SimplexProj( H ); % Project columns of H onto the simplex and origin\n elseif options.proj == 0\n H = max(H,0);\n elseif options.proj == 2\n H = SimplexColProj(H'); % Project rows of H onto the simplex\n H = H'; \n end\n Y = H; % second sequence\n i = 1; \n % Stop if ||V^{k}-V^{k+1}||_F <= delta * ||V^{0}-V^{1}||_F\n eps0 = 0; eps = 1; \n while i <= options.inner_max_epoch && eps >= options.delta*eps0\n % Previous iterate\n Hp = H; \n % FGM Coefficients; see Nesterov's book\n alpha(i+1) = ( sqrt(alpha(i)^4 + 4*alpha(i)^2 ) - alpha(i)^2) / (2); \n beta(i) = alpha(i)*(1-alpha(i))/(alpha(i)^2+alpha(i+1));\n % Projection step\n H = Y - (WtW*Y-WtX) / L;\n if options.proj == 1\n H = SimplexProj( H ); % Project columns of H onto the set {x|x>=0, sum(x) <= 1} \n elseif options.proj == 0\n H = max(H,0);\n elseif options.proj == 2\n H = SimplexColProj(H'); % Project rows of H onto the simplex\n H = H';\n end\n % `Optimal' linear combination of iterates\n Y = H + beta(i)*(H-Hp); \n if i == 1\n eps0 = norm(H-Hp,'fro'); \n end\n eps = norm(H-Hp,'fro'); \n i = i + 1; \n end \nend\n", "meta": {"author": "hiroyuki-kasai", "repo": "NMFLibrary", "sha": "ed44132dfe1b5495df685006b42259f0bd16bea3", "save_path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary/NMFLibrary-ed44132dfe1b5495df685006b42259f0bd16bea3/solver/nnls/nnls_fpgm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6875398565291144}} {"text": "% solve the problem:\n% min_{x,e} 0.5*|z-Dx-e|_2^2 + 0.5*lambda1*|x|_2^2 + lambda2*|e|_1\n%\n% solve the projection by APG\n% input:\n% z - data point\n% D - basis matrix\n% lambda1, lambda2 - tradeoff parameters\n% output:\n% r - projection coefficient\n% e - sparse noise\n% copyright Jiashi Feng (jshfeng@gmail.com)\n%\nfunction [x,e] = solve_proj2(z,D,lambda1,lambda2)\n % initialization\n [ndim,ncol] = size(D);\n e = zeros(ndim,1);\n x = zeros(ncol,1);\n I = eye(ncol);\n converged = false;\n maxIter = inf;\n iter = 0;\n % alternatively update\n DDt = inv(D'*D+lambda1*I)*D';\n while ~converged\n iter = iter + 1;\n xtemp = x;\n x = DDt*(z-e);\n % x = (D'*D + lambda1*I)\\(D'*(z-e));\n etemp = e;\n e = thres(z-D*x,lambda2);\n stopc = max(norm(e-etemp), norm(x-xtemp))/ndim;\n if stopc < 1e-6 || iter > maxIter\n converged = true;\n end\n % fval = func_proj(z,D,lambda1,lambda2,x,e);\n % fprintf('fval = %f\\n', fval);\n end\nend\n\nfunction x = thres(y,mu)\n x = max(y-mu, 0);\n x = x + min(y + mu, 0);\nend\n\nfunction fval = func_proj(z,D,lambda1,lambda2,x,e)\n fval = 0;\n fval = fval + 0.5*norm(z-D*x-e)^2;\n fval = fval + 0.5*lambda1*norm(x)^2;\n fval = fval + lambda2*sum(abs(e));\nend", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/STOC-RPCA/solve_proj2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6875398524527683}} {"text": "function obj=stat_density(obj,varargin)\n% geom_point Displays an smooth density estimate of the data in x\n%\n% Example syntax (default arguments): gramm_object.stat_density('function','pdf','kernel','normal','npoints',100)\n% the 'function','kernel', and 'bandwidth' arguments are the\n% ones used by the underlying matlab function ksdensity\n% 'npoints' is used to set how many x values are used to\n% display the density estimates.\n% 'extra_x' is used to increase the range of x values over\n% which the estimated density function is displayed. Values\n% will be extended to the right and to the left by extra_x\n% times the range of x data.\n\np=inputParser;\nmy_addParameter(p,'bandwidth',-1);\nmy_addParameter(p,'function','pdf')\nmy_addParameter(p,'kernel','normal')\nmy_addParameter(p,'npoints',100)\nmy_addParameter(p,'extra_x',0.1)\nparse(p,varargin{:});\n\nobj.geom=vertcat(obj.geom,{@(dobj,dd)my_density(dobj,dd,p.Results)});\nobj.results.stat_density={};\nend\n\nfunction hndl=my_density(obj,draw_data,params)\n\n\nif obj.polar.is_polar\n %Make x data modulo 2 pi\n draw_data.x=mod(comb(draw_data.x),2*pi);\n warning('Polar density estimate is probably not proper for circular data, use custom bandwidth');\n %Let's try to make boundaries a bit more proper by\n %repeating values below 0 and above 2 pi\n draw_data.x=[draw_data.x-2*pi;draw_data.x;draw_data.x+2*pi];\n extra_x=0;\n binranges=linspace(0,2*pi,params.npoints);\nelse\n extra_x=(obj.var_lim.maxx-obj.var_lim.minx)*params.extra_x;\n binranges=linspace(obj.var_lim.minx-extra_x,obj.var_lim.maxx+extra_x,params.npoints);\nend\n\nif params.bandwidth>0\n [f,xi] = ksdensity(comb(draw_data.x),binranges,'function',params.function,'bandwidth',params.bandwidth,'kernel',params.kernel);\nelse\n [f,xi] = ksdensity(comb(draw_data.x),binranges,'function',params.function,'kernel',params.kernel);\nend\n\nobj.plot_lim.minx(obj.current_row,obj.current_column)=obj.var_lim.minx-extra_x;\nobj.plot_lim.maxx(obj.current_row,obj.current_column)=obj.var_lim.maxx+extra_x;\nobj.plot_lim.miny(obj.current_row,obj.current_column)=0;\nif obj.firstrun(obj.current_row,obj.current_column)\n obj.plot_lim.maxy(obj.current_row,obj.current_column)=max(f);\n %obj.firstrun(obj.current_row,obj.current_column)=0;\n obj.aes_names.y=[obj.aes_names.x ' ' params.function];\nelse\n if max(f)>obj.plot_lim.maxy(obj.current_row,obj.current_column)\n obj.plot_lim.maxy(obj.current_row,obj.current_column)=max(f);\n end\nend\n\nobj.results.stat_density{obj.result_ind,1}.x=xi;\nobj.results.stat_density{obj.result_ind,1}.y=f;\n\n[xi,f]=to_polar(obj,xi,f);\nhndl=plot(xi,f,'LineStyle',draw_data.line_style,'Color',draw_data.color,'lineWidth',draw_data.line_size);\n\nobj.results.stat_density{obj.result_ind,1}.handle=hndl;\nend", "meta": {"author": "piermorel", "repo": "gramm", "sha": "b0fc59245c17d6fbcd86a105d893aeb745fb51e2", "save_path": "github-repos/MATLAB/piermorel-gramm", "path": "github-repos/MATLAB/piermorel-gramm/gramm-b0fc59245c17d6fbcd86a105d893aeb745fb51e2/@gramm/stat_density.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.687397210793914}} {"text": "function triangle_ncc_rule_test04 ( )\n\n%*****************************************************************************80\n%\n%% TEST04 tests TRIANGLE_NCC_RULE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 January 2007\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST04\\n' );\n fprintf ( 1, ' TRIANGLE_NCC_RULE returns the points and weights of\\n' );\n fprintf ( 1, ' an NCC rule for the unit triangle.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' This routine uses those rules to estimate the\\n' );\n fprintf ( 1, ' integral of monomomials in the unit triangle.\\n' );\n\n rule_num = triangle_ncc_rule_num ( );\n\n area = 0.5;\n\n for a = 0 : 10\n\n for b = 0 : 10 - a\n%\n% Multiplying X^A * Y^B by COEF will give us an integrand\n% whose integral is exactly 1. This makes the error calculations easy.\n%\n coef = ( a + b + 2 ) * ( a + b + 1 );\n for i = 1 : b\n coef = coef * ( a + i ) / i;\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Integrate %f * X^%d * Y^%d\\n', coef, a, b );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Rule QUAD ERROR\\n' );\n fprintf ( 1, '\\n' );\n\n for rule = 1 : rule_num\n\n order_num = triangle_ncc_order_num ( rule );\n\n [ xy, w ] = triangle_ncc_rule ( rule, order_num );\n\n quad = 0.0;\n\n for order = 1 : order_num\n\n x = xy(1,order);\n y = xy(2,order);\n\n if ( a == 0 & b == 0 )\n value = coef;\n elseif ( a == 0 & b ~= 0 )\n value = coef * y^b;\n elseif ( a ~= 0 & b == 0 )\n value = coef * x^a;\n elseif ( a ~= 0 & b ~= 0 )\n value = coef * x^a * y^b;\n end\n\n quad = quad + w(order) * value;\n\n end\n\n quad = area * quad;\n\n exact = 1.0;\n err = abs ( exact - quad );\n\n fprintf ( 1, ' %8d %14f %14f\\n', rule, quad, err );\n \n end\n\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/triangle_ncc_rule/triangle_ncc_rule_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.6873972090622308}} {"text": "function yval = basis_matrix_tmp ( left, n, mbasis, ndata, tdata, ydata, tval )\n\n%*****************************************************************************80\n%\n%% BASIS_MATRIX_TMP computes Q = T * MBASIS * P\n%\n% Discussion:\n%\n% YDATA is a vector of data values, most frequently the values of some\n% function sampled at uniformly spaced points. MBASIS is the basis\n% matrix for a particular kind of spline. T is a vector of the\n% powers of the normalized difference between TVAL and the left\n% endpoint of the interval.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer LEFT, indicats that TVAL is in the interval\n% [ TDATA(LEFT), TDATA(LEFT+1) ], or that this is the \"nearest\"\n% interval to TVAL.\n% For TVAL < TDATA(1), use LEFT = 1.\n% For TDATA(NDATA) < TVAL, use LEFT = NDATA - 1.\n%\n% Input, integer N, the order of the basis matrix.\n%\n% Input, real MBASIS(N,N), the basis matrix.\n%\n% Input, integer NDATA, the dimension of the vectors TDATA and YDATA.\n%\n% Input, real TDATA(NDATA), the abscissa values. This routine\n% assumes that the TDATA values are uniformly spaced, with an\n% increment of 1.0.\n%\n% Input, real YDATA(NDATA), the data values to be interpolated or\n% approximated.\n%\n% Input, real TVAL, the value of T at which the spline is to be\n% evaluated.\n%\n% Output, real YVAL, the value of the spline at TVAL.\n%\n if ( left == 1 )\n arg = 0.5E+00 * ( tval - tdata(left) );\n first = left;\n elseif ( left < ndata - 1 )\n arg = tval - tdata(left);\n first = left - 1;\n elseif ( left == ndata - 1 )\n arg = 0.5E+00 * ( 1.0E+00 + tval - tdata(left) );\n first = left - 1;\n end\n%\n% TVEC(I) = ARG**(N-I).\n%\n tvec(n,1) = 1.0E+00;\n for i = n-1 : -1 : 1\n tvec(i,1) = arg * tvec(i+1,1);\n end\n\n yval = 0.0E+00;\n for j = 1 : n\n yval = yval + ( tvec(1:n,1)' * mbasis(1:n,j) ) * ydata(first - 1 + j);\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/spline/basis_matrix_tmp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6873972009978547}} {"text": "function [r,c,V] = findnearest(srchvalue,srcharray,bias)\n\n% Usage:\n% Find the nearest numerical value in an array to a search value\n% All occurances are returned as array subscripts\n%\n% Output:\n%\n% For 2D matrix subscripts (r,c) use:\n%\n% [r,c] = findnearest(srchvalue,srcharray,gt_or_lt)\n%\n%\n% To also output the found value (V) use:\n%\n% [r,c,V] = findnearest(srchvalue,srcharray,gt_or_lt)\n%\n%\n% For single subscript (i) use:\n%\n% i = findnearest(srchvalue,srcharray,gt_or_lt)\n% \n%\n% Inputs:\n%\n% srchvalue = a numerical search value\n% srcharray = the array to be searched\n% bias = 0 (default) for no bias\n% -1 to bias the output to lower values\n% 1 to bias the search to higher values\n% (in the latter cases if no values are found\n% an empty array is ouput)\n%\n%\n% By Tom Benson (2002)\n% University College London\n% t.benson@ucl.ac.uk\n\nif nargin<2\n error('Need two inputs: Search value and search array')\nelseif nargin<3\n bias = 0;\nend\n\n% find the differences\nsrcharray = srcharray-srchvalue;\n\nif bias == -1 % only choose values <= to the search value\n \n srcharray(srcharray>0) =inf;\n \nelseif bias == 1 % only choose values >= to the search value\n \n srcharray(srcharray<0) =inf;\n \nend\n\n% give the correct output\nif nargout==1 | nargout==0\n \n if all(isinf(srcharray(:)))\n r = [];\n else\n r = find(abs(srcharray)==min(abs(srcharray(:))));\n end \n \nelseif nargout>1\n if all(isinf(srcharray(:)))\n r = [];c=[];\n else\n [r,c] = find(abs(srcharray)==min(abs(srcharray(:))));\n end\n \n if nargout==3\n V = srcharray(r,c)+srchvalue;\n end\nend\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/2838-findnearest-m/findnearest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6873497160616535}} {"text": "function V = construct_V_matrix(measurements)\n%function V = construct_V_matrix(measurements)\n%\n% This function constructs and returns the translational data matrix V\n% defined in equation (16) of the paper\n\n% Copyright (C) 2016 by David M. Rosen\n\nD = length(measurements.t{1}); % D = dimension of SE(d)\nN = max(max(measurements.edges)); % N = number of nodes in the pose graph\nM = size(measurements.edges,1); % M = number of edges in the pose graph\n\n\n% The number of nonzero elements in V; there are D nonzero elements for\n% each translational measurement, plus D*N slots to store the sum of the\n% observations emanating from each node\n\nNNZ = D*M + D*N;\n\nrows = zeros(1, NNZ);\ncols = zeros(1, NNZ);\nvals = zeros(1, NNZ);\n\nfor e = 1:M\n \n %Extract measurement data\n i = measurements.edges(e, 1); %The node that this edge *leaves*\n j = measurements.edges(e, 2); %The node that this edge *enters*\n \n tij = measurements.t{e};\n tau_ij = measurements.tau{e};\n \n %Set V_ji = -tau_ij * t_ij'\n \n cmin = D*(e-1) + 1;\n cmax = D*(e-1) + D;\n \n rows(cmin:cmax) = j*ones(1, D);\n cols(cmin:cmax) = D*(i-1) + 1 : D*(i-1) + D;\n vals(cmin:cmax) = -tau_ij * tij';\n \n %Add this observation to the weighted sum of measurements emanating\n %from node i\n \n cmin = D*M + D*(i - 1) + 1;\n cmax = D*M + D*(i - 1) + D;\n vals(cmin : cmax) = vals(cmin : cmax) + tau_ij*tij';\nend\n\n% Fill in the indices for the running sums\n\nfor i = 1:N\n cmin = D*M + D*(i-1) + 1;\n cmax = D*M + D*(i-1) + D;\n \n rows(cmin:cmax) = i*ones(1,D);\n cols(cmin:cmax) = [D*(i-1) + 1 : D*(i - 1) + D];\nend\n\nV = sparse(rows, cols, vals, N, D*N);\n\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/lib/construct_V_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.6873497121182158}} {"text": "function [ n_data, a, x, fx ] = poisson_cdf_values ( n_data )\n\n%*****************************************************************************80\n%\n%% POISSON_CDF_VALUES returns some values of the Poisson CDF.\n%\n% Discussion:\n%\n% CDF(X)(A) is the probability of at most X successes in unit time,\n% given that the expected mean number of successes is A.\n%\n% In Mathematica, the function can be evaluated by:\n%\n% Needs[\"Statistics`DiscreteDistributions`]\n% dist = PoissonDistribution [ a ]\n% CDF [ dist, x ]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 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% Daniel Zwillinger,\n% CRC Standard Mathematical Tables and Formulae,\n% 30th Edition, CRC Press, 1996, pages 653-658.\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, real A, the parameter of the function.\n%\n% Output, integer X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 21;\n\n a_vec = [ ...\n 0.02E+00, ...\n 0.10E+00, ...\n 0.10E+00, ...\n 0.50E+00, ...\n 0.50E+00, ...\n 0.50E+00, ...\n 1.00E+00, ...\n 1.00E+00, ...\n 1.00E+00, ...\n 1.00E+00, ...\n 2.00E+00, ...\n 2.00E+00, ...\n 2.00E+00, ...\n 2.00E+00, ...\n 5.00E+00, ...\n 5.00E+00, ...\n 5.00E+00, ...\n 5.00E+00, ...\n 5.00E+00, ...\n 5.00E+00, ...\n 5.00E+00 ];\n\n fx_vec = [ ...\n 0.9801986733067553E+00, ...\n 0.9048374180359596E+00, ...\n 0.9953211598395555E+00, ...\n 0.6065306597126334E+00, ...\n 0.9097959895689501E+00, ...\n 0.9856123220330293E+00, ...\n 0.3678794411714423E+00, ...\n 0.7357588823428846E+00, ...\n 0.9196986029286058E+00, ...\n 0.9810118431238462E+00, ...\n 0.1353352832366127E+00, ...\n 0.4060058497098381E+00, ...\n 0.6766764161830635E+00, ...\n 0.8571234604985470E+00, ...\n 0.6737946999085467E-02, ...\n 0.4042768199451280E-01, ...\n 0.1246520194830811E+00, ...\n 0.2650259152973617E+00, ...\n 0.4404932850652124E+00, ...\n 0.6159606548330631E+00, ...\n 0.7621834629729387E+00 ];\n\n x_vec = [ ...\n 0, 0, 1, 0, ...\n 1, 2, 0, 1, ...\n 2, 3, 0, 1, ...\n 2, 3, 0, 1, ...\n 2, 3, 4, 5, ...\n 6 ];\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 a = 0.0;\n x = 0;\n fx = 0.0;\n else\n a = a_vec(n_data);\n x = x_vec(n_data);\n fx = fx_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/poisson_cdf_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6873497099461418}} {"text": "function uI = faceinterpolate(u,node,elem,elemType)\n%% FACEINTERPOLATE interpolate to face elements (RT0 or BDM1).\n%\n% uI = faceinterpolate(u,node,elem,elemType) interpolates a given function u\n% into the lowesr order RT0 or BDM1 finite element spaces. The coefficient\n% is given by the line integral int_e u*n ds. The input elemType can be 'RT0'\n% or 'BDM1'.\n%\n% Example\n%\n% maxIt = 5;\n% node = [1,0; 1,1; 0,1; -1,1; -1,0; -1,-1; 0,-1; 0,0]; % nodes\n% elem = [1,2,8; 3,8,2; 8,3,5; 4,5,3; 7,8,6; 5,6,8]; % elements\n% bdEdge = setboundary(node,elem,'Dirichlet');\n% pde = mixBCdata;\n% err = zeros(maxIt,2); N = zeros(maxIt,1);\n% for i =1:maxIt\n% [node,elem,bdEdge] = uniformrefine(node,elem,bdEdge);\n% [u,sigma,M] = PoissonRT0(node,elem,pde,bdEdge);\n% sigmaI = faceinterpolate(pde.Du,node,elem,'RT0');\n% err(i,1) = getL2errorRT0(node,elem,pde.Du,sigmaI,pde.d);\n% err(i,2)=sqrt((sigma-sigmaI)'*M*(sigma-sigmaI));\n% N(i) = size(u,1);\n% end\n% figure;\n% showrate2(N,err(:,1),2,'r-+','||Du - \\sigma_I||',...\n% N,err(:,2),2,'b-+','||\\sigma^{RT_0} - \\sigma_I||');\n%\n% See also edgeinterpolate, edgeinterpolate1, edgeinterpolate2\n%\n% Created by Ming Wang at Mar 29, 2011, M-lint modified at May 14, 2011.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif ~exist('elemType','var'), elemType = 'RT0'; end\n%% edge \nif size(elem,2) == 2 % the input elem is edge\n edge = elem;\nelse\n [tempvar,edge] = dofedge(elem);\nend\nNE = size(edge,1);\nedgeVec = node(edge(:,2),:) - node(edge(:,1),:);\nnVec = zeros(NE,2);\nnVec(:,1) = edgeVec(:,2); \nnVec(:,2) = -edgeVec(:,1);\n\n%% dof for RT0\n[lambda,weight] = quadpts1(4);\nnQuad = size(lambda,1);\nuI = zeros(NE,1);\nfor i = 1:nQuad\n pxy = lambda(i,1)*node(edge(:,1),:)+lambda(i,2)*node(edge(:,2),:);\n flux = u(pxy);\n uI = uI + weight(i)*dot(flux,nVec,2); \nend\n\n%% dof for BDM1\nif strcmp(elemType,'BDM1')\n uI(NE+1:2*NE) = zeros(NE,1);\n for i = 1:nQuad\n pxy = lambda(i,1)*node(edge(:,1),:)+lambda(i,2)*node(edge(:,2),:);\n flux = u(pxy);\n uI(NE+1:2*NE) = uI(NE+1:2*NE)+ ...\n weight(i)*3*(lambda(i,1)-lambda(i,2))*dot(flux,nVec,2); \n end\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/iFEM/afem/faceinterpolate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.6873497086597493}} {"text": "function [ff,f]=v_lpccc2ff(cc,np,nc,c0)\n%V_LPCCC2FF Convert complex cepstrum to complex spectrum FF=(CC,NP,NC)\n%\n% Inputs: cc(nf,n) Complex ceptral coefficients excluding c(0), one frame per row\n% np Size of output spectrum is np+1 [n]\n% Alternatively, a vector of output frequencies in the range 0 to 0.5\n% nc Number of cepstral coefficients to use [np or, if np is a vector, n]\n% Set nc=-1 to use n coefficients\n% c0(nf,1) Cepstral coefficient c(0) [0]\n%\n% Outputs: ff(nf,np+2) Complex spectrum from DC to Nyquist\n% f(1,np+2) Normalized frequencies (0 to 0.5)\n%\n% The \"complex cepstral coefficients\", cc(n), are the inverse discrete-time Fourier transform\n% of the log of the complex-valued spectrum. The cc(n) are real-valued and, for n<0, cc(n)=0.\n% The \"real cepstral coeffcients\", rc(n), are the inverse discrete-time Fourier transform\n% of the log of the magnitude spectrum; rc(0)=cc(0) and rc(n)=0.5*cc(n) for n~=0. \n% For highest speed, choose np+1 to be a power of 2.\n\n% Copyright (C) Mike Brookes 2014\n% Version: $Id: v_lpccc2ff.m 10865 2018-09-21 17:22:45Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\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 can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n[nf,mc]=size(cc);\nif nargin<2 || ~numel(np)\n if nargout\n np=mc;\n else\n np=128;\n end\nend\nif nargin>=3 && numel(nc)==1 && nc==-1 nc=mc; end\nif nargin<4 || ~numel(c0) c0=zeros(nf,1); end\nif numel(np)>1 || np(1)<1\n if nargin<3 || ~numel(nc) nc=mc; end\n f=np(:)';\n if nc==mc\n ff=exp([c0 cc]*exp(-2i*pi*(0:mc)'*f));\n else\n ff=exp([c0 lpccc2cc(cc,nc)]*exp(-2i*pi*(0:nc)'*f));\n end\nelse\n if nargin<3 || ~numel(nc) nc=np; end\n if nc==mc\n ff=exp(v_rfft([c0 cc].',2*np).');\n else\n ff=exp(v_rfft([c0 v_lpccc2cc(cc,nc)].',2*np).');\n end\n f=linspace(0,0.5,np+1);\nend\nif ~nargout\n subplot(2,1,2);\n plot(f,unwrap(angle(ff.')));\n xlabel('Normalized frequency f/f_s');\n ylabel('Phase (rad)');\n subplot(2,1,1);\n plot(f,db(abs(ff.')));\n xlabel('Normalized frequency f/f_s');\n ylabel('Gain (dB)');\nend\n\n", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_lpccc2ff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.6873497029870781}} {"text": "%% Test Problems for CLP\nclc\nclear\n\n%% CLP Options Function\nclc\nclpset\n\na = clpset\n\n%% LP1 [-31.4]\nclc\nf = -[6 5]';\nA = sparse([1,4; 6,4; 2, -5]); \nrl = -Inf(3,1);\nru = [16;28;6]; \nlb = [0;0];\nub = [10;10];\n\nopts = [];\nopts.display = 1;\nopts.maxiter = 15;\nopts.algorithm = 'automatic';\nopts.numThreads = 4;\n[x,ff,e,i,lambda] = clp([],f,A,rl,ru,lb,ub,opts);\n\n%% LP1 with redundant row [-31.4]\nclc\nf = -[6 5]';\nA = sparse([1,4; 2 8; 6,4; 2, -5]); \nrl = -Inf(4,1);\nru = [16;32;28;6]; \nlb = [0;0];\nub = [10;10];\n\nopts = [];\nopts.display = 1;\nopts.maxiter = 15;\nopts.algorithm = 3;\n% opts.writeprob = 'prob.dat-s';\n% opts.writesol = 'sol.dat-s';\n[x,ff,e,i,lambda] = clp([],f,A,rl,ru,lb,ub,opts)\n\n%% LP2 [2]\nclc\nf = [8,1]';\nA = sparse([-1,-2;1,-4;3,-1;1,5;-1,1;-1,0;0,-1]); \nrl = -Inf(7,1);\nru = [-4,2,21,39,3,0,0]';\n\n[x,ff,e,i,lambda] = clp([],f,A,rl,ru)\n\n%% LP3 [-3.75]\nclc\nf = -[-1, 2]';\nA = sparse([2, 1;-4, 4]);\nrl = -Inf(2,1);\nru = [5, 5]';\n\n[x,ff,e,i,lambda] = clp([],f,A,rl,ru)\n\n%% LP4 [-97.5]\nclc\nf = -[1 2 3]';\nA = sparse([-1,1,1; 1,-3,1]);\nb = [20,30]';\nAeq = sparse([1 1 1]);\nA = [A;Aeq;-Aeq];\nbeq = 40;\nru = [b;beq;-beq];\nrl = -Inf(size(ru));\nlb = [0 0 0]';\nub =[40 inf inf]';\n\n[x,ff,e,i,lambda] = clp([],f,A,rl,ru,lb,ub,opts)\n\n%% LP5 [-30, no linear constraints]\nclc\nf = -[1, 2]';\nlb = [0;0];\nub = [10;10];\n\n[x,ff,e,i,lambda] = clp([],f,[],[],[],lb,ub,opts)\n\n\n%% LP6 infeasible\nclc\n%Objective & Constraints\nf = -[6 5]';\nA = sparse([1,4; 6,4; 2, -5]); \nrl = -Inf(3,1);\nru = [16;28;-30]; \nlb=[0;0];\nub=[10;10];\n\nopts = [];\nopts.display = 1;\nopts.maxiter = 150;\nopts.algorithm =5;\n\n[x,ff,e,i,lambda] = clp([],f,A,rl,ru,lb,ub,opts)\n\n%% LP7 unbounded\nclc\nf = -[1, 2]';\nlb = [0;0];\nub = [10;Inf];\n\nopts = [];\nopts.display = 1;\nopts.maxiter = 150;\nopts.algorithm = 0;\n\n[x,ff,e,i,lambda] = clp([],f,[],[],[],lb,ub,opts)\n\n%% LARGE LP\nclc\nclear clp\nprob = coinRead('maros-r7.mps');\n\nopts = [];\nopts.display = 1;\nopts.maxiter = 10000;\nopts.doPresolve = 1;\nopts.algorithm = 5;\nopts.numThreads = 4;\n\n[~,ff,e,i,lambda] = clp(prob.H,prob.f,prob.A,prob.rl,prob.ru,prob.lb,prob.ub,opts)\n\n%% AMPL Problem LP\nclc\nclear clp\nprob = coinRead('prod.mps');\n\nopts = [];\nopts.display = 1;\nopts.maxiter = 10000;\nopts.algorithm = 0;\nopts.doPresolve = 1;\nopts.numThreads = 1;\n\n[~,ff,e,i,lambda] = clp(prob.H,prob.f,prob.A,prob.rl,prob.ru,prob.lb,prob.ub,opts)\n\n%% LP No Presolve Dual \nclc\nf = -[-1, 2]';\nA = sparse([2, 1;-4, 4]);\nrl = -Inf(2,1);\nru = [5, 5]';\n\nopts = [];\nopts.display = 1;\nopts.maxiter = 15;\nopts.algorithm = 0;\nopts.doPresolve = 0;\nopts.numThreads = 1;\n[x,ff,e,i,lambda] = clp([],f,A,rl,ru,[],[],opts);\n\n%% LP Empty after Presolve Abc\nclc\nf = -[-1, 2]';\nA = sparse([2, 1;-4, 4]);\nrl = -Inf(2,1);\nru = [5, 5]';\n\nopts = [];\nopts.display = 1;\nopts.algorithm = 0;\nopts.numThreads = 2;\n[x,ff,e,i,lambda] = clp([],f,A,rl,ru,[],[],opts);\n\n%% QP1 -2.83333333301227;\nclc\nH = speye(3);\nf = -[2 3 1]';\nA = sparse([1 1 1;3 -2 -3; 1 -3 2]); \nb = [1;1;1]; \n\nopts = [];\nopts.display = 2;\nopts.algorithm = 5;\nopts.numThreads = 1;\n\n% prob=optiprob('qp',H,f,'ineq',A,b);\n% coinWrite(prob,'testqp.mps')\n\n[x,fval,e,i,l] = clp(H,f,A,-Inf(size(b)),b,[],[],opts) \n\n%% QP2 -8.22222220552525 \nclc\nH = (sparse([1 -1; -1 2]));\nf = -[2 6]';\nA = sparse([1 1; -1 2; 2 1]);\nb = [2; 2; 3]; \nlb = [0;0];\n\nopts = [];\nopts.display = 1;\nopts.algorithm = 3;\nopts.objbias = 10;\n\n[x,fval,e,i,l] = clp(tril(H),f,A,-Inf(size(b)),b,[],[],opts) \n\n%% QP3 -6.41379310344827\nH = tril(sparse([1 -1; -1 2]));\nf = -[2 6]';\nA = sparse([1 1; -1 2; 2 1]);\nb = [2; 2; 3];\nAeq = sparse([1 1.5]);\nbeq = 2;\nA = [A;Aeq]; rl = [zeros(size(b));beq]; ru = [b;beq];\nlb = [0;0];\nub = [10;10]; \n\nopts = [];\nopts.display = 2;\n[x,fval,e,i,l] = clp(H,f,A,rl,ru,lb,ub,opts) \n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Test Problems/Development/test_clp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.6873497003721628}} {"text": "function pass = test_cumsum(pref)\n\nif ( nargin == 0 )\n pref = chebfunpref; \nend\ntol = 100*pref.cheb3Prefs.chebfun3eps;\n\n% Check cumsum on cube domain\n[x, y, z] = cheb.xyz;\n\npass(1) = norm(cumsum(x) - .5*(x.^2-1)) < tol;\npass(2) = norm(cumsum(x, 1) - .5*(x.^2-1)) < tol;\npass(3) = norm(cumsum(x, 2) - x.*(y+1)) < tol;\npass(4) = norm(cumsum(x, 3) - x.*(z+1)) < tol;\n\npass(5) = norm(cumsum(y) - y.*(x+1)) < tol;\npass(6) = norm(cumsum(y, 1) - y.*(x+1)) < tol;\npass(7) = norm(cumsum(y, 2) - .5*(y.^2-1)) < tol;\npass(8) = norm(cumsum(y, 3) - y.*(z+1)) < tol;\n\npass(9) = norm(cumsum(z) - z.*(x+1)) < tol;\npass(10) = norm(cumsum(z, 1) - z.*(x+1)) < tol;\npass(11) = norm(cumsum(z, 2) - z.*(y+1)) < tol;\npass(12) = norm(cumsum(z, 3) - .5*(z.^2-1)) < tol;\n\n% Check cumsum on rectangular box domain\nx = chebfun3(@(x,y,z) x, [-1.1 2 -0.2 3 5 6]);\ny = chebfun3(@(x,y,z) y, [-1.1 2 -0.2 3 5 6]);\nz = chebfun3(@(x,y,z) z, [-1.1 2 -0.2 3 5 6]);\n\npass(13) = norm(cumsum(x) - .5*(x.^2-(-1.1)^2)) < tol;\npass(14) = norm(cumsum(x, 1) - .5*(x.^2-(-1.1)^2)) < tol;\npass(15) = norm(cumsum(x, 2) - x.*(y+0.2)) < tol;\npass(16) = norm(cumsum(x, 3) - x.*(z-5)) < tol;\n\npass(17) = norm(cumsum(y) - y.*(x+1.1)) < tol;\npass(18) = norm(cumsum(y, 1) - y.*(x+1.1)) < tol;\npass(19) = norm(cumsum(y, 2) - .5*(y.^2-(-0.2)^2)) < tol;\npass(20) = norm(cumsum(y, 3) - y.*(z-5)) < tol;\n\npass(21) = norm(cumsum(z) - z.*(x+1.1)) < tol;\npass(22) = norm(cumsum(z, 1) - z.*(x+1.1)) < tol;\npass(23) = norm(cumsum(z, 2) - z.*(y+0.2)) < tol;\npass(24) = norm(cumsum(z, 3) - .5*(z.^2-5^2)) < tol;\n\n% Check that a triple cumsum is a cumsum3\nf = sin((x-.1).*(y+.1).*(z+.1));\npass(25) = norm(cumsum(cumsum(cumsum(f), 2), 3) - cumsum3(f)) < tol; \npass(26) = norm(cumsum(cumsum(cumsum(f, 1), 2), 3) - cumsum3(f)) < tol; \n\n% Look in one direction and make sure we get the right thing:\nf = chebfun(@(x) exp(x));\nf3 = chebfun3(@(x,y,z) exp(x));\ng = cumsum(f);\ng3 = cumsum(f3);\ng3x = g3(:,0,.3);\npass(27) = norm(g3x-g) < tol;\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun3/test_cumsum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6873451122150743}} {"text": "function SD = SD_evaluation(F)\n[m,n]=size(F);\nu=mean(mean(F));\nSD=sqrt(sum(sum((F-u).^2))/(m*n));\nend\n", "meta": {"author": "Linfeng-Tang", "repo": "Image-Fusion", "sha": "9e6159f4a09ece3d3a1da6f9ca444436b7012c64", "save_path": "github-repos/MATLAB/Linfeng-Tang-Image-Fusion", "path": "github-repos/MATLAB/Linfeng-Tang-Image-Fusion/Image-Fusion-9e6159f4a09ece3d3a1da6f9ca444436b7012c64/General Evaluation Metric/Evaluation/SD_evaluation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850021922959, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6873450974067218}} {"text": "function [fL] = bruteloglike(vValues,time_as)\n % bruteloglike calculates the log likelihood function for the modeled aftershock sequence and the maximum likelihood estimate for k, c and p\n %\n % [fL] = bruteloglike(vValues,time_as);\n % -------------------------------------------------------------\n % Reference: Ogata, Estimation of the parameters in the modified Omori formula\n % for aftershock sequences by the maximum likelihood procedure, J. Phys. Earth, 1983\n % (Formula 6)\n %\n % J. Woessner\n % updated: 29.07.03\n\n p = vValues(1);\n c = vValues(2);\n k = vValues(3);\n\n % Setting start end end time\n fTstart = min(time_as);\n fTend = max(time_as);\n\n if p ~= 1\n fAcp = ((fTend+c).^(1-p)-(fTstart+c).^(1-p))./(1-p);\n %cumnr_model = k/(p-1)*(c^(1-p)-(c+time_as(i)).^(1-p)); % integrated form of MOL\n else\n fAcp = log(fTend+c)-log(fTstart+c);\n %cumnr_model = k*log(time_as(i)/c+1); % integrated form of MOL\n end\n % rms = (sum((i-cumnr_model).^2)/length(i))^0.5; % RMS between observed data and MOL\n % Log likelihood\n nNumEvents = length(time_as);\n fL = -(nNumEvents*log(k)-p*sum(log(time_as+c))-k*fAcp);\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/afterrate/bruteloglike.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6873375805383762}} {"text": "function [ r, s, area ] = node_reference_t10 ( )\n\n%*****************************************************************************80\n%\n%% NODE_REFERENCE_T10 returns the basis nodes for a 10 node triangle.\n%\n% Reference Element T10:\n%\n% |\n% 1 10\n% | |\\\n% | | \\\n% | 8 9\n% | | \\\n% S | \\\n% | 5 6 7\n% | | \\\n% | | \\\n% 0 1--2--3--4\n% |\n% +--0----R---1-->\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% Parameters:\n%\n% Output, real R(10), S(10), the coordinates of the basis nodes.\n%\n% Output, real AREA, the area of the element.\n%\n r(1) = 0.0;\n s(1) = 0.0;\n\n r(2) = 1.0 / 3.0;\n s(2) = 0.0;\n\n r(3) = 2.0 / 3.0;\n s(3) = 0.0;\n\n r(4) = 1.0;\n s(4) = 0.0;\n\n r(5) = 0.0;\n s(5) = 1.0 / 3.0;\n\n r(6) = 1.0 / 3.0;\n s(6) = 1.0 / 3.0;\n\n r(7) = 2.0 / 3.0;\n s(7) = 1.0 / 3.0;\n\n r(8) = 0.0;\n s(8) = 2.0 / 3.0;\n\n r(9) = 1.0 / 3.0;\n s(9) = 2.0 / 3.0;\n\n r(10) = 0.0;\n s(10) = 1.0;\n\n area = 0.5;\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/fem2d_pack/node_reference_t10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6872599977942228}} {"text": "function cout=comp_col2diag(cin);\n%COMP_COL2DIAG transforms columns to diagonals (in a special way)\n%\n% This function transforms the first column to the main diagonal. The\n% second column to the first side-diagonal below the main diagonal and so\n% on. \n% \n% This way fits well the connection of matrix and spreading function, see\n% spreadfun.\n%\n% This function is its own inverse.\n\n% AUTHOR : Peter L. S\u00f8ndergaard.\n% TESTING: OK\n% REFERENCE: OK\n\nL=size(cin,1);\ncout=zeros(L,assert_classname(cin));\n\njj=(0:L-1).';\nfor ii=0:L-1\n cout(ii+1,:)=cin(ii+1,mod(ii-jj,L)+1);\nend;\n\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/comp/comp_col2diag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.6872599803050327}} {"text": "function prob_test079 ( )\n\n%*****************************************************************************80\n%\n%% TEST079 tests GENLOGISTIC_CDF, GENLOGISTIC_CDF_INV, GENLOGISTIC_PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST079\\n' );\n fprintf ( 1, ' For the Generalized Logistic PDF:\\n' );\n fprintf ( 1, ' GENLOGISTIC_PDF evaluates the PDF.\\n' );\n fprintf ( 1, ' GENLOGISTIC_CDF evaluates the CDF;\\n' );\n fprintf ( 1, ' GENLOGISTIC_CDF_INV inverts the CDF.\\n' );\n\n a = 1.0;\n b = 2.0;\n c = 3.0;\n\n check = genlogistic_check ( a, b, c );\n\n if ( ~check );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST079 - Fatal error!\\n' );\n fprintf ( 1, ' The parameters are not legal.\\n' );\n return\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' PDF parameter A = %14f\\n', a );\n fprintf ( 1, ' PDF parameter B = %14f\\n', b );\n fprintf ( 1, ' PDF parameter C = %14f\\n', c );\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X PDF CDF CDF_INV\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : 10\n\n [ x, seed ] = genlogistic_sample ( a, b, c, seed );\n\n pdf = genlogistic_pdf ( x, a, b, c );\n\n cdf = genlogistic_cdf ( x, a, b, c );\n\n x2 = genlogistic_cdf_inv ( cdf, a, b, c );\n\n fprintf ( 1, ' %14f %14f %14f %14f\\n', x, pdf, cdf, x2 );\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/prob_test079.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.6872599787055365}} {"text": "function Test_trustregions\n\n \n % We attempt to compute an intrinsic mean of subspaces, that is, of\n % points on the Grassmann manifold. Let there be m subspaces of\n % dimension p embedded in R^n. We generate random data for our tests:\n % X is a random nxpxm matrix such that each slice of size nxp is an\n % orthonormal basis of a subspace.\n n = 50;\n p = 3;\n m = 100;\n Gr_multi = grassmannfactory(n, p, m);\n X = Gr_multi.rand();\n\n % Our search space is the Grassmann manifold: we want to locate one\n % point on the Grassmannian that \"averages\" the m given points.\n Gr = grassmannfactory(n, p);\n\n % The cost is the sum of squared Riemannian distances to the data\n % points.\n function f = cost(x)\n f = 0;\n for i = 1 : m\n xi = X(:, :, i);\n f = f + Gr.dist(x, xi)^2;\n end\n f = f/(2*m);\n end\n\n % The gradient is based on the Riemannian logarithmic map at the\n % current point, which gives tangent vectors at x pointing towards the\n % data points.\n function g = grad(x)\n g = Gr.zerovec(x);\n for i = 1 : m\n xi = X(:, :, i);\n g = g - Gr.log(x, xi);\n end\n g = g / m;\n end\n\n % Setup the problem structure, with the manifold M and the cost and its\n % gradient. Notice that we do not provide a Hessian, because it's\n % rather tricky to compute.\n problem.M = Gr;\n problem.cost = @cost;\n problem.grad = @grad;\n% problem.hess = @(x, xdot) Gr.zerovec(x) ;% * Gr.norm(x, xdot); \n \n % For peace of mind, check that the gradient is correct.\n % checkgradient(problem);\n % pause;\n \n % As a simple minded initial guess, choose one of the data points.\n x0 = X(:, :, 1);\n \n % Setup some options for the trustregions algorihm\n options.tolgradnorm = 1e-16;\n options.maxtime = 30;\n options.maxiter = 200;\n options.verbosity = 2;\n options.debug = 0;\n options.rho_regularization = 1e3;\n \n % We did not specify a Hessian, but use trustregions anyway. Hence, the\n % Hessian will be approximated, and we should be warned about it. To\n % disable the warning, you may execute this command:\n warning('off', 'manopt:getHessian:approx');\n \n [x, cost_x, info] = trustregions(problem, x0, options); %#ok\n \n xdata = [info.time];\n ydata = [info.gradnorm];\n semilogy(xdata, ydata, '.-');\n xlabel('Time [s]');\n ylabel('Gradient norm');\n hold on;\n radius_change = [0 sign(diff([info.Delta]))];\n text(xdata(radius_change > 0), ydata(radius_change > 0)/2, '+');\n text(xdata(radius_change < 0), ydata(radius_change < 0)/2, '-');\n text(xdata, ydata*2, num2str([info.numinner]'));\n hold off;\n \n % info\n % keyboard;\n\nend", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/tests/Test_trustregions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6872139551218416}} {"text": "function taulist = InverseDynamics(thetalist, dthetalist, ddthetalist, ...\n g, Ftip, Mlist, Glist, Slist)\n% *** CHAPTER 8: DYNAMICS OF OPEN CHAINS ***\n% Takes thetalist: n-vector of joint variables,\n% dthetalist: n-vector of joint rates,\n% ddthetalist: n-vector of joint accelerations,\n% g: Gravity vector g,\n% Ftip: Spatial force applied by the end-effector expressed in frame \n% {n+1},\n% Mlist: List of link frames {i} relative to {i-1} at the home \n% position,\n% Glist: Spatial inertia matrices Gi of the links,\n% Slist: Screw axes Si of the joints in a space frame, in the format\n% of a matrix with the screw axes as the columns.\n% Returns taulist: The n-vector of required joint forces/torques.\n% This function uses forward-backward Newton-Euler iterations to solve the \n% equation:\n% taulist = Mlist(thetalist) * ddthetalist + c(thetalist, dthetalist) ...\n% + g(thetalist) + Jtr(thetalist) * Ftip\n% Example Input (3 Link Robot):\n% \n% clear; clc;\n% thetalist = [0.1; 0.1; 0.1];\n% dthetalist = [0.1; 0.2; 0.3];\n% ddthetalist = [2; 1.5; 1];\n% g = [0; 0; -9.8];\n% Ftip = [1; 1; 1; 1; 1; 1];\n% M01 = [[1, 0, 0, 0]; [0, 1, 0, 0]; [0, 0, 1, 0.089159]; [0, 0, 0, 1]];\n% M12 = [[0, 0, 1, 0.28]; [0, 1, 0, 0.13585]; [-1, 0 ,0, 0]; [0, 0, 0, 1]];\n% M23 = [[1, 0, 0, 0]; [0, 1, 0, -0.1197]; [0, 0, 1, 0.395]; [0, 0, 0, 1]];\n% M34 = [[1, 0, 0, 0]; [0, 1, 0, 0]; [0, 0, 1, 0.14225]; [0, 0, 0, 1]];\n% G1 = diag([0.010267, 0.010267, 0.00666, 3.7, 3.7, 3.7]);\n% G2 = diag([0.22689, 0.22689, 0.0151074, 8.393, 8.393, 8.393]);\n% G3 = diag([0.0494433, 0.0494433, 0.004095, 2.275, 2.275, 2.275]);\n% Glist = cat(3, G1, G2, G3);\n% Mlist = cat(3, M01, M12, M23, M34); \n% Slist = [[1; 0; 1; 0; 1; 0], ...\n% [0; 1; 0; -0.089; 0; 0], ...\n% [0; 1; 0; -0.089; 0; 0.425]];\n% taulist = InverseDynamics(thetalist, dthetalist, ddthetalist, g, ...\n% Ftip, Mlist, Glist, Slist)\n% \n% Output:\n% taulist =\n% 74.6962\n% -33.0677\n% -3.2306\n\nn = size(thetalist, 1);\nMi = eye(4);\nAi = zeros(6, n);\nAdTi = zeros(6, 6, n + 1);\nVi = zeros(6, n + 1);\nVdi = zeros(6, n + 1);\nVdi(4: 6, 1) = -g;\nAdTi(:, :, n + 1) = Adjoint(TransInv(Mlist(:, :, n + 1)));\nFi = Ftip;\ntaulist = zeros(n, 1);\nfor i=1: n \n Mi = Mi * Mlist(:, :, i);\n Ai(:, i) = Adjoint(TransInv(Mi)) * Slist(:, i); \n AdTi(:, :, i) = Adjoint(MatrixExp6(VecTose3(Ai(:, i) ...\n * -thetalist(i))) * TransInv(Mlist(:, :, i))); \n Vi(:, i + 1) = AdTi(:, :, i) * Vi(:, i) + Ai(:, i) * dthetalist(i);\n Vdi(:, i + 1) = AdTi(:, :, i) * Vdi(:, i) ...\n + Ai(:, i) * ddthetalist(i) ...\n + ad(Vi(:, i + 1)) * Ai(:, i) * dthetalist(i); \nend\nfor i = n: -1: 1\n Fi = AdTi(:, :, i + 1)' * Fi + Glist(:, :, i) * Vdi(:, i + 1) ...\n - ad(Vi(:, i + 1))' * (Glist(:, :, i) * Vi(:, i + 1));\n taulist(i) = Fi' * Ai(:, i);\nend\nend", "meta": {"author": "ShuoYangRobotics", "repo": "QuadrupedSim", "sha": "8427715395b63bddb77329e66f7484e529998445", "save_path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim", "path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim/QuadrupedSim-8427715395b63bddb77329e66f7484e529998445/mr/InverseDynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.687213938954609}} {"text": "%% RATE OF CONVERGENCE OF ADAPTIVE FINITE ELEMENT METHOD USING WG ELEMENT\n%\n% This example is to show the rate of convergence of the lowest order\n% finite element approximation of the second order elliptic equation.\n%\n% # Lshape problem.\n% # Kellogg problem.\n\nclear all; close all;\n%% Kellogg problem\n[node,elem] = squaremesh([-1 1 -1 1], 0.5);\nbdFlag = setboundary(node,elem,'Dirichlet');\npde = Kelloggdata;\noption.L0 = 1;\noption.maxIt = 100;\noption.maxN = 1e4;\noption.theta = 0.2;\noption.plotflag = 1;\nerr = afemPoisson(node,elem,pde,bdFlag,option);\nfigure;\nshowrate2(err.N,err.H1,40,'k-*','||Du-Du_h||',err.N,err.eta,40,'-+','eta');\nlatexerrtable(err.N,[err.H1 err.eta])\n\n%% Lshape problem\n[node,elem] = squaremesh([-1,1,-1,1],1);\n[node,elem] = delmesh(node,elem,'x>0 & y<0');\nbdFlag = setboundary(node,elem,'Dirichlet');\npde = Lshapedata;\nformat shorte\noption.L0 = 1;\noption.maxIt = 25;\noption.printlevel = 1;\n% option.elemType = 'WG';\noption.plotflag = 1;\nerr = afemPoisson(node,elem,pde,bdFlag,option);", "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/afemrate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544448, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6871678163360172}} {"text": "function [C, S] = fcs(x)\n%FCS Computes Fresnel integrals.\n%[C, S] = fcs(x) returns Fresnel integrals C ans S for argument x,\n% x must be double and real.\n% F = fcs(x) returns complex F = C+i*S\n% \n% Algorithm:\n% This function uses an improved method for computing Fresnel integrals\n% with an error of less then 1x10-9, described in:\n% \n% Klaus D. Mielenz, Computation of Fresnel Integrals. II\n% J. Res. Natl. Inst. Stand. Technol. 105, 589 (2000), pp 589-590\n% \n% Copyright (c) 2002 by Peter L. Volegov (volegov@unm.edu) \n% All Rights Reserved. \n\nerror('You need to compile fcs.c to a mex file for your platform.');\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/6580-fresnel-integrals/fcs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6871678092377791}} {"text": "% FORMAT:\n%\n% sampval = ms2sample(timems, fs, rounding, offset)\n%\n% INPUTS:\n%\n% timesam - time value in samples\n% fs - sample rate\n%\n% Optional inputs:\n%\n% rounding - 1 means round the result {default}, 0 means do not round\n% offset - offset time in milliseconds (you can use sample2ms recursively here). Default 0\n%\n% OUTPUT:\n%\n% sampval - time in milliseconds\n%\n% EXAMPLES:\n%\n% 1) For a time serie recorded from 0 to 5 secs, at fs=500 sps, get the time in ms for the sample # 337.\n%\n% msval = sample2ms(337, 500)\n% \n% msval =\n% \n% 674\n%\n% 2) For a time serie recorded from -1 to 5 secs, at fs=500 sps, get the absolute time in ms for the sample # 337.\n%\n% msval = sample2ms(337, 500, 0, sample2ms(500,500))\n% \n% msval =\n% \n% 1674\n%\n%\n% Author: Javier Lopez-Calderon\n% Center for Mind and Brain\n% University of California, Davis,\n% Davis, CA\n% 2013\n\nfunction msval = sample2ms(timesam, fs, rounding, offset)\nif nargin<1\n help sample2ms\n return\nend\nif nargin<4\n offset = 0;\nend\nif nargin<3\n rounding = 1;\nend\nif nargin<2\n error('Two inputs are requiered at least.')\nend\nmsval = offset + 1000*timesam/fs;\nif rounding\n msval = round(msval);\nend", "meta": {"author": "ucdavis", "repo": "erplab", "sha": "e4f66f7a512c4dee2f7596982318e44bb1b72644", "save_path": "github-repos/MATLAB/ucdavis-erplab", "path": "github-repos/MATLAB/ucdavis-erplab/erplab-dd2f60aa41b01c866fcec342efafc48323523cc2/functions/sample2ms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220294, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6871678002510353}} {"text": "%test script fgg_2D_experiment.m for the 2D NFFT based on Fast Gaussian\n%Gridding.\n%\n%NOTE: In order for this FGG_2D to work, the C \n%file \"FGG_Convolution2D.c\" must be compiled into a Matlab executable\n%(cmex) with the following command: mex FGG_Convolution2D.c\n%\n%Code by (send correspondence to):\n%Matthew Ferrara, Research Mathematician\n%AFRL Sensors Directorate Innovative Algorithms Branch (AFRL/RYAT)\n%Matthew.Ferrara@wpafb.af.mil\n\nclear all;\nclose all;\n%clc\n%path(path, './nfftde');%NFFT mex files from Potts, et al.\n\n% make an \"image\"\n%Note for even lengths, the Nfft routine defines the image-space origin\n% at pixel location [Nx/2 + 1, Ny/2 + 1].\n% Convention: x counts down rows, y counts L to R columns.\nN=16;%even length assumed below...tedious to generalize...\nz = zeros(N,N);%\n%Make a smiley face:\nz(N/2+3,N/2-1 : N/2+1 ) = 1;\nz(N/2+2,N/2-2 ) = 1;\nz(N/2+2,N/2+2 ) = 1;\nz(N/2-1,N/2-1) = 1;\nz(N/2+1,N/2) = 1;\nz(N/2-1,N/2+1) = 1;\n%imagesc(z)\n\nN=[N,N];\nimg=double(z);\n% Now, let's compute a matlab DFT in d dimensions using the \"nfft\" command.\n% Note, use fftshifts to match indexing convention as used above in Pott's\n% nfft.\ndata=fftshift(ifftn(ifftshift(img)));\nDFTout = fftshift(fftn(ifftshift(data),N));\nz=z(:);\n\n% We need knots on [-1/2, 1-1/Nx]x[-1/2, 1-1/Ny] as fundamental period.\n% make square grid of knots for exact comparison to fft\ntmpx = linspace(-1/2,1/2 -1/N(1), N(1));% tmpx(end)=[];\ntmpy = linspace(-1/2,1/2 -1/N(2), N(2));% tmpy(end)=[];\n\n%this creates N+1 points, then discards point at +0.5.\n%store my K knots as a d-by-K matrix (d=2 dimension here)\n%...following four lines could be cleverly vectorized, avoiding loop.\n[Y,X]=meshgrid(tmpy,tmpx);\n\n\nknots=[X(:),Y(:)];\n\nNx=N(1);\nNy=N(2);\n%set the desired number of digits of accuracy desired from the NUFFT\n%routine:\nDesired_accuracy = 6;%6=single precision, 12=double precision.\ntic\nMattOut_Gauss=FGG_2d_type1(data(:),knots,[Nx,Ny],Desired_accuracy);\nimagesc(abs(MattOut_Gauss))\ncolorbar\ntitle('(Type-I Fast Gaussian Gridding) NFFT output')\ndisp(['NUFFT evaluated in ',num2str(toc),' seconds'])\nMattOut_t2=iFGG_2d_type2(MattOut_Gauss,knots,Desired_accuracy);\nMattOut_Gauss=FGG_2d_type1(MattOut_t2(:),knots,[Nx,Ny],Desired_accuracy);\nfigure\nimagesc(abs(MattOut_Gauss))\ncolorbar\ntitle('(Type-I Fast Gaussian Gridding) NFFT output from Type-II-generated data')\nnorm(MattOut_t2-z(:))\n\nfigure\nimagesc(abs(img-MattOut_Gauss))\ncolorbar\ntitle('Error between DFT and NFFT')\nMean_Error=mean(abs(MattOut_Gauss(:)-DFTout(:)))", "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/25135-nufft-nfft-usfft/NUFFT_code/NUFFT_code/fgg_2D_experiment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6871636250339284}} {"text": "% \"example_nufft1_reverse.m\"\n% This m-file is an example of applying the NUFFT method \"in reverse,\"\n% meaning that you have a nonuniformly-sampled signal spectrum in hand\n% and you want to try to \"compute its inverse Fourier transform\"\n% to get uniform set of signal samples. In the nomenclature of the 1999\n% SIAM J Sci. Comput. paper by Nguyen and Liu, this is \"Problem 1.\"\n% (It is somewhat related to MRI reconstruction by gridding.)\n% Before doing this, you should ask yourself if that is *really*\n% what you want to do. In most inverse problems, I think it is NOT\n% what we should do, as argued in the T-SP paper on this method.\n% Instead, we should solve the inverse problem *iteratively*, using\n% the NUFFT method (and its adjoint) each iteration.\n% Furthermore, the min-max optimality of the NUFFT method was only\n% established for the \"forward direction:\" going from uniform signal\n% samples to nonuniform frequency samples.\n% (You can replace time and frequency in the above discussion.)\n% Anyway, let's try it here and see how it works...\n\n%\n% synthesize some spectral data that is nonuniformly spaced\n%\nNo = 2^7;\t\t\t\t% number of frequency samples\nrng(0)\nom = 2*pi*sort(rand(No,1)-0.5);\t\t% random frequency samples on [-pi,pi ]\n%om = 2*pi*[-No/2:No/2-1]'/No;\t\t% test with uniform samples\n\n% a spectrum with periodic components, hopefully visible in other domain\nX = inline('2 + 2*sin(om*10) + 4*cos(15*om) + 4*cos(20*om)', 'om');\nXm = X(om);\n\n%\n% go to the time domain the \"exact\" (slow) DTFT way.\n% this implements essentially equation (1) in Nguyen and Liu (1999)\n%\nN1 = 2^6;\t\t% # of time samples\nn = [0:N1-1]'-N1/2;\t% time sample locations\nxd = dtft2_adj(Xm, [om 0*om], N1, 1, [N1/2 0]);\n\n%\n% now do it the fast NUFFT way\n%\nif 1 || ~isvar('st')\t% create NUFFT structure\n\tJ = 5;\t\t% interpolation neighborhood\n\tK1 = N1*2;\t% two-times oversampling\n\tst = nufft_init(om, N1, J, K1, N1/2, 'minmax:kb');\nend\n\nxn = nufft_adj(Xm, st);\t% call ADJOINT to go \"in reverse\"\n\n%\n% compare slow exact to fast NUFFT\n%\nfigure(1), clf, pl=220;\nsubplot(pl+1)\noo = [-200:200]'/400*2*pi;\nplot(om, Xm, '.', oo, X(oo), '-')\nxlabel \\omega, ylabel X(\\omega), title 'Spectrum and samples'\n\nsubplot(pl+2)\nplot(n, real(xd), 'c.-', n, imag(xd), 'y.-')\nxlabel n, ylabel x[n], title 'Exact \"nonuniform FT\"'\n\nsubplot(pl+3)\nplot(n, real(xn), 'c.-', n, imag(xn), 'y.-')\nxlabel n, ylabel x[n], title 'Fast NUFFT adjoint'\n\nsubplot(pl+4)\nplot(n, real(xn-xd), 'c.-', n, imag(xn-xd), 'y.-')\nxlabel n, ylabel x[n], title 'Approximation Error (very small!)'\n\n\n%\n% ok fine, so if you look at figure 1 you see that\n% the NUFFT gives a great approximation to the \"exact\" formula\n% but is the result *really* what you wanted?\n% It seems that ideally the result should be 4 spikes with\n% no background junk. If we solved \"Problem 5\" in Nguyen and Liu,\n% then we should get that! This is how we have approached the\n% MRI reconstruction problem, as described in ../mri.\n%\n% For iterative 2D version, see ../example/mri_example.m\n\nreturn\n\n%\n% here is a different strategy: interpolate the nonuniform data\n% onto a uniform grid, then simply take the inverse FFT.\n% this didn't work so well because it is a lousy gridding method.\n% todo: need to put a better gridding method here!\n%\nok = [-N1/2:(N1/2-1)]'/N1*2*pi;\nXg = interp1(om, Xm, ok, 'linear', 'extrap');\nxg = fftshift(ifft(fftshift(Xg)));\n\n%xg = xg ./ nufft_sinc(n/N1).^2; % post-compensate?\n\nfigure(2), clf, pl=220;\nsubplot(pl+1)\nplot(n, real(xg), 'c.-', n, imag(xg), 'y.-')\nxlabel n, ylabel x[n], title 'Gridding \"reconstruction\"'\n\nXg = dtft1(xg, om, N1/2);\nXd = dtft1(xd/No, om, N1/2);\n\nsubplot(pl+2)\nplot(om, real(Xg), '.', om, real(Xm), '-')\nxlabel \\omega, ylabel X(\\omega), title ''\n\nsubplot(pl+3)\nplot(om, real(Xd), '.', om, real(Xm), '-')\nxlabel \\omega, ylabel X(\\omega), title ''\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/nufft/example_nufft1_reverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6871636084105535}} {"text": "function K = covNNone(hyp, x, z, i)\n\n% Neural network covariance function with a single parameter for the distance\n% measure. The covariance function is parameterized as:\n%\n% k(x^p,x^q) = sf2 * asin(x^p'*P*x^q / sqrt[(1+x^p'*P*x^p)*(1+x^q'*P*x^q)])\n%\n% where the x^p and x^q vectors on the right hand side have an added extra bias\n% entry with unit value. P is ell^-2 times the unit matrix and sf2 controls the\n% signal variance. The hyperparameters are:\n%\n% hyp = [ log(ell)\n% log(sqrt(sf2) ]\n%\n% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2010-09-10.\n%\n% See also COVFUNCTIONS.M.\n\nif nargin<2, K = '2'; return; end % report number of parameters\nif nargin<3, z = []; end % make sure, z exists\nxeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode\n\nn = size(x,1);\nell2 = exp(2*hyp(1));\nsf2 = exp(2*hyp(2));\n\nsx = 1 + sum(x.*x,2);\nif dg % vector kxx\n K = sx./(sx+ell2);\nelse\n if xeqz % symmetric matrix Kxx\n S = 1 + x*x';\n K = S./(sqrt(ell2+sx)*sqrt(ell2+sx)');\n else % cross covariances Kxz\n S = 1 + x*z'; sz = 1 + sum(z.*z,2);\n K = S./(sqrt(ell2+sx)*sqrt(ell2+sz)');\n end\nend\n\nif nargin<4 % covariances\n K = sf2*asin(K);\nelse % derivatives\n if i==1 % lengthscale\n if dg\n V = K;\n else\n vx = sx./(ell2+sx);\n if xeqz\n V = repmat(vx/2,1,n) + repmat(vx'/2,n,1);\n else \n vz = sz./(ell2+sz); nz = size(z,1);\n V = repmat(vx/2,1,nz) + repmat(vz'/2,n,1);\n end\n end\n K = -2*sf2*(K-K.*V)./sqrt(1-K.*K);\n elseif i==2 % magnitude\n K = 2*sf2*asin(K);\n else\n error('Unknown hyperparameter')\n end\nend", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/gpml/cov/covNNone.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.6871636064134731}} {"text": " function y = downsample3(x, m)\n%|function y = downsample3(x, m)\n%| downsample by averaging by integer factors\n%| m can be a scalar (same factor for both dimensions)\n%| or a 3-vector\n%| in\n%|\tx\t[nx ny nz]\n%|\tm\t[1] or [1 3]\n%| out\n%|\ty\t[nx/m ny/m nz/m]\n%| function modified to 3D space by: Taka Masuda\n\nif nargin == 1 && streq(x, 'test'), downsample3_test, return, end\nif nargin < 2, ir_usage, end\n\nif ndims(x) == 2\n\twarn('2d case')\n\tif numel(m) == 1, m = [m m 1]; end\n\tif numel(m) ~= 3, fail 'm not length 3?', end\n\ty = downsample2(x, m(1:2));\nreturn\nend\n\nif ndims(x) ~= 3\n\tfail('not 3d')\nend\n\nif numel(m) == 1\n\tm = m * ones(ndims(x),1);\nend\nif numel(m) ~= ndims(x), error 'bad m', end\n\n% downsample along each dimension\ny = downsample1(x, m(1));\ny = downsample1(permute(y, [2 1 3]), m(2));\ny = downsample1(permute(y, [3 2 1]), m(3)); % [3 1 2] order\ny = permute(y, [2 3 1]);\n\n\n% downsample1hide()\n% 1d down sampling of each column\nfunction y = downsample1hide(x, m)\n'ok'\nif m == 1, y = x; return; end\nn1 = floor(size(x,1) / m);\nn2 = size(x,2);\nn3 = size(x,3);\ny = zeros(n1,n2,n3);\nfor ii=0:m-1\n\ty = y + x(ii+[1:m:m*n1],:,:);\n\tticker(mfilename, ii+1, m)\nend\ny = y / m;\n\n\n% downsample3_test\nfunction downsample3_test\nx = [6 5 2];\nx = reshape(2*[1:prod(x)], x);\ndown = 2;\ny = downsample3(x, down);\nif down == 1\n\tjf_equal(y, x)\nelse\n\tjf_equal(y, [39 63; 43 67; 47 71])\nend\n\nif has_aspire\n\tfilex = [test_dir filesep 'testx.fld'];\n\tfiley = [test_dir filesep 'testy.fld'];\n\tfld_write(filex, x)\n\tdelete(filey)\n\tcom = ['op sample3 mean ' filey ' ' filex ' %d %d %d'];\n\tcom = sprintf(com, down, down, down);\n\tos_run(com)\n\tz = fld_read(filey);\n\tif ~isequal(y, z), error 'aspire/matlab mismatch', end\nend\n\nif 0 % big\n\tx = zeros(2.^[7 8 9]);\n\tcpu etic\n\ty = downsample3(x, 2);\n\tcpu etoc 'downsample3 time:'\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/utilities/downsample3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.6871395321775954}} {"text": "function b = r8cc_vxm ( m, n, nz_num, colptr, rowind, a, x )\n\n%*****************************************************************************80\n%\n%% R8CC_VXM multiplies a vector times a R8CC matrix.\n%\n% Discussion:\n%\n% The R8CC format is the double precision sparse compressed column\n% format. Associated with this format, we have an M by N matrix\n% with NZ_NUM nonzero entries. We construct the column pointer\n% vector COL of length N+1, such that entries of column J will be\n% stored in positions COL(J) through COL(J+1)-1. This indexing\n% refers to both the ROW and A vectors, which store the row indices\n% and the values of the nonzero entries. The entries of the\n% ROW vector corresponding to each column are assumed to be\n% ascending sorted.\n%\n% The R8CC format is equivalent to the MATLAB \"sparse\" format,\n% and the Harwell Boeing \"real unsymmetric assembled\" (RUA) format.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 September 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Iain Duff, Roger Grimes, John Lewis,\n% User's Guide for the Harwell-Boeing Sparse Matrix Collection,\n% October 1992\n%\n% Parameters:\n%\n% Input, integer M, the number of rows of the matrix.\n%\n% Input, integer N, the number of columns of the matrix.\n%\n% Input, integer NZ_NUM, the number of nonzero elements in A.\n%\n% Input, integer COLPTR(N+1), points to the first element of each column.\n%\n% Input, integer ROWIND(NZ_NUM), contains the row indices of the elements.\n%\n% Input, real A(NZ_NUM), the matrix.\n%\n% Input, real X(M), the vector to be multiplied.\n%\n% Output, real B(N), the product A'*X.\n%\n b(1:n) = 0.0;\n\n for j = 1 : n\n for k = colptr(j) : colptr(j+1) - 1\n i = rowind(k);\n b(j) = b(j) + a(k) * x(i);\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/linplus/r8cc_vxm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.6871157671399021}} {"text": "function X_rec = recoverData(Z, U, K)\n%RECOVERDATA Recovers an approximation of the original data when using the \n%projected data\n% X_rec = RECOVERDATA(Z, U, K) recovers an approximation the \n% original data that has been reduced to K dimensions. It returns the\n% approximate reconstruction in X_rec.\n%\n\n% You need to return the following variables correctly.\nX_rec = zeros(size(Z, 1), size(U, 1));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the approximation of the data by projecting back\n% onto the original space using the top K eigenvectors in U.\n%\n% For the i-th example Z(i,:), the (approximate)\n% recovered data for dimension j is given as follows:\n% v = Z(i, :)';\n% recovered_j = v' * U(j, 1:K)';\n%\n% Notice that U(j, 1:K) is a row vector.\n% \n\n\n\n% =============================================================\n\nend\n", "meta": {"author": "schneems", "repo": "Octave", "sha": "411e8794574abb3fb042e178bf95861dfcee3b04", "save_path": "github-repos/MATLAB/schneems-Octave", "path": "github-repos/MATLAB/schneems-Octave/Octave-411e8794574abb3fb042e178bf95861dfcee3b04/mlclass-ex7/mlclass-ex7/recoverData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.687115765592489}} {"text": "% Fig. 6.12 Feedback Control of Dynamic Systems, 5e \n% Franklin, Powell, Emami\n%\n\nclear all;\nclose all;\n\nnum1=[10 10];\nden1=[1 10];\nw=logspace(-2,3,100);\n[m1,p1]=bode(num1,den1,w);\nnum2=[10 -10];\n[m2,p2]=bode(num2,den1,w);\nfigure(1)\nloglog(w,m1,w,m2);\nxlabel('\\omega (rad/sec)');\nylabel('Magnitude');\ntitle('Fig. 6.12 Bode Plot for a NMP System (a) magnitude');\ngrid;\npause;\nfigure(2)\nsemilogx(w,p1,w,p2);\ngrid;\nxlabel('\\omega (rad/sec)');\nylabel('Phase (deg)');\ntitle('Fig 6.12 (b) phase');\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/9907-feedback-control-of-dynamic-systems-fifth-ed/fig6_12.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6870962374915651}} {"text": "function dImgLow = fDownSample( dImgHigh, out_size )\n\nout_x_sz = out_size(1); out_y_sz = out_size(2); out_z_sz = out_size(3);\n[in_x_sz,in_y_sz, in_z_sz, nCha, nTime] = size( dImgHigh );\n\n\n% build grid vectors for the up/down sampling\n% ============================================\n% if the input is even & output is odd-> use floor for all\n% if the output is even & input is odd -> use ceil for all\n% other cases - don't care\n% for downsampling -> the opposite\nif (~mod( in_x_sz,2 ) & (out_x_sz>in_x_sz)) | (mod( in_x_sz,2 ) & (out_x_szin_y_sz)) | (mod( in_y_sz,2 ) & (out_y_szin_z_sz)) | (mod( in_z_sz,2 ) & (out_z_sz=1;\n sum(y)>=1;\n\n % trick to test for same support (idea: m > largest possible sum)\n m*x'*A>=y'*A;\n m*y'*A>=x'*A;\n\ncvx_end\n\ndisp(find(x))\ndisp(find(y))\n\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/topology/FR/combinatorialDependentRows.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6870913318493915}} {"text": "% This script runs program rundivcrl\n% for nine coordinate systems and puts\n% the output in rundivcrl.tst\nif exist('rundivcrl.tst','file')==2\n delete rundivcrl.tst\nend\nsyms x y z\nvxyz=[x*y,y*z,z*x]; \ndiary rundivcrl.tst\n% rundivcrl(vxyz,cordname,tn,noprint) call list\nrundivcrl(vxyz,@cylin,[10*rand,rand*2*pi,rand*10]);\nrundivcrl(vxyz,@sphr,[10*rand,rand*pi,rand*2*pi]);\nrundivcrl(vxyz,@cone,[2*rand,rand*pi/2,rand*2*pi]);\nrundivcrl(vxyz,@elipcyl,[2*rand,rand*2*pi,2*rand]);\nrundivcrl(vxyz,@elipsod,[rand,1+rand,2+rand]);\nrundivcrl(vxyz,@notort,[2*rand,rand*pi,rand*2*pi]);\nrundivcrl(vxyz,@oblate,[2*rand,rand*pi,rand*2*pi]);\nrundivcrl(vxyz,@parab,[2*rand,2*rand,2*rand]);\nrundivcrl(vxyz,@toroid,[rand*2,rand*2*pi,rand*2*pi]);\ndiary 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/15903-curvilinear-coordinates/cc/testdivcrl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6870913239284454}} {"text": "function determ = cheby_van2_determinant ( n )\n\n%*****************************************************************************80\n%\n%% CHEBY_VAN2_DETERMINANT returns the determinant of the CHEBY_VAN2 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Output, real DETERM, the determinant.\n%\n if ( n <= 0 )\n determ = 0.0;\n elseif ( n == 1 )\n determ = 1.0;\n else\n determ = r8_mop ( floor ( n / 2 ) ) * sqrt ( 2.0 )^( 4 - 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/test_mat/cheby_van2_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.687044413818476}} {"text": "% CSparse: a Concise Sparse matrix Package.\n%\n% Matrices used in CSparse must in general be either sparse and real,\n% or dense vectors. Ordering methods can accept any sparse matrix.\n%\n% cs_add - sparse matrix addition.\n% cs_amd - approximate minimum degree ordering.\n% cs_chol - sparse Cholesky factorization.\n% cs_cholsol - solve A*x=b using a sparse Cholesky factorization.\n% cs_counts - column counts for sparse Cholesky factor L.\n% cs_dmperm - maximum matching or Dulmage-Mendelsohn permutation.\n% cs_dmsol - x=A\\b using the coarse Dulmage-Mendelsohn decomposition.\n% cs_dmspy - plot the Dulmage-Mendelsohn decomposition of a matrix.\n% cs_droptol - remove small entries from a sparse matrix.\n% cs_esep - find an edge separator of a symmetric matrix A\n% cs_etree - elimination tree of A or A'*A.\n% cs_gaxpy - sparse matrix times vector.\n% cs_lsolve - solve a sparse lower triangular system L*x=b.\n% cs_ltsolve - solve a sparse upper triangular system L'*x=b.\n% cs_lu - sparse LU factorization, with fill-reducing ordering.\n% cs_lusol - solve Ax=b using LU factorization.\n% cs_make - compiles CSparse for use in MATLAB.\n% cs_multiply - sparse matrix multiply.\n% cs_nd - generalized nested dissection ordering.\n% cs_nsep - find a node separator of a symmetric matrix A.\n% cs_permute - permute a sparse matrix.\n% cs_print - print the contents of a sparse matrix.\n% cs_qr - sparse QR factorization.\n% cs_qleft - apply Householder vectors on the left.\n% cs_qright - apply Householder vectors on the right.\n% cs_qrsol - solve a sparse least-squares problem.\n% cs_randperm - random permutation.\n% cs_sep - convert an edge separator into a node separator.\n% cs_scc - strongly-connected components of a square sparse matrix.\n% cs_scc2 - cs_scc, or connected components of a bipartite graph.\n% cs_sparse - convert a triplet form into a sparse matrix.\n% cs_sqr - symbolic sparse QR factorization.\n% cs_symperm - symmetric permutation of a symmetric matrix.\n% cs_transpose - transpose a real sparse matrix.\n% cs_updown - rank-1 update/downdate of a sparse Cholesky factorization.\n% cs_usolve - solve a sparse upper triangular system U*x=b.\n% cs_utsolve - solve a sparse lower triangular system U'*x=b.\n% cspy - plot a matrix in color.\n% ccspy - plot the connected components of a matrix.\n\n% Example:\n% help cs_add\n\n% Copyright 2006-2007, Timothy A. Davis.\n% http://www.cise.ufl.edu/research/sparse\n\n% helper function:\n% cs_must_compile - return 1 if source code f must be compiled, 0 otherwise\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/SuiteSparse/CSparse/MATLAB/CSparse/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.6870444028543096}} {"text": "% produces synthetic Omori aftershock sequence using given epicentres\n% Omori parameters can be chosen arbitraily\n%\n% Samuel Neukomm, 27.2.2004\n\n[filename,pathname] = uigetfile('*.mat','Load earthquake sequence');\ndo = ['load ' pathname filename]; eval(do)\n\nlon = a.Longitude; lat = a.Latitude; mag = a.Magnitude; dep = a.Depth;\n[m_main, main] = max(a.Magnitude);\nif size(a,2) == 9\n date_matlab = datenum(a.Date.Year,a.Date.Month,a.Date.Day,a.Date.Hour,a.Date.Minute,zeros(size(a,1),1));\nelse\n date_matlab = datenum(a.Date.Year,a.Date.Month, a.Date.Day,a.Date.Hour,a.Date.Minute,a(:,10));\nend\n\ndate_main = date_matlab(main);\ntime_aftershock = date_matlab-date_main;\n\nl = time_aftershock(:) > 0;\nt_aftershock = time_aftershock(l);\neqcatalogue = a.subset(l);\n\nncum = (1:length(t_aftershock))';\n\nprompt = {'p value:','c value:','k value:'};\ndef = {'0.9','0.05','1000'};\ndlgTitle = 'Choose Omori parameters';\nlineNo = 1;\nanswer = inputdlg(prompt,dlgTitle,lineNo,def);\n\npv = str2double(answer{1});\ncv = str2double(answer{2});\nkv = str2double(answer{3});\n\ntasnew = (cv^(1-pv)-ncum*(pv-1)/kv).^(1/(1-pv))-cv;\n\ndate_mat_new = tasnew + date_main;\n[yr,mon,day,hr,mn,sec] = datevec(date_mat_new);\n\ndatum = [yr mon day hr mn sec];\nyr = decyear(datum);\n\nif size(a,2) == 9\n a = [a(main,:) 0; eqcatalogue(:,1) eqcatalogue(:,2) yr mon day eqcatalogue(:,6) eqcatalogue(:,7) hr mn sec];\nelse\n a = [a(main,1:10); eqcatalogue(:,1) eqcatalogue(:,2) yr mon day eqcatalogue(:,6) eqcatalogue(:,7) hr mn sec];\nend\n\n[filename, pathname] = uiputfile('*.mat', 'Save synthetic catalog as');\n\ntry\n save(fullfile(pathname, filename),'a','pv','cv','kv');\ncatch\n disp('failed to save'); %complain\nend", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/afterrate/make_synthcat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6870370848061146}} {"text": "function [x,P]=ukf(fstate,x,P,hmeas,z,Q,R)\n% UKF Unscented Kalman Filter for nonlinear dynamic systems\n% [x, P] = ukf(f,x,P,h,z,Q,R) returns state estimate, x and state covariance, P \n% for nonlinear dynamic system (for simplicity, noises are assumed as additive):\n% x_k+1 = f(x_k) + w_k\n% z_k = h(x_k) + v_k\n% where w ~ N(0,Q) meaning w is gaussian noise with covariance Q\n% v ~ N(0,R) meaning v is gaussian noise with covariance R\n% Inputs: f: function handle for f(x)\n% x: \"a priori\" state estimate\n% P: \"a priori\" estimated state covariance\n% h: fanction handle for h(x)\n% z: current measurement\n% Q: process noise covariance \n% R: measurement noise covariance\n% Output: x: \"a posteriori\" state estimate\n% P: \"a posteriori\" state covariance\n%\n% Example:\n%{\nn=3; %number of state\nq=0.1; %std of process \nr=0.1; %std of measurement\nQ=q^2*eye(n); % covariance of process\nR=r^2; % covariance of measurement \nf=@(x)[x(2);x(3);0.05*x(1)*(x(2)+x(3))]; % nonlinear state equations\nh=@(x)x(1); % measurement equation\ns=[0;0;1]; % initial state\nx=s+q*randn(3,1); %initial state % initial state with noise\nP = eye(n); % initial state covraiance\nN=20; % total dynamic steps\nxV = zeros(n,N); %estmate % allocate memory\nsV = zeros(n,N); %actual\nzV = zeros(1,N);\nfor k=1:N\n z = h(s) + r*randn; % measurments\n sV(:,k)= s; % save actual state\n zV(k) = z; % save measurment\n [x, P] = ukf(f,x,P,h,z,Q,R); % ekf \n xV(:,k) = x; % save estimate\n s = f(s) + q*randn(3,1); % update process \nend\nfor k=1:3 % plot results\n subplot(3,1,k)\n plot(1:N, sV(k,:), '-', 1:N, xV(k,:), '--')\nend\n%}\n% Reference: Julier, SJ. and Uhlmann, J.K., Unscented Filtering and\n% Nonlinear Estimation, Proceedings of the IEEE, Vol. 92, No. 3,\n% pp.401-422, 2004. \n%\n% By Yi Cao at Cranfield University, 04/01/2008\n%\nL=numel(x); %numer of states\nm=numel(z); %numer of measurements\nalpha=1e-3; %default, tunable\nki=0; %default, tunable\nbeta=2; %default, tunable\nlambda=alpha^2*(L+ki)-L; %scaling factor\nc=L+lambda; %scaling factor\nWm=[lambda/c 0.5/c+zeros(1,2*L)]; %weights for means\nWc=Wm;\nWc(1)=Wc(1)+(1-alpha^2+beta); %weights for covariance\nc=sqrt(c);\nX=sigmas(x,P,c); %sigma points around x\n[x1,X1,P1,X2]=ut(fstate,X,Wm,Wc,L,Q); %unscented transformation of process\n% X1=sigmas(x1,P1,c); %sigma points around x1\n% X2=X1-x1(:,ones(1,size(X1,2))); %deviation of X1\n[z1,Z1,P2,Z2]=ut(hmeas,X1,Wm,Wc,m,R); %unscented transformation of measurments\nP12=X2*diag(Wc)*Z2'; %transformed cross-covariance\nK=P12*inv(P2);\nx=x1+K*(z-z1); %state update\nP=P1-K*P12'; %covariance update\n\nfunction [y,Y,P,Y1]=ut(f,X,Wm,Wc,n,R)\n%Unscented Transformation\n%Input:\n% f: nonlinear map\n% X: sigma points\n% Wm: weights for mean\n% Wc: weights for covraiance\n% n: numer of outputs of f\n% R: additive covariance\n%Output:\n% y: transformed mean\n% Y: transformed smapling points\n% P: transformed covariance\n% Y1: transformed deviations\n\nL=size(X,2);\ny=zeros(n,1);\nY=zeros(n,L);\nfor k=1:L \n Y(:,k)=f(X(:,k)); \n y=y+Wm(k)*Y(:,k); \nend\nY1=Y-y(:,ones(1,L));\nP=Y1*diag(Wc)*Y1'+R; \n\nfunction X=sigmas(x,P,c)\n%Sigma points around reference point\n%Inputs:\n% x: reference point\n% P: covariance\n% c: coefficient\n%Output:\n% X: Sigma points\n\nA = c*chol(P)';\nY = x(:,ones(1,numel(x)));\nX = [x Y+A Y-A]; ", "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/18217-learning-the-unscented-kalman-filter/ukf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6870266210673353}} {"text": "function matlab_time = unixtime2mat(unix_time);\n% unixtime2mat Converts unix time stamps (seconds since Jan 1, 1970) to\n% Matlab serial date number (decimal days since Jan 1 0000).\n% \n% USAGE:\n% unixtime2mat(unix_time)\n%\n%\n% The function may not handle leap years or leap seconds\n% appropriately. \n%\n% Val Schmidt \n% Center for Coastal and Ocean Mapping\n% 2007\n\nunix_epoch = datenum(1970,1,1,0,0,0);\nmatlab_time = unix_time./86400 + unix_epoch; \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/24024-convert-unix-time-seconds-since-jan-1-1970-to-matlab-serial-time/unixtime2mat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6870266145138695}} {"text": "%WAVE_BASES 1D Wavelet functions Morlet, Paul, or DOG\n%\n% [DAUGHTER,FOURIER_FACTOR,COI,DOFMIN] = ...\n% wave_bases(MOTHER,K,SCALE,PARAM);\n%\n% Computes the wavelet function as a function of Fourier frequency,\n% used for the wavelet transform in Fourier space.\n% (This program is called automatically by WAVELET)\n%\n% INPUTS:\n%\n% MOTHER = a string, equal to 'MORLET' or 'PAUL' or 'DOG'\n% K = a vector, the Fourier frequencies at which to calculate the wavelet\n% SCALE = a number, the wavelet scale\n% PARAM = the nondimensional parameter for the wavelet function\n%\n% OUTPUTS:\n%\n% DAUGHTER = a vector, the wavelet function\n% FOURIER_FACTOR = the ratio of Fourier period to scale\n% COI = a number, the cone-of-influence size at the scale\n% DOFMIN = a number, degrees of freedom for each point in the wavelet power\n% (either 2 for Morlet and Paul, or 1 for the DOG)\n%\n%----------------------------------------------------------------------------\n% Copyright (C) 1995-1998, Christopher Torrence and Gilbert P. Compo\n% University of Colorado, Program in Atmospheric and Oceanic Sciences.\n% This software may be used, copied, or redistributed as long as it is not\n% sold and this copyright notice is reproduced on each copy made. This\n% routine is provided as is without any express or implied warranties\n% whatsoever.\n%----------------------------------------------------------------------------\nfunction [daughter,fourier_factor,coi,dofmin] = ...\n\twave_bases(mother,k,scale,param);\n\nmother = upper(mother);\nn = length(k);\n\nif (strcmp(mother,'MORLET')) %----------------------------------- Morlet\n\tif (param == -1), param = 6.;, end\n\tk0 = param;\n\texpnt = -(scale.*k - k0).^2/2.*(k > 0.);\n\tnorm = sqrt(scale*k(2))*(pi^(-0.25))*sqrt(n); % total energy=N [Eqn(7)]\n\tdaughter = norm*exp(expnt);\n\tdaughter = daughter.*(k > 0.); % Heaviside step function\n\tfourier_factor = (4*pi)/(k0 + sqrt(2 + k0^2)); % Scale-->Fourier [Sec.3h]\n\tcoi = fourier_factor/sqrt(2); % Cone-of-influence [Sec.3g]\n\tdofmin = 2; % Degrees of freedom\nelseif (strcmp(mother,'PAUL')) %-------------------------------- Paul\n\tif (param == -1), param = 4.;, end\n\tm = param;\n\texpnt = -(scale.*k).*(k > 0.);\n\tnorm = sqrt(scale*k(2))*(2^m/sqrt(m*prod(2:(2*m-1))))*sqrt(n);\n\tdaughter = norm*((scale.*k).^m).*exp(expnt);\n\tdaughter = daughter.*(k > 0.); % Heaviside step function\n\tfourier_factor = 4*pi/(2*m+1);\n\tcoi = fourier_factor*sqrt(2);\n\tdofmin = 2;\nelseif (strcmp(mother,'DOG')) %-------------------------------- DOG\n\tif (param == -1), param = 2.;, end\n\tm = param;\n\texpnt = -(scale.*k).^2 ./ 2.0;\n\tnorm = sqrt(scale*k(2)/gamma(m+0.5))*sqrt(n);\n\tdaughter = -norm*(i^m)*((scale.*k).^m).*exp(expnt);\n\tfourier_factor = 2*pi*sqrt(2./(2*m+1));\n\tcoi = fourier_factor/sqrt(2);\n\tdofmin = 1;\nelse\n\terror('Mother must be one of MORLET,PAUL,DOG')\nend\n\nreturn\n", "meta": {"author": "grinsted", "repo": "wavelet-coherence", "sha": "b8c3925f54c8d113620925070eb1ac572fbcac05", "save_path": "github-repos/MATLAB/grinsted-wavelet-coherence", "path": "github-repos/MATLAB/grinsted-wavelet-coherence/wavelet-coherence-b8c3925f54c8d113620925070eb1ac572fbcac05/private/wave_bases.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6870266054168125}} {"text": "function pass = test_times( pref ) \n\n% Grab some preferences\nif ( nargin == 0 )\n pref = chebfunpref();\nend\ntol = 1e2*pref.techPrefs.chebfuneps;\n\nf = ballfun(@(x,y,z)x.*y);\nZ = ballfun(@(x,y,z)0);\n\n% Example 1:\nF = ballfunv(f,Z,Z);\nG = ballfunv(Z,f,Z);\nH = times(F,G);\nHexact = ballfunv(Z,Z,Z);\npass(1) = norm(H - Hexact) < tol;\n\n% Example 2:\nF = ballfunv(f,Z,Z);\nG = ballfunv(-f,Z,Z);\nH = times(F,G);\nHexact = ballfunv(-power(f,2),Z,Z);\npass(2) = norm(H - Hexact) < tol;\n\n% Example 3:\nF = ballfunv(f,2*f,3*f);\nG = ballfunv(-2*f,f,-f);\nH = times(F,G);\nHexact = ballfunv(-2*power(f,2),2*power(f,2),-3*power(f,2));\npass(3) = norm(H - Hexact) < tol;\n\n% Example 4:\n% Multiply ballfunv by ballfun\nV = ballfunv(@(x,y,z)x,@(x,y,z)y,@(x,y,z)z);\nf = ballfun(@(x,y,z)cos(y));\nexact = ballfunv(@(x,y,z)x.*cos(y),@(x,y,z)y.*cos(y),@(x,y,z)z.*cos(y));\npass(3) = norm(V*f-exact) < tol;\npass(4) = norm(f*V-exact) < tol;\n\nif (nargout > 0)\n pass = all(pass(:));\nend\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/ballfunv/test_times.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.687026600688733}} {"text": "function result = SimulateSSCOMP_3Spaces(D, K, Ng, theta, SNR, shuffle)\n% Simulates SSC-OMP algorithm\n% D - Ambient space dimension\n% K - Subspace dimension\n% Ng - Number of vectors per subspace\n% theta - angle between disjoint subspaces\n% shuffle - whether to shuffle the vectors or not.\n\n if nargin < 6\n shuffle = false;\n end\n if nargin < 5\n SNR = Inf;\n end\n % number of subspaces = number of clusters\n ns = 3;\n % Let us form the subspaces\n [A, B, C] = spx.la.spaces.three_disjoint_spaces_at_angle(K, deg2rad(theta)); \n % Put them together\n X = [A B C];\n % Put them to bigger dimension\n X = spx.la.spaces.k_dim_to_n_dim(X, D);\n % Perform a random orthonormal transformation\n O = orth(randn(D));\n X = O * X;\n % Split them again\n A = X(:, 1:K);\n B = X(:, K + (1:K));\n C = X(:, 2*K + (1:K));\n % coefficients for Ng vectors chosen randomly in subspace A\n coeffs_a = randn(K,Ng);\n % avoid small values\n coeffs_a = 2*sign(coeffs_a) + coeffs_a;\n % coefficients for Ng vectors chosen randomly in subspace B\n coeffs_b = randn(K,Ng);\n % coefficients for Ng vectors chosen randomly in subspace C\n coeffs_c = randn(K,Ng);\n % avoid small values\n coeffs_c = 2*sign(coeffs_c) + coeffs_c;\n % Actual vectors from the three subspaces\n XA = A * coeffs_a;\n XB = B * coeffs_b;\n XC = C * coeffs_c;\n % Prepare the overall set of signals\n X = [XA XB XC];\n % ground through clustering data\n true_labels = [1*ones(Ng,1) ; 2*ones(Ng,1) ; 3*ones(Ng,1)];\n % All signals are expected to have a K-sparse representation\n if shuffle\n % We also shuffle the signals\n shuffled_indices = randperm(3*Ng);\n X = X(:, shuffled_indices);\n true_labels = true_labels(shuffled_indices);\n end\n if ~isinf(SNR)\n % We need to add some noise in the signals.\n noises = spx.data.noise.Basic.createNoise(X, SNR);\n % Preserve original data\n X0 = X;\n % Add noise\n X = X0 + noises;\n end\n % Keep data for reference.\n result.num_subspaces = 3;\n result.theta = theta;\n result.subspace_dimension = K;\n result.ambient_dimension = D;\n result.num_signals_per_subspace = Ng;\n result.num_total_signals = size(X, 2);\n result.true_labels = true_labels;\n result.X = X;\n\n tstart = tic; \n % Application of Sparse subspace clustering\n solver = spx.cluster.ssc.SSC_OMP(X, K, ns);\n solver.Quiet = true;\n ssc_result = solver.solve();\n elapsed_time = toc(tstart);\n result.elapsed_time = elapsed_time;\n result.C = solver.Representation;\n % fprintf('Sparse subspace clustering time spent: %.2f seconds\\n', elapsed_time);\n\n cluster_labels = ssc_result.Labels;\n %combined_labels = [true_labels cluster_labels]';\n result.cluster_labels = cluster_labels;\n\n % Time to compare the clustering\n comparer = spx.cluster.ClusterComparison(true_labels, cluster_labels);\n result.comparison = comparer.fMeasure();\n % fprintf('Sparse subspace clustering results:\\n');\n % comparer.printF1MeasureResult(result.comparison);\nend", "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/clustering/sparse_subspace_clustering/ssc_omp/SimulateSSCOMP_3Spaces.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.687015467764019}} {"text": "function [node,elem,HB] = cubemesh(box,h)\n%% CUBEMESH a uniform mesh of a cube\n%\n% [node,elem,HB] = cubemesh([x0,x1,y0,y1,z0,z1],h) enerates a uniform mesh\n% of the cube [x0,x1]*[y0,y1]*[z0,z1] with mesh size h.\n%\n% Example\n%\n% [node,elem,HB] = cubemesh([-1,1,-1,1,-1,1],0.5);\n% showmesh3(node,elem);\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details. \n\nx0 = box(1); x1 = box(2); \ny0 = box(3); y1 = box(4);\nz0 = box(5); z1 = box(6);\nnode = [x0,y0,z0; x1,y0,z0; x1,y1,z0; x0,y1,z0; ...\n x0,y0,z1; x1,y0,z1; x1,y1,z1; x0,y1,z1];\nelem = [1 2 3 7; 1 4 3 7; 1 5 6 7; 1 5 8 7; 1 2 6 7; 1 4 8 7];\nn = ceil(log2(abs(x1-x0)/h));\nfor k = 1:n\n [node,elem] = uniformrefine3(node,elem); \nend\n% Set this as an initial grid\nN0 = size(node,1);\nHB(1:N0,1:3) = repmat((1:N0)',1,3); \nHB(1:N0,4) = 0;", "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/mesh/cubemesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.6869645454646955}} {"text": "function [hess, storedb] = getHessian(problem, x, d, storedb)\n% Computes the Hessian of the cost function at x along d.\n%\n% function [hess, storedb] = getHessian(problem, x, d, storedb)\n%\n% Returns the Hessian at x along d of the cost function described in the\n% problem structure. The cache database storedb is passed along, possibly\n% modified and returned in the process.\n%\n% If an exact Hessian is not provided, an approximate Hessian is returned\n% if possible, without warning. If not possible, an exception will be\n% thrown. To check whether an exact Hessian is available or not (typically\n% to issue a warning if not), use canGetHessian.\n%\n% See also: getPrecon getApproxHessian canGetHessian\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Dec. 30, 2012.\n% Contributors: \n% Change log: \n \n if isfield(problem, 'hess')\n %% Compute the Hessian using hess.\n\n\t\tis_octave = exist('OCTAVE_VERSION', 'builtin');\n\t\tif ~is_octave\n\t\t\tnarg = nargin(problem.hess);\n\t\telse\n\t\t\tnarg = 3;\n\t\tend\n\t\n % Check whether the hess function wants to deal with the store\n % structure or not.\n switch narg\n case 2\n hess = problem.hess(x, d);\n case 3\n % Obtain, pass along, and save the store structure\n % associated to this point.\n store = getStore(problem, x, storedb);\n [hess store] = problem.hess(x, d, store);\n storedb = setStore(problem, x, storedb, store);\n otherwise\n up = MException('manopt:getHessian:badhess', ...\n 'hess should accept 2 or 3 inputs.');\n throw(up);\n end\n \n elseif isfield(problem, 'ehess') && canGetEuclideanGradient(problem)\n %% Compute the Hessian using ehess.\n \n % We will need the Euclidean gradient for the conversion from the\n % Euclidean Hessian to the Riemannian Hessian.\n [egrad, storedb] = getEuclideanGradient(problem, x, storedb);\n \n\t\tis_octave = exist('OCTAVE_VERSION', 'builtin');\n\t\tif ~is_octave\n\t\t\tnarg = nargin(problem.ehess);\n\t\telse\n\t\t\tnarg = 3;\n\t\tend\n\t\t\n % Check whether the ehess function wants to deal with the store\n % structure or not.\n switch narg\n case 2\n ehess = problem.ehess(x, d);\n case 3\n % Obtain, pass along, and save the store structure\n % associated to this point.\n store = getStore(problem, x, storedb);\n [ehess store] = problem.ehess(x, d, store);\n storedb = setStore(problem, x, storedb, store);\n otherwise\n up = MException('manopt:getHessian:badehess', ...\n 'ehess should accept 2 or 3 inputs.');\n throw(up);\n end\n \n % Convert to the Riemannian Hessian\n hess = problem.M.ehess2rhess(x, egrad, ehess, d);\n \n else\n %% Attempt the computation of an approximation of the Hessian.\n \n [hess, storedb] = getApproxHessian(problem, x, d, storedb);\n \n end\n \nend\n", "meta": {"author": "hiroyuki-kasai", "repo": "ClassifierToolbox", "sha": "63aa78304a8ac10c432840c45d63170ea2bbabb0", "save_path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox", "path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox/ClassifierToolbox-63aa78304a8ac10c432840c45d63170ea2bbabb0/lib/Riemannian_DL_SC_SPD/manopt/manopt/privatetools/getHessian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.7956581097540518, "lm_q1q2_score": 0.6869645447596531}} {"text": "function [ fea, out ] = ex_axistressstrain1( varargin )\n%EX_AXISTRESSSTRAIN1 Example for hollow cylider axisymmetric stress-strain.\n%\n% [ FEA, OUT ] = EX_AXISTRESSSTRAIN1( VARARGIN ) Example to calculate displacements and stresses\n% in a hollow cylinder in axisymmetric/cylindrical coordinates.\n%\n% Ref. 4.1.9 Long (generalized plane strain) cylinder subjected to internal and external pressure.\n% [1] Applied Mechanics of Solids, Allan F. Bower, 2012 (http://solidmechanics.org/).\n%\n% Accepts the following property/value pairs.\n%\n% Input Value/{Default} Description\n% -----------------------------------------------------------------------------------\n% a scalar {1.5} Cylinder inner radius\n% b scalar {2} Cylinder outer radius\n% l scalar {3} Cylinder length\n% pa scalar {5e3} Inner load force\n% pb scalar {20e4} Outer load force\n% E scalar {200e9} Modulus of elasticity\n% nu scalar {0.3} Poissons ratio\n% igrid scalar 0/{1} Cell type (0=quadrilaterals, 1=triangles)\n% hmax scalar {0.1} Max grid cell size\n% sfun string {sflag2} Shape function for displacements\n% iplot scalar 0/{1} Plot solution (=1)\n% .\n% Output Value/(Size) Description\n% -----------------------------------------------------------------------------------\n% fea struct Problem definition struct\n% out struct Output struct\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\ncOptDef = { 'a', 0.9;\n 'b', 2;\n 'l', 3;\n 'pa', 5e3;\n 'pb', 20e4;\n 'E', 200e9;\n 'nu', 0.3;\n 'igrid', 0;\n 'hmax', 0.01;\n 'sfun', 'sflag2';\n 'iplot', 1;\n 'tol', 5e-2;\n 'fid', 1 };\n[got,opt] = parseopt(cOptDef,varargin{:});\nfid = opt.fid;\n\n\n% Geometry and grid.\na = opt.a;\nb = opt.b;\nl = opt.l;\nfea.geom.objects = { gobj_rectangle( a, b, 0, l, 'R1' ) };\nif ( opt.igrid==1 )\n fea.grid = gridgen( fea, 'hmax', opt.hmax, 'fid', fid );\nelse\n fea.grid = rectgrid( ceil((b-a)/opt.hmax), ceil(l/opt.hmax), [a b;0 l] );\n if( opt.igrid<0 )\n fea.grid = quad2tri( fea.grid );\n end\nend\nn_bdr = max(fea.grid.b(3,:)); % Number of boundaries.\n\n\n% Axisymmetric stress-strain equation definitions.\nfea.sdim = { 'r', 'z' };\nfea = addphys( fea, @axistressstrain );\nfea.phys.css.eqn.coef{1,end} = { opt.nu };\nfea.phys.css.eqn.coef{2,end} = { opt.E };\nfea.phys.css.sfun = { opt.sfun opt.sfun }; % Set shape functions.\n\n% Boundary conditions.\nbctype = mat2cell( zeros(2,n_bdr), [1 1], ones(1,n_bdr) );\n[bctype{2,:}] = deal( 1 );\nfea.phys.css.bdr.coef{1,5} = bctype;\n\nbccoef = mat2cell( zeros(2,n_bdr), [1 1], ones(1,n_bdr) );\nbccoef{1,2} = opt.pb*b;\nbccoef{1,4} = opt.pa*a;\nfea.phys.css.bdr.coef{1,end} = bccoef;\n\n\n% Solve.\nfea = parsephys( fea );\nfea = parseprob( fea );\nfea.sol.u = solvestat( fea, 'icub', 1+str2num(strrep(opt.sfun,'sflag','')), 'fid', fid );\n\n\n% Postprocessing.\nn = 20;\nr = linspace(a,b,n);\nz = l/2*ones(1,n);\npa = opt.pa; pb = -opt.pb; E = opt.E; nu = opt.nu;\n% 4.1.9 http://solidmechanics.org/Text/Chapter4_1/Chapter4_1.php#Sect4_1_9\nu_ref = (1+nu)*a^2*b^2/E/(b^2-a^2)*( (pa-pb)./r' + (1-2*nu)*(pa*a^2 - pb*b^2)/a^2/b^2*r' );\nsr_ref = (pa*a^2-pb*b^2)/(b^2-a^2) - a^2*b^2/(b^2-a^2)./(r').^2*(pa-pb);\nst_ref = (pa*a^2-pb*b^2)/(b^2-a^2) + a^2*b^2/(b^2-a^2)./(r').^2*(pa-pb);\nsz_ref = 2*nu*(pa*a^2-pb*b^2)/(b^2-a^2);\nu = evalexpr( fea.phys.css.eqn.vars{3,2}, [r;z], fea );\nw = evalexpr( fea.phys.css.eqn.vars{4,2}, [r;z], fea );\nsr = evalexpr( fea.phys.css.eqn.vars{5,2}, [r;z], fea );\nst = evalexpr( fea.phys.css.eqn.vars{6,2}, [r;z], fea );\nsz = evalexpr( fea.phys.css.eqn.vars{7,2}, [r;z], fea );\nif( opt.iplot>0 )\n subplot(1,2,1)\n postplot( fea, 'surfexpr', fea.phys.css.eqn.vars{3,2} )\n title('r-displacement')\n subplot(1,2,2), hold on\n plot(u_ref,r,'r-')\n plot(u,r,'b.')\n legend('exact solution','computed solution')\n xlabel('r')\n grid on\nend\n\n\n% Error checking.\nout.erru = norm( u_ref - u )/norm( u_ref );\nout.errw = norm( w );\nout.errsr = norm( sr_ref - sr )/norm( sr_ref );\nout.errst = norm( st_ref - st )/norm( st_ref );\nout.errsz = norm( sz_ref - sz )/norm( sz_ref );\nout.err = [ out.erru, out.errw, out.errsr, out.errst, out.errsz ];\nout.pass = all(out.err < opt.tol);\n\n\nif( nargout==0 )\n clear fea out\nend\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/examples/ex_axistressstrain1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.6869645343008531}} {"text": "function varargout = transformVector3d(varargin)\n%TRANSFORMVECTOR3D Transform a vector with a 3D affine transform.\n%\n% V2 = transformVector3d(V1, TRANS);\n% Computes the vector obtained by transforming vector V1 with affine\n% transform TRANS.\n% V1 has the form [x1 y1 z1], and TRANS is a [3x3], [3x4], or [4x4]\n% matrix, with one of the forms:\n% [a b c] , [a b c j] , or [a b c j]\n% [d e f] [d e f k] [d e f k]\n% [g h i] [g h i l] [g h i l]\n% [0 0 0 1]\n%\n% V2 = transformVector3d(V1, TRANS) also works when V1 is a [Nx3xMxEtc]\n% array of double. In this case, V2 has the same size as V1.\n%\n% V2 = transformVector3d(X1, Y1, Z1, TRANS);\n% Specifies vectors coordinates in three arrays with same size.\n%\n% [X2 Y2 Z2] = transformVector3d(...);\n% Returns the coordinates of the transformed vector separately.\n%\n%\n% See also \n% vectors3d, transforms3d, transformPoint3d\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2008-11-25, from transformPoint3d\n% Copyright 2008-2022 INRA - TPV URPOI - BIA IMASTE\n\nif nargin~=2 && nargin~=4\n error('Invalid number of input arguments. Type ''help transformVector3d'' for details.');\nend\n\n% Extract only the linear part of the affine transform\ntrans = varargin{end};\ntrans(1:4,4) = [0; 0; 0; 1];\n\n% Call transformPoint3d using equivalent output arguments\nvarargout = cell(1, max(1,nargout));\n[varargout{:}] = transformPoint3d(varargin{1:end-1}, trans);\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/transformVector3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6869645126314758}} {"text": "% Studies the recovery probability of different algorithms\n% at a fixed sparsity level and varying number of signals.\n\nclose all;\nclear all;\nclc;\nrng('default');\n% Create the directory for storing images\n[status_code,message,message_id] = mkdir('bin');\n% Signal space \nN = 256;\n% Number of measurements\nM = 48;\n% Number of signals\nSs = 1:32;\n% Sparsity level\nK = 16;\nnum_trials = 100;\nnum_ss = length(Ss);\nsuccess_with_s.somp = zeros(num_ss, 1);\nsuccess_with_s.ra_omp = zeros(num_ss, 1);\nsuccess_with_s.ra_ormp = zeros(num_ss, 1);\nsuccess_with_s.cosamp_mmv = zeros(num_ss, 1);\nsuccess_with_s.ra_cosamp = zeros(num_ss, 1);\n\n\nsnr_threshold = 100;\n\nfor ns=1:num_ss\n % Current number of signals\n S = Ss(ns);\n num_successes.somp = 0;\n num_successes.ra_omp = 0;\n num_successes.ra_ormp = 0;\n num_successes.cosamp_mmv = 0;\n num_successes.ra_cosamp = 0;\n for nt=1:num_trials\n % Sensing matrix\n Phi = spx.dict.simple.gaussian_dict(M, N);\n % Sparse signal generator\n gen = spx.data.synthetic.SparseSignalGenerator(N, K, S);\n % Gaussian distributed non-zero samples\n X = gen.gaussian;\n % Measurement vectors\n Y = Phi * X;\n \n\n % Create the solver for simultaneous orthogonal matching pursuit\n solver = spx.pursuit.joint.OrthogonalMatchingPursuit(Phi, K, 2);\n result = solver.solve(Y);\n % Solution vectors\n X_Rec = result.Z;\n % Comparison\n cs = spx.commons.SparseSignalsComparison(X, X_Rec, K);\n % Reconstruction SNR\n snr = cs.cum_signal_to_noise_ratio;\n success = snr > snr_threshold;\n num_successes.somp = num_successes.somp + success;\n\n % Create the solver for rank aware orthogonal matching pursuit\n solver = spx.pursuit.joint.RankAwareOMP(Phi, K);\n result = solver.solve(Y);\n % Solution vectors\n X_Rec = result.Z;\n % Comparison\n cs = spx.commons.SparseSignalsComparison(X, X_Rec, K);\n % Reconstruction SNR\n snr = cs.cum_signal_to_noise_ratio;\n success = snr > snr_threshold;\n num_successes.ra_omp = num_successes.ra_omp + success;\n\n % Create the solver for rank aware order recursive matching pursuit\n solver = spx.pursuit.joint.RankAwareORMP(Phi, K);\n result = solver.solve(Y);\n % Solution vectors\n X_Rec = result.Z;\n % Comparison\n cs = spx.commons.SparseSignalsComparison(X, X_Rec, K);\n % Reconstruction SNR\n snr = cs.cum_signal_to_noise_ratio;\n success = snr > snr_threshold;\n num_successes.ra_ormp = num_successes.ra_ormp + success;\n\n % Create the solver for CoSaMP MMV\n solver = spx.pursuit.joint.CoSaMP(Phi, K);\n result = solver.solve(Y);\n % Solution vectors\n X_Rec = result.Z;\n % Comparison\n cs = spx.commons.SparseSignalsComparison(X, X_Rec, K);\n % Reconstruction SNR\n snr = cs.cum_signal_to_noise_ratio;\n success = snr > snr_threshold;\n num_successes.cosamp_mmv = num_successes.cosamp_mmv + success;\n\n % Create the solver for Rank Aware CoSaMP MMV\n solver = spx.pursuit.joint.CoSaMP(Phi, K);\n solver.RankAwareResidual = true;\n result = solver.solve(Y);\n % Solution vectors\n X_Rec = result.Z;\n % Comparison\n cs = spx.commons.SparseSignalsComparison(X, X_Rec, K);\n % Reconstruction SNR\n snr = cs.cum_signal_to_noise_ratio;\n success = snr > snr_threshold;\n num_successes.ra_cosamp = num_successes.ra_cosamp + success;\n\n fprintf('S: %d, K=%d, trial=%d\\n', S, K, nt);\n end\n success_with_s.somp(ns) = num_successes.somp / num_trials;\n success_with_s.ra_omp(ns) = num_successes.ra_omp / num_trials;\n success_with_s.ra_ormp(ns) = num_successes.ra_ormp / num_trials;\n success_with_s.cosamp_mmv(ns) = num_successes.cosamp_mmv / num_trials;\n success_with_s.ra_cosamp(ns) = num_successes.ra_cosamp / num_trials;\nend\n\n\nsave ('bin/success_with_s_comparison.mat');\n\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/experiments/cosamp_mmv/ex_comparison_with_s.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6869024392026153}} {"text": "function y = lnCumGaussian(x)\n\n% LNCUMGAUSSIAN log cumulative distribution for the normalised Gaussian.\n% FORMAT\n% DESC computes the logarithm of the cumulative Gaussian\n% distribution.\n% ARG X : input position.\n% RETURN y : log probability of the value under the cumulative\n% Gaussian.\n%\n% SEEALSO : erf, erfcx, cumGaussian, lnDiffCumGaussian, gaussOverDiffCumGaussian\n%\n% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006\n\n% NDLUTIL\n\nindex = find(x< 0);\nif length(index)\n y(index) = -.5*x(index).*x(index) + log(.5) + log(erfcx(-sqrt(2)/2* ...\n x(index)));\nend\nindex = find(x>=0);\nif length(index)\n y(index) = log(cumGaussian(x(index)));\nend\ny=reshape(y, size(x));\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/ndlutil/lnCumGaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6869024236352447}} {"text": "function value = hexagon_contains_point_2d ( v, p )\n\n%*****************************************************************************80\n%\n%% HEXAGON_CONTAINS_POINT_2D finds if a point is inside a hexagon in 2D.\n%\n% Discussion:\n%\n% This test is only valid if the hexagon is convex.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real V(2,6), the vertics, in counterclockwise order.\n%\n% Input, real P(2), the point to be tested.\n%\n% Output, logical VALUE, is TRUE if X is in the hexagon.\n%\n n = 6;\n%\n% A point is inside a convex hexagon if and only if it is \"inside\"\n% each of the 6 halfplanes defined by lines through consecutive\n% vertices.\n%\n for i = 1 : n\n\n j = mod ( i, n ) + 1;\n\n if ( v(1,i) * ( v(2,j) - p(2 ) ) ...\n + v(1,j) * ( p(2 ) - v(2,i) ) ...\n + p(1 ) * ( v(2,i) - v(2,j) ) < 0.0 )\n\n value = 0;\n return\n\n end\n\n end\n\n value = 1;\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_triangulation/hexagon_contains_point_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240862, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.686833925459915}} {"text": "classdef ContourFitting < handle\n %CONTOURFITTING Contour Fitting algorithm using Fourier descriptors\n %\n % Contour fitting matches two contours `z_a` and `z_b` minimizing distance\n % `d(z_a, z_b) = sum_n (a_n - s * b_n * exp(j * (n * alpha + phi)))^2`\n % where `a_n` and `b_n` are Fourier descriptors of `z_a` and `z_b` and `s`\n % is a scaling factor and `phi` is angle rotation and `alpha` is starting\n % point factor adjustement.\n %\n % ## References:\n % [PersoonFu1977]:\n % > E Persoon and King-Sun Fu. \"Shape discrimination using fourier\n % > descriptors\". IEEE Transactions on Pattern Analysis and Machine\n % > Intelligence, 7(3):170-179, 1977.\n %\n % [BergerRaghunathan1998]:\n % > L Berger, V A Raghunathan, C Launay, D Ausserre, and Y Gallot.\n % > \"Coalescence in 2 dimensions: experiments on thin copolymer films and\n % > numerical simulations\". The European Physical Journal B - Condensed\n % > Matter and Complex Systems, 2(1):93-99, 1998.\n %\n % See also: cv.ContourFitting.ContourFitting, cv.matchShapes,\n % cv.ShapeContextDistanceExtractor\n %\n\n properties (SetAccess = private)\n % Object ID\n id\n end\n\n properties (Dependent)\n % number of Fourier descriptors used in\n % cv.ContourFitting.estimateTransformation equal to number of contour\n % points after resampling.\n CtrSize\n % number of Fourier descriptors used for optimal curve matching in\n % cv.ContourFitting.estimateTransformation when using vector of points\n FDSize\n end\n\n %% ContourFitting\n methods\n function this = ContourFitting(varargin)\n %CONTOURFITTING Create ContourFitting object\n %\n % obj = cv.ContourFitting()\n % obj = cv.ContourFitting('OptionName',optionValue, ...)\n %\n % ## Options\n % * __CtrSize__ number of contour points after resampling.\n % default 1024\n % * __FDSize__ number of Fourier descriptors. default 16\n %\n % See also: cv.ContourFitting.estimateTransformation\n %\n this.id = ContourFitting_(0, 'new', varargin{:});\n end\n\n function delete(this)\n %DELETE Destructor\n %\n % obj.delete()\n %\n % See also: cv.ContourFitting\n %\n if isempty(this.id), return; end\n ContourFitting_(this.id, 'delete');\n end\n\n function [alphaPhiST, d] = estimateTransformation(this, src, ref, varargin)\n %ESTIMATETRANSFORMATION Fits two closed curves using Fourier descriptors\n %\n % [alphaPhiST, d] = obj.estimateTransformation(src, ref)\n % [...] = obj.estimateTransformation(..., 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __src__ Contour defining first shape (source), or Fourier\n % descriptors if `FD` is true.\n % * __ref__ Contour defining second shape (target), or Fourier\n % descriptors if `FD` is true.\n %\n % ## Output\n % * __alphaPhiST__ transformation as a 5-elements vector\n % `[alpha, phi, s, Tx, Ty]`, where:\n % * __alpha__ starting point factor adjustement\n % * __phi__ angle rotation in radian\n % * __s__ scaling factor\n % * __Tx__, __Ty__ the translation\n % * __d__ distance between `src` and `ref` after matching.\n %\n % ## Options\n % * __FD__ If false then `src` and `ref` are contours, and\n % if true `src` and `ref` are Fourier descriptors. default false\n %\n % When `FD` is false, it applies cv.ContourFitting.contourSampling\n % and cv.ContourFitting.fourierDescriptor to compute Fourier\n % descriptors.\n %\n % More details in [PersoonFu1977] and [BergerRaghunathan1998].\n %\n % See also: cv.ContourFitting.transformFD,\n % cv.ContourFitting.contourSampling,\n % cv.ContourFitting.fourierDescriptor\n %\n [alphaPhiST, d] = ContourFitting_(this.id, 'estimateTransformation', src, ref, varargin{:});\n end\n end\n\n %% Algorithm\n methods (Hidden)\n function clear(this)\n %CLEAR Clears the algorithm state\n %\n % obj.clear()\n %\n % See also: cv.ContourFitting.empty, cv.ContourFitting.load\n %\n ContourFitting_(this.id, 'clear');\n end\n\n function b = empty(this)\n %EMPTY Checks if algorithm object is empty\n %\n % b = obj.empty()\n %\n % ## Output\n % * __b__ Returns true if the algorithm object is empty\n % (e.g. in the very beginning or after unsuccessful read).\n %\n % See also: cv.ContourFitting.clear, cv.ContourFitting.load\n %\n b = ContourFitting_(this.id, 'empty');\n end\n\n function save(this, filename)\n %SAVE Saves the algorithm parameters to a file\n %\n % obj.save(filename)\n %\n % ## Input\n % * __filename__ Name of the file to save to.\n %\n % This method stores the algorithm parameters in the specified\n % XML or YAML file.\n %\n % See also: cv.ContourFitting.load\n %\n ContourFitting_(this.id, 'save', filename);\n end\n\n function load(this, fname_or_str, varargin)\n %LOAD Loads algorithm from a file or a string\n %\n % obj.load(fname)\n % obj.load(str, 'FromString',true)\n % obj.load(..., 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __fname__ Name of the file to read.\n % * __str__ String containing the serialized model you want to\n % load.\n %\n % ## Options\n % * __ObjName__ The optional name of the node to read (if empty,\n % the first top-level node will be used). default empty\n % * __FromString__ Logical flag to indicate whether the input is a\n % filename or a string containing the serialized model.\n % default false\n %\n % This method reads algorithm parameters from the specified XML or\n % YAML file (either from disk or serialized string). The previous\n % algorithm state is discarded.\n %\n % See also: cv.ContourFitting.save\n %\n ContourFitting_(this.id, 'load', fname_or_str, varargin{:});\n end\n\n function name = getDefaultName(this)\n %GETDEFAULTNAME Returns the algorithm string identifier\n %\n % name = obj.getDefaultName()\n %\n % ## Output\n % * __name__ This string is used as top level XML/YML node tag\n % when the object is saved to a file or string.\n %\n % See also: cv.ContourFitting.save, cv.ContourFitting.load\n %\n name = ContourFitting_(this.id, 'getDefaultName');\n end\n end\n\n %% Getters/Setters\n methods\n function value = get.CtrSize(this)\n value = ContourFitting_(this.id, 'get', 'CtrSize');\n end\n function set.CtrSize(this, value)\n ContourFitting_(this.id, 'set', 'CtrSize', value);\n end\n\n function value = get.FDSize(this)\n value = ContourFitting_(this.id, 'get', 'FDSize');\n end\n function set.FDSize(this, value)\n ContourFitting_(this.id, 'set', 'FDSize', value);\n end\n end\n\n %% Static functions\n methods (Static)\n function out = contourSampling(src, numElt)\n %CONTOURSAMPLING Contour sampling\n %\n % out = cv.ContourFitting.contourSampling(src, numElt)\n %\n % ## Input\n % * __src__ input contour, vector of 2D points stored in numeric\n % array Nx2/Nx1x2/1xNx2 or cell array of 2-element vectors\n % `{[x,y], ...}`.\n % * __NumElt__ number of points in `out` contour.\n %\n % ## Output\n % * __out__ output contour with `numElt` points.\n %\n % See also: cv.findContours, cv.approxPolyDP\n %\n out = ContourFitting_(0, 'contourSampling', src, numElt);\n end\n\n function dst = fourierDescriptor(src, varargin)\n %FOURIERDESCRIPTOR Fourier descriptors for planed closed curves\n %\n % dst = cv.ContourFitting.fourierDescriptor(src)\n % dst = cv.ContourFitting.fourierDescriptor(src, 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __src__ input contour, vector of 2D points stored in numeric\n % array Nx2/Nx1x2/1xNx2 or cell array of 2-element vectors\n % `{[x,y], ...}`.\n %\n % ## Output\n % * __dst__ 2-channel array of type `single` and length `NumElt`.\n %\n % ## Options\n % * __NumElt__ number of rows in `dst` or cv.getOptimalDFTSize\n % rows if `NumElt=-1`. default -1\n % * __NumFD__ number of FD to return in `dst`,\n % `dst = [FD(1...NumFD/2) FD(NumFD/2-NumElt+1...:NumElt)]`.\n % default -1 (return all of FD as is).\n %\n % For more details about this implementation, please see\n % [PersoonFu1977].\n %\n % See also: cv.dft\n %\n dst = ContourFitting_(0, 'fourierDescriptor', src, varargin{:});\n end\n\n function dst = transformFD(src, t, varargin)\n %TRANSFORMFD Transform a contour\n %\n % dst = cv.ContourFitting.transformFD(src, t)\n % dst = cv.ContourFitting.transformFD(src, t, 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __src__ contour, or Fourier descriptors if `FD` is true.\n % * __t__ 1x5 transform matrix given by\n % cv.ContourFitting.estimateTransformation method.\n %\n % ## Output\n % * __dst__ 2-channel matrix of type `double` and `NumElt` rows.\n %\n % ## Options\n % * __FD__ if true `src` are Fourier descriptors, if false `src`\n % is a contour. default true\n %\n % See also: cv.ContourFitting.estimateTransformation,\n % cv.ContourFitting.contourSampling,\n % cv.ContourFitting.fourierDescriptor\n %\n dst = ContourFitting_(0, 'transformFD', src, t, varargin{:});\n end\n end\n\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/opencv_contrib/+cv/ContourFitting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.686833920631055}} {"text": "function [ a, seed ] = wathen_gb ( nx, ny, n, seed )\n\n%*****************************************************************************80\n%\n%% WATHEN_GB returns the Wathen matrix, using general banded (GB) storage.\n%\n% Discussion:\n%\n% The Wathen matrix is a finite element matrix which is sparse.\n%\n% The entries of the matrix depend in part on a physical quantity\n% related to density. That density is here assigned random values between\n% 0 and 100.\n%\n% The matrix order N is determined by the input quantities NX and NY,\n% which would usually be the number of elements in the X and Y directions.\n% The value of N is\n%\n% N = 3*NX*NY + 2*NX + 2*NY + 1,\n%\n% The matrix is the consistent mass matrix for a regular NX by NY grid\n% of 8 node serendipity elements.\n%\n% The local element numbering is\n%\n% 3--2--1\n% | |\n% 4 8\n% | |\n% 5--6--7\n%\n% Here is an illustration for NX = 3, NY = 2:\n%\n% 23-24-25-26-27-28-29\n% | | | |\n% 19 20 21 22\n% | | | |\n% 12-13-14-15-16-17-18\n% | | | |\n% 8 9 10 11\n% | | | |\n% 1--2--3--4--5--6--7\n%\n% For this example, the total number of nodes is, as expected,\n%\n% N = 3 * 3 * 2 + 2 * 2 + 2 * 3 + 1 = 29\n%\n% The matrix is symmetric positive definite for any positive values of the\n% density RHO(X,Y).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 July 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Nicholas Higham,\n% Algorithm 694: A Collection of Test Matrices in MATLAB,\n% ACM Transactions on Mathematical Software,\n% Volume 17, Number 3, September 1991, pages 289-305.\n%\n% Andrew Wathen,\n% Realistic eigenvalue bounds for the Galerkin mass matrix,\n% IMA Journal of Numerical Analysis,\n% Volume 7, Number 4, October 1987, pages 449-457.\n%\n% Parameters:\n%\n% Input, integer NX, NY, values which determine the size of the matrix.\n%\n% Input, integer N, the number of variables.\n%\n% Input/output, integer SEED, the random number seed.\n%\n% Output, real A(9*NX+13,N), the matrix.\n%\n if ( nargin < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'WATHEN_GB - Fatal error!\\n' );\n fprintf ( 1, ' Not enough input.\\n' );\n error ( 'WATHEN_GB - Fatal error!' );\n end\n\n if ( nargin < 2 )\n ny = nx;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' NY was not supplied. Setting NY = NX = %d.\\n', ny );\n end\n\n if ( nargin < 3 )\n n = wathen_order ( nx, ny );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N was not supplied. N = %d\\n', n );\n end\n\n if ( nargin < 4 )\n seed = 123456789;\n end\n\n ml = 3 * nx + 4;\n mu = 3 * nx + 4;\n\n a = zeros ( 2 * ml + mu + 1, n );\n\n em = [\n 6.0, -6.0, 2.0, -8.0, 3.0, -8.0, 2.0, -6.0;\n -6.0, 32.0, -6.0, 20.0, -8.0, 16.0, -8.0, 20.0;\n 2.0, -6.0, 6.0, -6.0, 2.0, -8.0, 3.0, -8.0;\n -8.0, 20.0, -6.0, 32.0, -6.0, 20.0, -8.0, 16.0;\n 3.0, -8.0, 2.0, -6.0, 6.0, -6.0, 2.0, -8.0;\n -8.0, 16.0, -8.0, 20.0, -6.0, 32.0, -6.0, 20.0;\n 2.0, -8.0, 3.0, -8.0, 2.0, -6.0, 6.0, -6.0;\n -6.0, 20.0, -8.0, 16.0, -8.0, 20.0, -6.0, 32.0 ]';\n\n node = zeros(8,1);\n\n for j = 1 : ny\n\n for i = 1 : nx\n%\n% For the element (I,J), determine the indices of the 8 nodes.\n%\n node(1) = 3 * j * nx + 2 * j + 2 * i + 1;\n node(2) = node(1) - 1;\n node(3) = node(1) - 2;\n\n node(4) = ( 3 * j - 1 ) * nx + 2 * j + i - 1;\n node(8) = node(4) + 1;\n\n node(5) = ( 3 * j - 3 ) * nx + 2 * j + 2 * i - 3;\n node(6) = node(5) + 1;\n node(7) = node(5) + 2;\n\n [ rho, seed ] = r8_uniform_01 ( seed );\n rho = 100.0 * rho;\n\n for krow = 1 : 8\n for kcol = 1 : 8\n ii = node(krow);\n jj = node(kcol);\n a(ii-jj+ml+mu+1,jj) = a(ii-jj+ml+mu+1,jj) + rho * em(krow,kcol);\n end\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/wathen/wathen_gb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6868339125760045}} {"text": "%DEMEV1\tDemonstrate Bayesian regression for the MLP.\n%\n%\tDescription\n%\tThe problem consists an input variable X which sampled from a\n%\tGaussian distribution, and a target variable T generated by computing\n%\tSIN(2*PI*X) and adding Gaussian noise. A 2-layer network with linear\n%\toutputs is trained by minimizing a sum-of-squares error function with\n%\tisotropic Gaussian regularizer, using the scaled conjugate gradient\n%\toptimizer. The hyperparameters ALPHA and BETA are re-estimated using\n%\tthe function EVIDENCE. A graph is plotted of the original function,\n%\tthe training data, the trained network function, and the error bars.\n%\n%\tSee also\n%\tEVIDENCE, MLP, SCG, DEMARD, DEMMLP1\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\nclc;\ndisp('This demonstration illustrates the application of Bayesian')\ndisp('re-estimation to determine the hyperparameters in a simple regression')\ndisp('problem. It is based on a local quadratic approximation to a mode of')\ndisp('the posterior distribution and the evidence maximization framework of')\ndisp('MacKay.')\ndisp(' ')\ndisp('First, we generate a synthetic data set consisting of a single input')\ndisp('variable x sampled from a Gaussian distribution, and a target variable')\ndisp('t obtained by evaluating sin(2*pi*x) and adding Gaussian noise.')\ndisp(' ')\ndisp('Press any key to see a plot of the data together with the sine function.')\npause;\n\n% Generate the matrix of inputs x and targets t.\n\nndata = 16;\t\t\t% Number of data points.\nnoise = 0.1;\t\t\t% Standard deviation of noise distribution.\nrandn('state', 0);\nx = 0.25 + 0.07*randn(ndata, 1);\nt = sin(2*pi*x) + noise*randn(size(x));\n\n% Plot the data and the original sine function.\nh = figure;\nnplot = 200;\nplotvals = linspace(0, 1, nplot)';\nplot(x, t, 'ok')\nxlabel('Input')\nylabel('Target')\nhold on\naxis([0 1 -1.5 1.5])\nfplot('sin(2*pi*x)', [0 1], '-g')\nlegend('data', 'function');\n\ndisp(' ')\ndisp('Press any key to continue')\npause; clc;\n\ndisp('Next we create a two-layer MLP network having 3 hidden units and one')\ndisp('linear output. The model assumes Gaussian target noise governed by an')\ndisp('inverse variance hyperparmeter beta, and uses a simple Gaussian prior')\ndisp('distribution governed by an inverse variance hyperparameter alpha.')\ndisp(' ');\ndisp('The network weights and the hyperparameters are initialised and then')\ndisp('the weights are optimized with the scaled conjugate gradient')\ndisp('algorithm using the SCG function, with the hyperparameters kept')\ndisp('fixed. After a maximum of 500 iterations, the hyperparameters are')\ndisp('re-estimated using the EVIDENCE function. The process of optimizing')\ndisp('the weights with fixed hyperparameters and then re-estimating the')\ndisp('hyperparameters is repeated for a total of 3 cycles.')\ndisp(' ')\ndisp('Press any key to train the network and determine the hyperparameters.')\npause;\n\n% Set up network parameters.\nnin = 1;\t\t% Number of inputs.\nnhidden = 3;\t\t% Number of hidden units.\nnout = 1;\t\t% Number of outputs.\nalpha = 0.01;\t\t% Initial prior hyperparameter. \nbeta_init = 50.0;\t% Initial noise hyperparameter.\n\n% Create and initialize network weight vector.\nnet = mlp(nin, nhidden, nout, 'linear', alpha, beta_init);\n\n% Set up vector of options for the optimiser.\nnouter = 3;\t\t\t% Number of outer loops.\nninner = 1;\t\t\t% Number of innter loops.\noptions = zeros(1,18);\t\t% Default options vector.\noptions(1) = 1;\t\t\t% This provides display of error values.\noptions(2) = 1.0e-7;\t\t% Absolute precision for weights.\noptions(3) = 1.0e-7;\t\t% Precision for objective function.\noptions(14) = 500;\t\t% Number of training cycles in inner loop. \n\n% Train using scaled conjugate gradients, re-estimating alpha and beta.\nfor k = 1:nouter\n net = netopt(net, options, x, t, 'scg');\n [net, gamma] = evidence(net, x, t, ninner);\n fprintf(1, '\\nRe-estimation cycle %d:\\n', k);\n fprintf(1, ' alpha = %8.5f\\n', net.alpha);\n fprintf(1, ' beta = %8.5f\\n', net.beta);\n fprintf(1, ' gamma = %8.5f\\n\\n', gamma);\n disp(' ')\n disp('Press any key to continue.')\n pause;\nend\n\nfprintf(1, 'true beta: %f\\n', 1/(noise*noise));\n\ndisp(' ')\ndisp('Network training and hyperparameter re-estimation are now complete.') \ndisp('Compare the final value for the hyperparameter beta with the true') \ndisp('value.')\ndisp(' ')\ndisp('Notice that the final error value is close to the number of data')\ndisp(['points (', num2str(ndata),') divided by two.'])\ndisp(' ')\ndisp('Press any key to continue.')\npause; clc;\ndisp('We can now plot the function represented by the trained network. This')\ndisp('corresponds to the mean of the predictive distribution. We can also')\ndisp('plot ''error bars'' representing one standard deviation of the')\ndisp('predictive distribution around the mean.')\ndisp(' ')\ndisp('Press any key to add the network function and error bars to the plot.')\npause;\n\n% Evaluate error bars.\n[y, sig2] = netevfwd(mlppak(net), net, x, t, plotvals);\nsig = sqrt(sig2);\n\n% Plot the data, the original function, and the trained network function.\n[y, z] = mlpfwd(net, plotvals);\nfigure(h); hold on;\nplot(plotvals, y, '-r')\nxlabel('Input')\nylabel('Target')\nplot(plotvals, y + sig, '-b');\nplot(plotvals, y - sig, '-b');\nlegend('data', 'function', 'network', 'error bars');\n\ndisp(' ')\ndisp('Notice how the confidence interval spanned by the ''error bars'' is')\ndisp('smaller in the region of input space where the data density is high,')\ndisp('and becomes larger in regions away from the data.')\ndisp(' ')\ndisp('Press any key to end.')\npause; clc; close(h); \n%clear all\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/netlab3.3/demev1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6868339066856486}} {"text": "% function [x1,x2,P1,P2] = make_synthetic_data(N,range_model,range_image,verbose)\n% makes a synthetic 3D model and makes two projective images of the model\n% using arbitrary projective cameras Pi=[M|t]. The second cameras are normalized\n% to Pi = Pi / Pi_{34}.\n% inputs: \n% N 1x1 (optional) the maximum number of correspondences to generate. \n% range_model 2x1 (optional) defines a bounding box (starting from origin) containing the model\n% range_image 2x1 (optional) the size of the output image(scaling on correspondences)\n% verbose 1x1 (optional) plots the generated model and images\n% outputs:\n% x1 3x1 homogeneous coordinates of the correspondences in image 1\n% x2 3x1 homogeneous coordinates of the correspondences in image 2\n% P1 3x4 the camera that generates x1(up to an affine transformation)\n% P2 3x4 the camera that generates x2(up to an affine transformation)\n% \n% Author: Omid Aghazadeh, KTH(Royal Institute of Technology), 2010/05/09\nfunction [x1,x2,P1,P2] = make_synthetic_data(N,range_model,range_image,verbose)\nif nargin < 1, N = 100; end\nif nargin < 2, range_model = [10;10;10]; end\nif nargin < 3, range_image = [640;480]; end\nif nargin < 4, verbose = 1; end\nX = rand(3,N); X = (X - repmat(min(X,[],2),1,N)) .* repmat(range_model ./ (max(X,[],2) - min(X,[],2)),1,N);\nX = [X; ones(1,N)];\nP1 = rand(3,4); P1(end) = 1;\nP2 = rand(3,4); P2(end) = 1; %avoid cameras at infinity\nx1 = P1*X; x1 = x1./repmat(x1(3,:),3,1); x2 = P2*X; x2 = x2./repmat(x2(3,:),3,1); \nixinv = sum(isinf(x1) | isnan(x1) | isinf(x2) | isnan(x2) | abs(x1) > 1e3 | abs(x2) > 1e3,1 )>0 ;\nx1 = x1(:,~ixinv); x2 = x2(:,~ixinv); N = size(x1,2);\nx1 = (x1-repmat([min(x1(1:2,:),[],2);0],1,N)).* repmat([range_image./(max(x1(1:2,:),[],2) - min(x1(1:2,:),[],2));1],1,N); \n\nx2 = (x2-repmat([min(x2(1:2,:),[],2);0],1,N)).* repmat([range_image./(max(x2(1:2,:),[],2) - min(x2(1:2,:),[],2));1],1,N); \nif verbose\n figure(1); subplot(1,3,1); plot3(X(1,:),X(2,:),X(3,:),'b.'); title('generated 3D model');\n subplot(1,3,2); plot(x1(1,:),x1(2,:),'rx'); title('generated first image');\n subplot(1,3,3); plot(x2(1,:),x2(2,:),'gx'); title('generated second image');\nend\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/27541-fundamental-matrix-computation/make_synthetic_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6868339040006317}} {"text": "function test03 ( dim_num, level_max )\n \n%*****************************************************************************80\n%\n%% TEST03 call SPARSE_GRID_GL to create a Gauss-Legendre sparse grid.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 26 September 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer LEVEL_MAX, the level.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST03:\\n' );\n fprintf ( 1, ' SPARSE_GRID_GL makes a sparse Gauss-Legendre grid.\\n' );\n \n level_min = max ( 0, level_max + 1 - dim_num );\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LEVEL_MIN = %d\\n', level_min );\n fprintf ( 1, ' LEVEL_MAX = %d\\n', level_max );\n fprintf ( 1, ' Spatial dimension DIM_NUM = %d\\n', dim_num );\n%\n% Determine the number of points.\n%\n point_num = sparse_grid_gl_size ( dim_num, level_max );\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of unique points in the grid = %d\\n', point_num );\n%\n% Compute the weights and points.\n%\n [ grid_weight, grid_point ] = sparse_grid_gl ( dim_num, level_max, point_num );\n%\n% Print them out.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Grid weights:\\n' );\n fprintf ( 1, '\\n' );\n for point = 1 : point_num\n fprintf ( 1, ' %4d %10f\\n', point, grid_weight(point) );\n end\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Grid points:\\n' );\n fprintf ( 1, '\\n' );\n for point = 1 : point_num\n fprintf ( 1, ' %4d', point );\n for dim = 1 : dim_num\n fprintf ( 1, '%10f', grid_point(dim,point) );\n end\n fprintf ( 1, '\\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_gl/sparse_grid_gl_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522815, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6868338932605637}} {"text": "function res = parallelEdge(edge, dist)\n%PARALLELEDGE Edge parallel to another edge.\n%\n% EDGE2 = parallelEdge(EDGE, DIST)\n% Computes the edge parallel to the input edge EDGE and located at the\n% given signed distance DIST.\n%\n% Example\n% obox = [30 40 80 40 30];\n% figure; hold on; axis equal;\n% drawOrientedBox(obox, 'LineWidth', 2);\n% edge1 = centeredEdgeToEdge(obox([1 2 3 5]));\n% edge2 = centeredEdgeToEdge(obox([1 2 4 5])+[0 0 0 90]);\n% drawEdge(edge1, 'LineWidth', 2, 'color', 'g');\n% drawEdge(edge2, 'LineWidth', 2, 'color', 'g');\n% drawEdge(parallelEdge(edge1, -30), 'LineWidth', 2, 'color', 'k');\n% drawEdge(parallelEdge(edge2, -50), 'LineWidth', 2, 'color', 'k');\n%\n% See also \n% edges2d, parallelLine, drawEdge, centeredEdgeToEdge, edgeToLine\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2012-07-31, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012-2022 INRA - Cepia Software Platform\n\n% compute the line parallel to the supporting line of edge\nline = parallelLine(edgeToLine(edge), dist);\n\n% result edge is given by line positions 0 and 1.\nres = [line(:, 1:2) line(:, 1:2)+line(:, 3:4)];\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/parallelEdge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.6868338454068611}} {"text": "function sparse_test02 ( )\n\n%*****************************************************************************80\n%\n%% SPARSE_TEST02 demonstrates a simple use of the SPARSE matrix facility.\n%\n% Discussion:\n%\n% This is a nice but very simple example. \n%\n% Note in this example that we define three sparse matrices,\n% SUP, DIAG, and SUB, and then define A as the sum of those matrices.\n%\n% However, again, each time we define a sparse matrix, we are assuming\n% we have all the information available at one time.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 August 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% George Lindfield, John Penny,\n% Numerical Methods Using MATLAB,\n% Prentice Hall, 1999\n% \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPARSE_TEST02:\\n' );\n fprintf ( 1, ' Demonstrate the use of MATLAB''s SPARSE facility\\n' );\n fprintf ( 1, ' to define a sparse matrix, and solve an associated\\n' );\n fprintf ( 1, ' linear system.\\n' );\n\n n = 100;\n%\n% We set up the three diagonals of the -1, 2, -1 matrix.\n%\n sup = sparse ( 1:n-1, 2:n, -1.0, n, n );\n diag = sparse ( 1:n, 1:n, 2.0, n, n );\n sub = sparse ( 2:n, 1:n-1, -1.0, n, n );\n%\n% A is the matrix whose superdiagonal, diagonal, and subdiagonal\n% have been set above. Because SUP, DIAG and SUB are sparse,\n% A will \"inherit\" this property.\n%\n A = sup + diag + sub;\n%\n% Set up a right hand side b that defines a linear system whose\n% solution is [ 1, 2, 3, ..., n ].\n%\n b(1:n-1,1) = 0.0;\n b(n,1) = n + 1;\n%\n% Use MATLAB's backslash command to solve the linear system.\n% Because MATLAB \"knows\" that A is a sparse matrix, it will\n% automatically do the efficient thing.\n%\n x = A \\ b;\n%\n% Print the solution.\n%\n 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/sparse/sparse_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.8006920116079208, "lm_q1q2_score": 0.6868080753001804}} {"text": "% OZDEMO\n% This program creates the Ornstein-Zernike example in Chapter 3.\n% [H,C]=OZDEMO returns the solution on a grid with a mesh\n% spacing of 1/256.\n%\nfunction [h,c]=ozdemo\nglobal L U rho\nn=257;\nepsilon=.1; sigma=2.0; rho=.2; beta=10; L=9;\ndx=L/(n-1); r=0:dx:L; r=r'; \n% \n% Compute the potential and store it in a global variable.\n%\nU=elj(r,sigma,epsilon,beta);\n%\ntol=[1.d-8,1.d-8];\nx=zeros(2*n,1);\nparms=[40,80,-.1];\n[sol, it_hist, ierr] = nsoli(x,'oz',tol);\n%\n% Unpack h and c.\n%\nh=sol(1:n); c=sol(n+1:2*n);\n%\n% Plot the solution.\n%\nfigure(1)\nsubplot(1,2,1)\nplot(r,h,'-');\nylabel('h','Rotation',1);\nxlabel('r');\nsubplot(1,2,2)\nplot(r,c,'-');\nylabel('c','Rotation',1);\nxlabel('r');\n%\n% Do a second solve with constant forcing terms.\n% Are you getting the same results each time? \n%\nfb=it_hist(1,1);\nparms=[40,80,-.1]; x=zeros(2*n,1);\n[sola, it_hist1, ierr] = nsoli(x,'oz',tol,parms);\nnorm(sola-sol)\n%\n% plot residual vs iteration counter\n%\nfigure(2)\nni=length(it_hist(:,1));\nn1=length(it_hist1(:,1));\nsemilogy(0:ni-1,it_hist(:,1)/fb,'-',...\n0:n1-1,it_hist1(:,1)/fb,'--');\nlegend('default','.1');\nxlabel('Nonlinear iterations');\nylabel('Relative residual');\n%\n% plot residual vs function counter\n%\nfigure(3)\nsemilogy(it_hist(:,2),it_hist(:,1)/fb,'-',...\nit_hist1(:,2),it_hist1(:,1)/fb,'--');\nxlabel('Function evaluations');\nylabel('Relative residual');\nlegend('default','.1');\n\n%\nfunction u=elj(r,sigma,epsilon,beta)\nn2=length(r);\nra=r(2:n2);\nr12=(sigma./ra).^12; r6=(sigma./ra).^6;\nua=exp(-4*beta*epsilon*(r12-r6));\nu=[0,ua']';\n\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/SNEwNM/Chapter3/ozdemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.6868080551992827}} {"text": "function [ o, x, w ] = cn_leg_03_xiu ( n )\n\n%*****************************************************************************80\n%\n%% CN_LEG_03_XIU implements the Xiu precision 3 rule for region CN_LEG.\n%\n% Discussion:\n%\n% The rule has order\n%\n% O = 2 * N.\n%\n% The rule has precision P = 3.\n%\n% CN_LEG is the cube [-1,+1]^N with the Legendre weight function\n%\n% w(x) = 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Dongbin Xiu,\n% Numerical integration formulas of degree two,\n% Applied Numerical Mathematics,\n% Volume 58, 2008, pages 1515-1520.\n%\n% Parameters:\n%\n% Input, integer N, the spatial dimension.\n%\n% Input, integer O, the order.\n%\n% Output, real X(N,O), the abscissas.\n%\n% Output, real W(O), the weights.\n%\n o = 2 * n;\n\n x = zeros ( n, o );\n w = zeros ( o, 1 );\n\n expon = 0;\n volume = c1_leg_monomial_integral ( expon );\n volume = volume ^ n;\n\n for j = 1 : o\n\n i = 0;\n for r = 1 : floor ( n / 2 )\n arg = ( 2 * r - 1 ) * j * pi / n;\n i = i + 1;\n x(i,j) = sqrt ( 2.0 ) * cos ( arg ) / sqrt ( 3.0 );\n i = i + 1;\n x(i,j) = sqrt ( 2.0 ) * sin ( arg ) / sqrt ( 3.0 );\n end\n\n if ( i < n )\n i = i + 1;\n x(i,j) = sqrt ( 2.0 ) * r8_mop ( j ) / sqrt ( 3.0 );\n if ( n == 1 )\n x(i,j) = x(i,j) / sqrt ( 2.0 );\n end\n end\n\n end\n\n w(1:o) = volume / o;\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/cn_leg_03_xiu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.6868080455939675}} {"text": "% THIS PROGRAM IS FOR IMPLEMENTATION OF DISCRETE TIME PROCESS UNSCENTED KALMAN FILTER\n% FOR GAUSSIAN AND LINEAR STOCHASTIC DIFFERENCE EQUATION.\n% (19 JULY 2005).\n% UNSCENTED KALMAN FILTER (UKF) AT ITS BEST.\n%(Under Nonlinear conditions,UNSCENTED KALMAN FILTER \n% performs to a much better extent as compared to EXTENDED KALMAN FILTER).\n\nclc; close all; clear all;\n\nformat long g;\nXo = [1; 0; 0; 0; 0; 0; 0; 0; 0; 0];\nnx = length(Xo);\nbeta = 2;\nelfa = 1*(10^-1);\nlambda = (((elfa^2)*(nx)) - nx);\nmn1 = mean(Xo); %FIRST STEP\nCV1 = (Xo-mn1)*(Xo-mn1)';\n%CV1 = (Xo)*(Xo)';\nPO = CV1;\nFX = size(CV1);\nVTt = [1 0 0 0 0 0 0 0 0 0]';\nADP1 = randn(1,200);\nmn2 = mean(VTt);\nNTt = [1 0 0 0 0 0 0 0 0 0]';\nADP2 = randn(1,200);\nmn3 = mean(NTt);\nQo = (VTt-mn2)*(VTt-mn2)';\nRo = (NTt-mn3)*(NTt-mn3)';\n%Qo = (VTt)*(VTt)';\n%Ro = (NTt)*(NTt)';\nFX = zeros(10,10);\nPAO = [PO FX FX; FX Qo FX;FX FX Ro];\nXao = [mn1 0 0]';\nlam = sqrt((elfa^2)*(nx));\n\nWmo = lambda/(nx+lambda);\nWmi = 1/(2*(nx+lambda));\nWmin = 1/(2*(nx+lambda));\n\nWco = (lambda/(nx+lambda)) + (1-(elfa^2)+ beta);\nWci = Wmi;\nWcin = Wmin;\n\n%CALCULATION OF SIGMA POINTS\n[Sg11,Sg12,Sg13,Sg21,Sg22,Sg23,Sg31,Sg32,Sg33] = sigmacal(mn1,CV1,mn2,Qo,mn3,Ro,lam);\n\n%TIME UPDATE EQUATIONS.\n[Xinew1,Xinew2,Xinew3,Yinew1,Yinew2,Yinew3,Xbark,Ybark,Pbark] = TMUPDT(Wmo,Wmi,Wmin,Wco,Wci,Wcin,Sg11,Sg12,Sg13,Sg21,Sg22,Sg23,Sg31,Sg32,Sg33);\n\n%MEASUREMENT UPDATE EQUATIONS.\n[KGain,XNEW,PT1,PT2,PT3] = MSMTUPDT(Xinew1,Xinew2,Xinew3,Yinew1,Yinew2,Yinew3,Xbark,Ybark,Pbark,Wco,Wci,Wcin,Xo,VTt);\n\nfor ii = 1:1:100\n \n VTt = [ADP1(ii+1) 0 0 0 0 0 0 0 0 0]';\n NTt = [ADP2(ii+1) 0 0 0 0 0 0 0 0 0]';\n \n %CV1 = (XNEW)*(XNEW)';\n mn1 = mean(XNEW);\n mn2 = mean(VTt);\n mn3 = mean(NTt);\n % Qo = (VTt)*(VTt)';\n % Ro = (NTt)*(NTt)';\n \n CV1 = (XNEW-mn1)*(XNEW-mn1)';\n Qo = (VTt-mn2)*(VTt-mn2)';\n Ro = (NTt-mn3)*(NTt-mn3)';\n \n lam = sqrt((elfa^2)*(nx));\n \n [Sg11,Sg12,Sg13,Sg21,Sg22,Sg23,Sg31,Sg32,Sg33] = sigmacal(mn1,CV1,mn2,Qo,mn3,Ro,lam);\n \n [Xinew1,Xinew2,Xinew3,Yinew1,Yinew2,Yinew3,Xbark,Ybark,Pbark] = TMUPDT(Wmo,Wmi,Wmin,Wco,Wci,Wcin,Sg11,Sg12,Sg13,Sg21,Sg22,Sg23,Sg31,Sg32,Sg33);\n \n [KGain,XNEW,PT1,PT2,PT3,YNEW] = MSMTUPDT(Xinew1,Xinew2,Xinew3,Yinew1,Yinew2,Yinew3,Xbark,Ybark,Pbark,Wco,Wci,Wcin,XNEW,VTt);\n \n INP1(ii) = XNEW(1,1);\n INP2(ii) = YNEW(1,1);\n \nend\n\nT = 1:1:100; \nfigure(1); subplot(211); plot(real(INP1)); title('ORIGINAL SIGNAL');\nsubplot(212); plot(real(INP2)); title('ESTIMATED SIGNAL (UNDER Nonlinear MODEL)');\n\nfigure(2); plot(T,abs(INP1),T,abs(INP2)); title('Combined plot'); legend('original','estimated');\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/11145-unscented-kalman-filter/prog1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6867926276669524}} {"text": "function [Pw] = RFT_Pval(u,k,c,fwhm,L,type,dof)\n% computes Pval according to Friston et al. (1996), Eq. 1-4.\n% [Pw] = RFT_Pval(u,k,c,fwhm,L)\n% This function ca be called to derive the p-value at different levels of\n% inference, i.e.:\n% - P_peak = RFT_Pval(u,0,1,fwhm,L)\n% - P_cluster = RFT_Pval(U,k,1,fwhm,L), where U was the set-inducing\n% threshold, and k is the observed spatial extent of the cluster.\n% - P_set = RFT_Pval(U,K,c,fwhm,L), where U and K were the set-inducing\n% thresholds, and c was the number of observed upcrossing clusters\n% IN:\n% - u: RF value\n% - k: cluster's spatial extent\n% - c: number of upcrossing clusters\n% - fwhm: estimated FWHM\n% - L: search volume\n% - type: type of RF. Can be set to 'norm' (normal, default), 't'\n% (Student) or 'F' (Fisher).\n% - dof: degrees of freedom (only relevant for 't' or 'F' fields).\n% OUT:\n% - Pw: the ensuing p-value\n\nEC = RFT_expectedTopo(u,L,fwhm,1,type,dof);\nswitch type\n case 'norm'\n P0 = 1-VBA_spm_Ncdf(u,0,1);\n case 't'\n P0 = 1-VBA_spm_Tcdf(u,dof);\n case 'F'\n P0 = 1-VBA_spm_Fcdf(u,dof(1),dof(2));\nend\nbeta = (gamma(3/2).*EC./(L.*P0)).^2;\nPnk = exp(-beta.*k.^2);\nif k == 0, Pnk = 1; end; % solves the numerical issue when P0=0 \nPw = 1;\nfor i=0:c-1\n Pw = Pw - myPoissonPMF(i,EC.*Pnk);\nend\n\nfunction p = myPoissonPMF(x,Ex)\np = (Ex.^x).*exp(-Ex)./factorial(x);\n\n% function p = myPoissonCDF(x,Ex)\n% p = 1 - gammainc(Ex,x+1);\n\n\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/modules/random_field_theory/RFT_Pval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6867917409934317}} {"text": "function euler = rotMat2euler(R)\n%ROTMAT2EULER Converts a rotation matrix orientation to ZYX Euler angles\n%\n% euler = rotMat2euler(R)\n%\n% Converts a rotation matrix orientation to ZYX Euler angles where phi is\n% a rotation around X, theta around Y and psi around Z.\n%\n% For more information see:\n% http://www.x-io.co.uk/node/8#quaternions\n%\n% Date Author Notes\n% 27/09/2011 SOH Madgwick Initial release\n\n phi = atan2(R(3,2,:), R(3,3,:) );\n theta = -atan(R(3,1,:) ./ sqrt(1-R(3,1,:).^2) );\n psi = atan2(R(2,1,:), R(1,1,:) );\n\n euler = [phi(1,:)' theta(1,:)' psi(1,:)'];\nend\n\n", "meta": {"author": "xioTechnologies", "repo": "Oscillatory-Motion-Tracking-With-x-IMU", "sha": "314208abbb592c9623ad0940138ea597447774a9", "save_path": "github-repos/MATLAB/xioTechnologies-Oscillatory-Motion-Tracking-With-x-IMU", "path": "github-repos/MATLAB/xioTechnologies-Oscillatory-Motion-Tracking-With-x-IMU/Oscillatory-Motion-Tracking-With-x-IMU-314208abbb592c9623ad0940138ea597447774a9/quaternion_library/rotMat2euler.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.7662936430859598, "lm_q1q2_score": 0.6867917383334583}} {"text": "options.filter = 'linear'; \noptions.filter = '9-7';\n\n%% 1D %%\nn = 1024;\nx = linspace(0,1,n)';\nx = cos(10*pi*x) + (x>.4);\n\nJmin = 6;\n\noptions.ti = 0;\ny = perform_lifting_transform(x, Jmin, +1, options);\nx1 = perform_lifting_transform(y, Jmin, -1, options);\ndisp(['Error(should be 0)=' num2str(norm(x-x1)/norm(x))]);\n\noptions.ti = 1;\ny = perform_lifting_transform(x, Jmin, +1, options);\nx1 = perform_lifting_transform(y, Jmin, -1, options);\ndisp(['Error(should be 0)=' num2str(norm(x-x1)/norm(x))]);\n\n\n%% test for RWT\noptions.ti = 1;\noptions.use_mex = 1;\noptions.wavelet_vm = 3;\noptions.wavelet_type = 'daubechies';\ny = perform_wavelet_transform(x, Jmin, +1, options);\nx1 = perform_wavelet_transform(y, Jmin, -1, options);\ndisp(['Error(should be 0)=' num2str(norm(x-x1)/norm(x))]);\n\n%% test for wavelab\noptions.ti = 1;\noptions.use_mex = 0;\noptions.wavelet_vm = 3;\noptions.wavelet_type = 'daubechies';\ny = perform_wavelet_transform(x, Jmin, +1, options);\nx1 = perform_wavelet_transform(y, Jmin, -1, options);\ndisp(['Error(should be 0)=' num2str(norm(x-x1)/norm(x))]);\n\n\nreturn;\n\n%% 2D %%\nn = 256;\nJmin = 3;\nx = load_image('lena', n);\nx = rescale(x);\n\noptions.ti = 0;\ny = perform_lifting_transform(x, Jmin, +1, options);\nx1 = perform_lifting_transform(y, Jmin, -1, options);\ndisp(['Error(should be 0)=' num2str(norm(x-x1)/norm(x))]);\n\noptions.ti = 1;\ny = perform_lifting_transform(x, Jmin, +1, options);\nx1 = perform_lifting_transform(y, Jmin, -1, options);\ndisp(['Error(should be 0)=' num2str(norm(x-x1)/norm(x))]);\n", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_wavelets/tests/test_lifting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7662936430859598, "lm_q1q2_score": 0.6867917340864071}} {"text": "function [l, u] = ComputeDistanceExtremes(X, a, b, M)\n% [l, u] = ComputeDistanceExtremes(X, a, b, M)\n%\n% Computes sample histogram of the distances between rows of X and returns\n% the value of these distances at the a^th and b^th percentils. This\n% method is used to determine the upper and lower bounds for\n% similarity / dissimilarity constraints. \n%\n% X: (n x m) data matrix \n% a: lower bound percentile between 1 and 100\n% b: upper bound percentile between 1 and 100\n% M: Mahalanobis matrix to compute distances \n%\n% Returns l: distance corresponding to a^th percentile\n% u: distance corresponding the b^th percentile\n\nif (a < 1 || a > 100),\n error('a must be between 1 and 100')\nend\nif (b < 1 || b > 100),\n error('b must be between 1 and 100')\nend\n\nn = size(X, 1);\n\nnum_trials = min(100, n*(n-1)/2);\n\n% we will sample with replacement\ndists = zeros(num_trials, 1);\nfor (i=1:num_trials),\n j1 = ceil(rand(1)*n);\n j2 = ceil(rand(1)*n); \n dists(i) = (X(j1,:) - X(j2,:))*M*(X(j1,:) - X(j2,:))';\nend\n\n\n[f, c] = hist(dists, 100);\nl = c(floor(a));\nu = c(floor(b));", "meta": {"author": "zhunzhong07", "repo": "IDE-baseline-Market-1501", "sha": "8be027b5e45adce1d8ea381cc5a17ec20ed521e5", "save_path": "github-repos/MATLAB/zhunzhong07-IDE-baseline-Market-1501", "path": "github-repos/MATLAB/zhunzhong07-IDE-baseline-Market-1501/IDE-baseline-Market-1501-8be027b5e45adce1d8ea381cc5a17ec20ed521e5/market_evaluation/KISSME/toolbox/lib/itml/ComputeDistanceExtremes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.7662936430859598, "lm_q1q2_score": 0.6867917255923044}} {"text": "function [in2] = ft22in2(ft2)\n% Convert area from square feet to square inches.\n% Chad A. Greene 2012\nin2 = ft2*144;", "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/35258-unit-converters/unit_converters/ft22in2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6867681671779418}} {"text": "function [EV, EVal] = ncuts(A, n_ev)\n% Computes the n_ev smallest (non-zero) eigenvectors and eigenvalues of the \n% of the Laplacian of A\n\nD = sparse(1:size(A,1), 1:size(A,1), full(sum(A, 1)), size(A,1), size(A,2));\n\nopts.issym = 0;\nopts.isreal = 1;\nopts.disp = 0;\nnvec = n_ev+1;\n\n[EV, EVal] = eigs((D - A) + (10^-10) * speye(size(D)), D, nvec, 'sm',opts);\n\n[junk, sortidx] = sort(diag(EVal), 'descend');\nEV = EV(:,sortidx(end-1:-1:1));\nv = diag(EVal);\nEVal = v(sortidx(end-1:-1:1));\n\nEV = bsxfun(@rdivide, EV, sqrt(sum(EV.^2,1))); % makes the eigenvectors unit norm\n", "meta": {"author": "jponttuset", "repo": "mcg", "sha": "e72031d793abf8921e39a8ef3c20de2198c8b26f", "save_path": "github-repos/MATLAB/jponttuset-mcg", "path": "github-repos/MATLAB/jponttuset-mcg/mcg-e72031d793abf8921e39a8ef3c20de2198c8b26f/dncuts/ncuts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6867681621625067}} {"text": "function f = fx3 ( n, x )\n\n%*****************************************************************************80\n%\n%% FX3 is the third 1D example.\n%\n% Discussion:\n%\n% The function should be plotted over [-1.0,+1.0].\n%\n% Internally, this range is mapped to [-3.0,+3.0].\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Rick Archibald, Anne Gelb, Jungho Yoon,\n% Polynomial fitting for edge detection in irregularly sampled signals \n% and images,\n% SIAM Journal on Numerical Analysis,\n% Volume 43, Number 1, 2006, pages 259-279.\n%\n% Parameters:\n%\n% Input, integer N, the number of points.\n%\n% Input, real X(N), the arguments.\n%\n% Output, real F(N,1), the function values.\n%\n\n%\n% Destroy all row vectors!\n%\n x = x ( : );\n%\n% Map from the convenient range [-1,+1] to the physical range [-3,+3].\n%\n x = ( ( 1.0 - x ) * ( -3.0 ) ...\n + ( 1.0 + x ) * ( +3.0 ) ) ...\n / 2.0;\n\n f = zeros ( n, 1 );\n\n i = find ( -2.0 <= x & x <= -1.0 );\n f(i) = 1.0;\n\n j = find ( -0.5 <= x & x <= 0.5 );\n f(j) = 0.5 + 4.0 * ( x(j) + 0.5 ).^2;\n\n k = find ( 1.25 <= x & 3.0 * x <= 7.0 );\n f(k) = 3.0 * ( 2.0 - x(k) );\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/edge/fx3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332893, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.6867590314944726}} {"text": "function vectorSez = rotVectToSEZCoords(rVectorECEF, vectorECEF)\n numVectors = size(rVectorECEF,2);\n \n kHat = repmat([0;0;1], 1, numVectors);\n zHat = vect_normVector(rVectorECEF);\n eHat = vect_normVector(cross(kHat, zHat));\n sHat = vect_normVector(cross(eHat, zHat));\n \n rotMat = [reshape(sHat, [1, 3, numVectors]); \n reshape(eHat, [1, 3, numVectors]); \n reshape(zHat, [1, 3, numVectors])];\n \n vectorECEF = reshape(vectorECEF, [3, 1, numVectors]);\n vectorSez = pagemtimes(rotMat, vectorECEF);\n vectorSez = squeeze(vectorSez);\nend\n% kHat = [0;0;1];\n% zHat = normVector(rVectorECEF);\n% eHat = normVector(cross(kHat, zHat));\n% sHat = normVector(cross(eHat, zHat));\n% \n% rotMat = [sHat'; eHat'; zHat'];\n% \n% vectorSez = rotMat * vectorECEF;\n\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/astrodynamics/fixed_frame/rotVectToSEZCoords.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6866561358208325}} {"text": "function [dop_buf] = rayleigh_dop(in_val)\n% Function to generate Doppler-filtered Rayleigh fading simulator\n\n% Doppler parameters\nvo = (1.2*1000/3600); % vo = 1.2 km/h -> 0.333 m/s\nlambda = 3e8 / 5.4e9; % lambda = c / fc;\nfd = vo/lambda; % Doppler Spread (around 6 Hz)\n\n% Generate Doppler Sf (256 points)\nf_rng = 10*fd;\nf = -f_rng/2 : f_rng/255 : f_rng/2;\ndop_Sf = 1./(1+9*(f/fd).^2);\n\n% Generate 256 samples of Doppler-filtered, Rayleigh fading sim. \ndop_buf1(129:256) = randn(1,128)+j*randn(1,128);\ndop_buf1( 1:128) = conj(dop_buf1(256:-1:129));\ndop_buf2(129:256) = randn(1,128)+j*randn(1,128);\ndop_buf2( 1:128) = conj(dop_buf2(256:-1:129));\ndop_buf1 = ifft(dop_buf1 .* dop_Sf);\ndop_buf2 = ifft(dop_buf2 .* dop_Sf);\ndop_buf = sqrt(dop_buf1.^2 + dop_buf2.^2);\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/26232-ieee-802-11n-wlan-file-update/w11n_jointprop/wlan/tgn_bak/tgn_testing/rayleigh_dop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620619801095, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.6866367977364263}} {"text": "%% with mandrill\nx = mandrill;\n\nwavelet = wavelet_factory_2d(size(x));\nSx = scat(x, wavelet);\nsx = format_scat(Sx);\n\n%% with 32,32 \nx = rand(32,32);\n\nfilt_opt.J = 3;\nfilt_opt.L = 6;\nscat_opt.oversampling = 2;\n[wavelet, filters] = wavelet_factory_2d(size(x), filt_opt, scat_opt);\n\nSx = scat(x, wavelet);\n[s , meta] = format_scat(Sx);\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/test/core/test_format_scat_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625126757596, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6866351890229422}} {"text": "function coef=ref_dgtns_1(f,gamma,V)\n%REF_DGT_1 Reference DGTNS using P.Prinz algorithm\n% Usage: c=ref_dgtns_1(f,gamma,V);\n%\n\na=V(1,1);\nb=V(2,2);\nr=-V(2,1);\nL=size(gamma,1);\nM=L/b;\nN=L/a;\nW=size(f,2);\n\nc=gcd(a,M);\np=a/c;\nq=M/c;\nd=N/q;\n\nif r==0\n % The grid is rectangular. Call another reference algorithm.\n coef=zeros(M*N,W);\n coef(:)=ref_dgt(f,gamma,a,M);\n\n return;\nend;\n\n% We can now assume that the grid is truly nonseperable,\n% and so d>1.\n\n% Conjugate.\ngammac=conj(gamma);\n\n% Level 2: Block diagonalize, and use that some blocks are\n% the same up to permutations.\n\np1=stridep(M,L);\np2=stridep(N,M*N);\n\n% Get shift offsets for stage 2 of the algorithm.\n[mll,all]=shiftoffsets(a,M);\n \n% Step 1: Permute\ns1 = f(p1,:);\n\n% Step 2: Multiply by DG'\ns2=zeros(M*N,W);\n\n% Do interpreter-language-optimized indexing.\n[n_big,m_big]=meshgrid(0:N-1,0:b-1);\nbase=m_big*M-n_big*a+L;\nbase=base.';\n\n% Work arrays.\nwork=zeros(b,M/c*W);\nwk=zeros(N,b);\nwkrect=zeros(N,b);\n\n% Create fixed modulation matrix (Does not change with k)\nfixedmod=zeros(N,b);\nfor n=0:N-1\n fixedmod(n+1,:)=exp(2*pi*i*r*n/L*(0:M:L-1));\nend;\n \n% This loop iterates over the number of truly different wk's.\nfor ko=0:c-1\n \n % Create the wk of the rectangular-grid case.\n wkrect(:)=gammac(mod(base+ko,L)+1);\n \n % Create wk of skewed case.\n wk=(fixedmod.*wkrect);\n\n \n % Setup work array.\n for l=0:M/c-1 \n k=ko+l*c;\n rowmod=exp(2*pi*i*r*(0:b-1)/b*all(l+1)).';\n\n work(:,l*W+1:(l+1)*W)=circshift(rowmod.*s1(1+(ko+l*c)*b:(ko+l*c+1)*b,:),-mll(l+1));\n end;\n\n % Do the actual multiplication,\n work2=wk*work;\n\n % Place the result correctly.\n for l=0:M/c-1\n k=ko+l*c;\n kmod=exp(2*pi*i*r*(0:N-1)*k/L).';\n colmod=exp(2*pi*i*r*(0:N-1)/b*mll(l+1)).';\n doublefac=exp(-2*pi*i*r/b*all(l+1)*mll(l+1)); \n\n\n s2(1+(ko+l*c)*N:(ko+l*c+1)*N,:)=doublefac*colmod.*kmod.*circshift(work2(:,l*W+1:(l+1)*W),all(l+1));\n end;\n\nend; \n\n% Step 3: Permute again.\ncoef = s2(p2,:);\n\n% Apply fft.\nfor n=1:N\n coef((n-1)*M+1:n*M,:)=fft(coef((n-1)*M+1:n*M,:));\nend;\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/reference/ref_dgtns_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7577943822145997, "lm_q1q2_score": 0.6865540000772421}} {"text": "function [beta_median beta_std beta_lbound beta_ubound sigma_median sigma_t_median sigma_t_lbound sigma_t_ubound gamma_median]=stvol2estimates(beta_gibbs,sigma_gibbs,sigma_t_gibbs,gamma_gibbs,n,T,cband)\n\n\n\n\n\n\n% compute the median, variance, and credibility intervals for the posterior distribution of beta\nbeta_median=quantile(beta_gibbs,0.5,2);\nbeta_std=std(beta_gibbs,0,2);\nbeta_lbound=quantile(beta_gibbs,(1-cband)/2,2);\nbeta_ubound=quantile(beta_gibbs,1-(1-cband)/2,2);\n\n\n% compute the results for sigma (long-run value)\nsigma_median=reshape(quantile(sigma_gibbs,0.5,2),n,n);\n\n\n% compute the rsults for sigma (sample values)\nsigma_t_median=cell(n,n);\nsigma_t_lbound=cell(n,n);\nsigma_t_ubound=cell(n,n);\n% loop over periods and entries\nfor ii=1:T\n for jj=1:n\n for kk=1:jj\n sigma_t_median{jj,kk}(ii,1)=quantile(sigma_t_gibbs{ii,1}(jj,kk,:),0.5,3);\n sigma_t_lbound{jj,kk}(ii,1)=quantile(sigma_t_gibbs{ii,1}(jj,kk,:),(1-cband)/2,3);\n sigma_t_ubound{jj,kk}(ii,1)=quantile(sigma_t_gibbs{ii,1}(jj,kk,:),1-(1-cband)/2,3);\n end\n end\nend\n\n\n% compute the estimates for gamma\ngamma_median=quantile(gamma_gibbs,0.5,1);\n \n\n\n\n\n\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/stvol2estimates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6865539852100045}} {"text": "function [rows, cols, vals] = rcvize_matrix(M, i, j)\n%function [rows, cols, vals] = rcvize_matrix(M, i, j)\n%\n% Given a DxD matrix M that we wish to insert into the (i,j)th DxD\n% block of a sparse matrix, this function computes and returns the\n% corresponding {row, col, val} vectors describing this block\n\n% Copyright (C) 2016 by David M. Rosen\n\nD = size(M, 1);\n\nvals = reshape(M, [1, D^2]); %Vectorize M by concatenating its columns\n\nrows = repmat( [D*(i-1) + 1 : D*(i-1) + D], [1,D]);\ncols = kron( [D*(j-1) + 1 : D*(j-1) + D], ones(1, D));\n\n\nend\n\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/lib/rcvize_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.6865450690524738}} {"text": "function fem2d_bvp_linear_test01 ( )\n\n%*****************************************************************************80\n%\n%% FEM2D_BVP_LINEAR_TEST01 carries out test case #1.\n%\n% Discussion:\n%\n% Use A1, C1, F1, EXACT1, EXACT_UX1, EXACT_UY1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n nx = 3;\n ny = 3;\n\n% nx = 5;\n% ny = 5;\n\n% nx = 9;\n% ny = 9;\n\n% nx = 17;\n% ny = 17;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM2D_BVP_LINEAR_TEST01\\n' );\n fprintf ( 1, ' Solve - del ( A del U ) + C U = F \\n' );\n fprintf ( 1, ' on the unit square with zero boundary conditions.\\n' );\n fprintf ( 1, ' A1(X,Y) = 1.0\\n' );\n fprintf ( 1, ' C1(X,Y) = 0.0\\n' );\n fprintf ( 1, ' F1(X,Y) = 2*X*(1-X)+2*Y*(1-Y).\\n' );\n fprintf ( 1, ' U1(X,Y) = X * ( 1 - X ) * Y * ( 1 - Y )\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The grid uses %d by %d nodes.\\n', nx, ny );\n%\n% Geometry definitions.\n%\n x = linspace ( 0.0, 1.0, nx );\n y = linspace ( 0.0, 1.0, ny );\n\n u = fem2d_bvp_linear ( nx, ny, @a1, @c1, @f1, x, y );\n\n if ( 0 )\n [ X, Y ] = meshgrid ( x, y );\n surf ( X, Y, u )\n end\n\n if ( nx * ny <= 25 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I J X Y U Uexact Error\\n' );\n fprintf ( 1, '\\n' );\n\n for j = 1 : ny\n for i = 1 : nx\n uexact = exact1 ( x(i), y(j) );\n fprintf ( 1, ' %4d %4d %8f %8f %8f %8f %8e\\n', ...\n i, j, x(i), y(j), u(i,j), uexact, abs ( u(i,j) - uexact ) );\n end\n end\n\n end\n\n e1 = fem2d_l1_error ( nx, ny, x, y, u, @exact1 );\n e2 = fem2d_l2_error_linear ( nx, ny, x, y, u, @exact1 );\n h1s = fem2d_h1s_error_linear ( nx, ny, x, y, u, @exact_ux1, @exact_uy1 );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' l1 error = %g\\n', e1 );\n fprintf ( 1, ' L2 error = %g\\n', e2 );\n fprintf ( 1, ' H1S error = %g\\n', h1s );\n\n return\nend\nfunction value = a1 ( x, y )\n\n%*****************************************************************************80\n%\n%% A1 evaluates A function #1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, Y, the evaluation point.\n%\n% Output, real VALUE, the value of A(X).\n%\n value = 1.0;\n\n return\nend\nfunction value = c1 ( x, y )\n\n%*****************************************************************************80\n%\n%% C1 evaluates C function #1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, Y, the evaluation point.\n%\n% Output, real VALUE, the value of C(X).\n%\n value = 0.0;\n\n return\nend\nfunction value = exact1 ( x, y )\n\n%*****************************************************************************80\n%\n%% EXACT1 evaluates exact solution #1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, Y, the evaluation point.\n%\n% Output, real VALUE, the value of the solution.\n%\n value = x .* ( 1.0 - x ) .* y .* ( 1.0 - y );\n\n return\nend\nfunction value = exact_ux1 ( x, y )\n\n%*****************************************************************************80\n%\n%% EXACT_UX1 evaluates the derivative dUdX of exact solution #1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, Y, the evaluation point.\n%\n% Output, real VALUE, the value of dUdX.\n%\n value = ( 1.0 - 2.0 * x ) .* ( y - y .* y );\n\n return\nend\nfunction value = exact_uy1 ( x, y )\n\n%*****************************************************************************80\n%\n%% EXACT_UY1 evaluates the derivative dUdY of exact solution #1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, Y, the evaluation point.\n%\n% Output, real VALUE, the value of dUdX.\n%\n value = ( x - x .* x ) .* ( 1.0 - 2.0 * y );\n\n return\nend\nfunction value = f1 ( x, y )\n\n%*****************************************************************************80\n%\n%% F1 evaluates right hand side function #1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, Y, the evaluation point.\n%\n% Output, real VALUE, the value of the right hand side.\n%\n value = 2.0 * x .* ( 1.0 - x ) ...\n + 2.0 * y .* ( 1.0 - y );\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/fem2d_bvp_linear/fem2d_bvp_linear_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8175744717487329, "lm_q1q2_score": 0.6865450615873887}} {"text": "function [ t, w ] = t_quadrature_rule ( n )\n\n%*****************************************************************************80\n%\n%% T_QUADRATURE_RULE: quadrature rule for T(n,x).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 March 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the rule.\n%\n% Output, real T(N,1), W(N,1), the points and weights of the rule.\n%\n aj = zeros ( n, 1 );\n\n bj = 0.5 * ones ( n, 1 );\n bj(1) = sqrt ( 0.5 );\n\n w = zeros ( n, 1 );\n w(1,1) = sqrt ( pi );\n\n [ t, w ] = imtqlx ( n, aj, bj, w );\n\n w(1:n,1) = w(1:n,1).^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/chebyshev_polynomial/t_quadrature_rule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.6865450512438735}} {"text": "function [x_g,w_g,phi,p_x,p_y,p_z] = threed_shapeiso(x_local,r,s,t,w)\n%-----------------------------------------------------------------------\n% threed_shapeiso.m - computes test functions and derivatives on an\n% element given element coordinates and Gauss points.\n% Isoparametric coordinates are used (curved elements)\n%\n% Copyright (c) 2002, Jeff Borggaard, Virginia Tech\n% Version: 1.0a\n%\n% Usage: [x_g,w_g,phi,p_x,p_y,p_z] = threed_shapeiso(x_local,r,s,t,w)\n%\n% Variables: x_local\n% Coordinates of the element nodes\n% (r,s,t)\n% Coordinates of Gauss points in unit tetrahedron\n% w\n% Gauss weights associated with (r,s,t)\n%\n% x_g\n% Coordinates of Gauss points in the element\n% w_g\n% Gauss weights scaled by the element Jacobian\n% phi\n% Value of element shape functions at x_g\n% p_x\n% p_y\n% p_z\n% First spatial derivatives of phi\n% p_xx, etc.\n% Second spatial derivatives of phi\n% (only applicable with 2nd order or higher)\n% (currently not implemented)\n%-----------------------------------------------------------------------\n x = x_local;\n [n,t1] = size(x); % t1 had better be 3\n rule = length(r);\n\n if (n == 10)\n % The following assumes isoparametric elements\n c0 = x( 1,:); % 1\n c1 =-3*x( 1,:) - x( 2,:) + 4*x( 5,:) ; % r\n c2 =-3*x( 1,:) - x( 3,:) + 4*x( 7,:) ; % s\n c3 =-3*x( 1,:) - x( 4,:) + 4*x(10,:) ; % t\n c4 = 2*x( 1,:) + 2*x( 2,:) - 4*x( 5,:) ; % r^2\n c5 = 2*x( 1,:) + 2*x( 3,:) - 4*x( 7,:) ; % s^2\n c6 = 2*x( 1,:) + 2*x( 4,:) - 4*x(10,:) ; % t^2\n c7 = 4*x( 1,:) - 4*x( 5,:) + 4*x( 6,:) - 4*x( 7,:); % rs\n c8 = 4*x( 1,:) - 4*x( 5,:) + 4*x( 8,:) - 4*x(10,:); % rt\n c9 = 4*x( 1,:) - 4*x( 7,:) + 4*x( 9,:) - 4*x(10,:); % st\n\n x_g(:,1) = c0(1) + c1(1)*r + c2(1)*s + c3(1)*t + c4(1)*r.^2 ...\n + c5(1)*s.^2 + c6(1)*t.^2 + c7(1)*r.*s + c8(1)*r.*t ...\n + c9(1)*s.*t; \n xr = c1(1) + 2*c4(1)*r + c7(1)*s + c8(1)*t;\n xs = c2(1) + 2*c5(1)*s + c7(1)*r + c9(1)*t;\n xt = c3(1) + 2*c6(1)*t + c8(1)*r + c9(1)*s;\n\n x_g(:,2) = c0(2) + c1(2)*r + c2(2)*s + c3(2)*t + c4(2)*r.^2 ...\n + c5(2)*s.^2 + c6(2)*t.^2 + c7(2)*r.*s + c8(2)*r.*t ...\n + c9(2)*s.*t; \n yr = c1(2) + 2*c4(2)*r + c7(2)*s + c8(2)*t;\n ys = c2(2) + 2*c5(2)*s + c7(2)*r + c9(2)*t;\n yt = c3(2) + 2*c6(2)*t + c8(2)*r + c9(2)*s;\n\n x_g(:,3) = c0(3) + c1(3)*r + c2(3)*s + c3(3)*t + c4(3)*r.^2 ...\n + c5(3)*s.^2 + c6(3)*t.^2 + c7(3)*r.*s + c8(3)*r.*t ...\n + c9(3)*s.*t; \n zr = c1(3) + 2*c4(3)*r + c7(3)*s + c8(3)*t;\n zs = c2(3) + 2*c5(3)*s + c7(3)*r + c9(3)*t;\n zt = c3(3) + 2*c6(3)*t + c8(3)*r + c9(3)*s;\n\n % Compute the Jacobian of the (r,s,t) -> (x,y,z) transformation\n jac = ( xr.*ys.*zt + xs.*yt.*zr + xt.*yr.*zs ...\n -xr.*yt.*zs - xs.*yr.*zt - xt.*ys.*zr );\n\n w_g = jac.*w;\n\n % Invert derivatives of the mapping\n rx = ( ys.*zt-yt.*zs )./jac;\n ry = ( xt.*zs-xs.*zt )./jac;\n rz = ( xs.*yt-xt.*ys )./jac;\n\n sx = ( yt.*zr-yr.*zt )./jac;\n sy = ( xr.*zt-xt.*zr )./jac;\n sz = ( xt.*yr-xr.*yt )./jac;\n\n tx = ( yr.*zs-ys.*zr )./jac;\n ty = ( xs.*zr-xr.*zs )./jac;\n tz = ( xr.*ys-xs.*yr )./jac;\n\n % Compute shape function and derivatives at Gauss points\n u = 1 - r - s - t ;\n ux = - rx - sx - tx;\n uy = - ry - sy - ty;\n uz = - rz - sz - tz;\n \n phi = zeros(rule,n);\n phi(:,1) = u - 2*r.*u - 2*s.*u - 2*t.*u;\n phi(:,2) = r - 2*r.*u - 2*r.*s - 2*r.*t;\n phi(:,3) = s - 2*r.*s - 2*s.*u - 2*s.*t;\n phi(:,4) = t - 2*r.*t - 2*s.*t - 2*t.*u;\n phi(:,5) = 4*r.*u;\n phi(:,6) = 4*r.*s;\n phi(:,7) = 4*s.*u;\n phi(:,8) = 4*r.*t;\n phi(:,9) = 4*s.*t;\n phi(:,10) = 4*t.*u;\n \n p_x = zeros(rule,n);\n p_x(:,1) = ux - 2*rx.*u - 2*r.*ux - 2*sx.*u ...\n - 2*s.*ux - 2*tx.*u - 2*t.*ux ;\n p_x(:,2) = rx - 2*rx.*u - 2*r.*ux - 2*rx.*s ...\n - 2*r.*sx - 2*rx.*t - 2*r.*tx ;\n p_x(:,3) = sx - 2*rx.*s - 2*r.*sx - 2*sx.*u ...\n - 2*s.*ux - 2*sx.*t - 2*s.*tx ;\n p_x(:,4) = tx - 2*rx.*t - 2*r.*tx - 2*sx.*t ...\n - 2*s.*tx - 2*tx.*u - 2*t.*ux ;\n p_x(:,5) = 4*rx.*u + 4*r.*ux;\n p_x(:,6) = 4*rx.*s + 4*r.*sx;\n p_x(:,7) = 4*sx.*u + 4*s.*ux;\n p_x(:,8) = 4*rx.*t + 4*r.*tx;\n p_x(:,9) = 4*sx.*t + 4*s.*tx;\n p_x(:,10) = 4*tx.*u + 4*t.*ux;\n \n p_y = zeros(rule,n);\n p_y(:,1) = uy - 2*ry.*u - 2*r.*uy - 2*sy.*u ...\n - 2*s.*uy - 2*ty.*u - 2*t.*uy ;\n p_y(:,2) = ry - 2*ry.*u - 2*r.*uy - 2*ry.*s ...\n - 2*r.*sy - 2*ry.*t - 2*r.*ty ;\n p_y(:,3) = sy - 2*ry.*s - 2*r.*sy - 2*sy.*u ...\n - 2*s.*uy - 2*sy.*t - 2*s.*ty ;\n p_y(:,4) = ty - 2*ry.*t - 2*r.*ty - 2*sy.*t ...\n - 2*s.*ty - 2*ty.*u - 2*t.*uy ;\n p_y(:,5) = 4*ry.*u + 4*r.*uy;\n p_y(:,6) = 4*ry.*s + 4*r.*sy;\n p_y(:,7) = 4*sy.*u + 4*s.*uy;\n p_y(:,8) = 4*ry.*t + 4*r.*ty;\n p_y(:,9) = 4*sy.*t + 4*s.*ty;\n p_y(:,10) = 4*ty.*u + 4*t.*uy;\n \n p_z = zeros(rule,n);\n p_z(:,1) = uz - 2*rz.*u - 2*r.*uz - 2*sz.*u ...\n - 2*s.*uz - 2*tz.*u - 2*t.*uz ;\n p_z(:,2) = rz - 2*rz.*u - 2*r.*uz - 2*rz.*s ...\n - 2*r.*sz - 2*rz.*t - 2*r.*tz ;\n p_z(:,3) = sz - 2*rz.*s - 2*r.*sz - 2*sz.*u ...\n - 2*s.*uz - 2*sz.*t - 2*s.*tz ;\n p_z(:,4) = tz - 2*rz.*t - 2*r.*tz - 2*sz.*t ...\n - 2*s.*tz - 2*tz.*u - 2*t.*uz ;\n p_z(:,5) = 4*rz.*u + 4*r.*uz;\n p_z(:,6) = 4*rz.*s + 4*r.*sz;\n p_z(:,7) = 4*sz.*u + 4*s.*uz;\n p_z(:,8) = 4*rz.*t + 4*r.*tz;\n p_z(:,9) = 4*sz.*t + 4*s.*tz;\n p_z(:,10) = 4*tz.*u + 4*t.*uz;\n\n else\n error('Only quadratic isoparametric elements are supported\\n')\n end\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/threed/threed_shapeiso.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248208414329, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.686482150822633}} {"text": "function imageData = whitebalance(imageData)\n% WHITEBALANCE forces the average image color to be gray.\n% Copyright 2013 The MathWorks, Inc. \n\n% Find the average values for each channel.\navg_rgb = mean(mean(imageData));\n \n% Find the average gray value and compute the scaling \n% factor.\nfactors = max(mean(avg_rgb), 128)./avg_rgb;\n\n% Adjust the image to the new gray value.\nimageData(:,:,1) = uint8(imageData(:,:,1)*factors(1));\nimageData(:,:,2) = uint8(imageData(:,:,2)*factors(2));\nimageData(:,:,3) = uint8(imageData(:,:,3)*factors(3));\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/38401-matlab-for-cuda-programmers/01_apply_scaling_factors/whitebalance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6864645771377731}} {"text": "function [m,v,w,g,f,pp,gg]=v_gaussmix(x,c,l,m0,v0,w0,wx)\n%V_GAUSSMIX fits a gaussian mixture pdf to a set of data observations [m,v,w,g,f]=(x,c,l,m0,v0,w0,wx)\n%\n% Usage:\n% (1) [m,v,w]=v_gaussmix(x,[],[],k); % create GMM with k mixtures and diagonal covariances\n% (2) [m,v,w]=gaussmix(x,[],[],k,'v'); % create GMM with k mixtures and full covariances\n%\n% Inputs: n data values, k mixtures, p parameters, l loops\n%\n% X(n,p) Input data vectors, one per row.\n% C(1) Minimum variance of normalized data (Use [] to take default value of 1/n^2)\n% L The integer portion of l gives a maximum loop count. The fractional portion gives\n% an optional stopping threshold. Iteration will cease if the increase in\n% log likelihood density per data point is less than this value. Thus l=10.001 will\n% stop after 10 iterations or when the increase in log likelihood falls below\n% 0.001.\n% As a special case, if L=0, then the first three outputs are omitted.\n% Use [] to take default value of 100.0001\n% M0 Number of mixtures required (or initial mixture means - see below)\n% V0 Initialization mode:\n% 'f' Initialize with K randomly selected data points [default]\n% 'p' Initialize with centroids and variances of random partitions\n% 'k' k-means algorithm ('kf' and 'kp' determine initialization)\n% 'h' k-harmonic means algorithm ('hf' and 'hp' determine initialization) [default]\n% 's' use unscaled data during initialization phase instead of scaling it first\n% 'm' M0 contains the initial centres\n% 'v' full covariance matrices\n% Mode 'hf' [the default] generally gives the best results but 'f' is faster and often OK\n% W0(n,1) Data point weights\n%\n% Alternatively, initial values for M0, V0 and W0 can be given explicitly:\n%\n% M0(k,p) Initial mixture means, one row per mixture.\n% V0(k,p) Initial mixture variances, one row per mixture.\n% or V0(p,p,k) one full-covariance matrix per mixture\n% W0(k,1) Initial mixture weights, one per mixture. The weights should sum to unity.\n% WX(n,1) Data point weights\n%\n% Outputs: (Note that M, V and W are omitted if L==0)\n%\n% M(k,p) Mixture means, one row per mixture. (omitted if L==0)\n% V(k,p) Mixture variances, one row per mixture. (omitted if L==0)\n% or V(p,p,k) if full covariance matrices in use (i.e. either 'v' option or V0(p,p,k) specified)\n% W(k,1) Mixture weights, one per mixture. The weights will sum to unity. (omitted if L==0)\n% G Average log probability of the input data points.\n% F Fisher's Discriminant measures how well the data divides into classes.\n% It is the ratio of the between-mixture variance to the average mixture variance: a\n% high value means the classes (mixtures) are well separated.\n% PP(n,1) Log probability of each data point\n% GG(l+1,1) Average log probabilities at the beginning of each iteration and at the end\n%\n% The fitting procedure uses one of several initialization methods to create an initial guess\n% for the mixture centres and then uses the EM (expectation-maximization) algorithm to refine\n% the guess. Although the EM algorithm is deterministic, the initialization procedures use\n% random numbers and so the routine will not give identical answers if you call it multiple\n% times with the same input data. See v_randvec() for generating GMM data vectors.\n\n% Bugs/Suggestions\n% (1) Allow processing in chunks by outputting/reinputting an array of sufficient statistics\n% (2) Other initialization options:\n% 'l' LBG algorithm\n% 'm' Move-means (dog-rabbit) algorithm\n% (3) Allow updating of weights-only, not means/variances\n% (4) Allow freezing of means and/or variances\n\n% Copyright (C) Mike Brookes 2000-2009\n% Version: $Id: v_gaussmix.m 10865 2018-09-21 17:22:45Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\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 can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n[n,p]=size(x); % n = number of training values, p = dimension of data vector\nwn=ones(n,1);\nmemsize=v_voicebox('memsize'); % set memory size to use\nif isempty(c)\n c=1/n^2;\nelse\n c=c(1); % just to prevent legacy code failing\nend\nfulliv=0; % initial variance is not full\nif isempty(l)\n l=100+1e-4; % max loop count + stopping threshold\nend\nif nargin<5 || isempty(v0) || ischar(v0) % no initial values specified for m0, v0, w0\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % No initialvalues given, so we must use k-means or equivalent\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if nargin<6\n if nargin<5 || isempty(v0)\n v0='hf'; % default initialization mode: hf\n end\n wx=wn; % no data point weights\n else\n wx=w0(:); % data point weights\n end\n wx=wx/sum(wx);\n if any(v0=='m')\n k=size(m0,1);\n else\n k=m0;\n end\n fv=any(v0=='v'); % full covariance matrices requested\n mx0=wx'*x; % calculate mean of input data in each dimension\n vx0=wx'*x.^2-mx0.^2; % calculate variance of input data in each dimension\n sx0=sqrt(vx0);\n sx0(sx0==0)=1; % do not divide by zero when scaling\n if n<=k % each data point can have its own mixture\n xs=(x-mx0(wn,:))./sx0(wn,:); % scale the data\n m=xs(mod((1:k)-1,n)+1,:); % just include all points several times\n v=zeros(k,p); % will be set to floor later\n w=zeros(k,1);\n w(1:n)=1/n;\n if l>0\n l=0.1; % no point in iterating\n end\n else % more points than mixtures\n if any(v0=='s')\n xs=x; % do not scale data during initialization\n else\n xs=(x-mx0(wn,:))./sx0(wn,:); % else scale now\n if any(v0=='m')\n m=(m0-mx0(ones(k,1),:))./sx0(ones(k,1),:); % scale specified means as well\n end\n end\n w=repmat(1/k,k,1); % all mixtures equally likely\n if any(v0=='k') % k-means initialization\n if any(v0=='m')\n [m,e,j]=v_kmeans(xs,k,m);\n elseif any(v0=='p')\n [m,e,j]=v_kmeans(xs,k,'p');\n else\n [m,e,j]=v_kmeans(xs,k,'f');\n end\n elseif any(v0=='h') % k-harmonic means initialization\n if any(v0=='m')\n [m,e,j]=v_kmeanhar(xs,k,[],4,m);\n else\n if any(v0=='p')\n [m,e,j]=v_kmeanhar(xs,k,[],4,'p');\n else\n [m,e,j]=v_kmeanhar(xs,k,[],4,'f');\n end\n end\n elseif any(v0=='p') % Initialize using a random partition\n j=ceil(rand(n,1)*k); % allocate to random clusters\n j(v_rnsubset(k,n))=1:k; % but force at least one point per cluster\n for i=1:k\n m(i,:)=mean(xs(j==i,:),1);\n end\n else\n if any(v0=='m')\n m=m0; % use specified centres\n else\n m=xs(v_rnsubset(k,n),:); % Forgy initialization: sample k centres without replacement [default]\n end\n [e,j]=v_kmeans(xs,k,m,0); % find out the cluster allocation\n end\n if any(v0=='s')\n xs=(x-mx0(wn,:))./sx0(wn,:); % scale data now if not done previously\n end\n v=zeros(k,p); % diagonal covariances\n w=zeros(k,1);\n for i=1:k\n ni=sum(j==i); % number assigned to this centre\n w(i)=(ni+1)/(n+k); % weight of this mixture\n if ni\n v(i,:)=sum((xs(j==i,:)-repmat(m(i,:),ni,1)).^2,1)/ni;\n else\n v(i,:)=zeros(1,p);\n end\n end\n end\nelse\n %%%%%%%%%%%%%%%%%%%%%%%%\n % use initial values given as input parameters\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if nargin<7\n wx=wn; % no data point weights\n end\n wx=wx(:)/sum(wx); % normalize weights and force a column vector \n mx0=wx'*x; % calculate mean of input data in each dimension\n vx0=wx'*x.^2-mx0.^2; % calculate variance of input data in each dimension\n sx0=sqrt(vx0);\n sx0(sx0==0)=1; % do not divide by zero when scaling\n [k,p]=size(m0);\n xs=(x-mx0(wn,:))./sx0(wn,:); % scale the data\n m=(m0-mx0(ones(k,1),:))./sx0(ones(k,1),:); % and the means\n v=v0;\n w=w0;\n fv=ndims(v)>2 || size(v,1)>k; % full covariance matrix is supplied\n if fv\n mk=eye(p)==0; % off-diagonal elements\n fulliv=any(v(repmat(mk,[1 1 k]))~=0); % check if any are non-zero\n if ~fulliv\n v=reshape(v(repmat(~mk,[1 1 k])),p,k)'./repmat(sx0.^2,k,1); % just pick out and scale the diagonal elements for now\n else\n v=v./repmat(sx0'*sx0,[1 1 k]); % scale the full covariance matrix\n end\n end\nend\nif length(wx)~=n\n error('%d datapoints but %d weights',n,length(wx));\nend\nlsx=sum(log(sx0));\nxsw=xs.*repmat(wx,1,p); % weighted data points\nif ~fulliv % initializing with diagonal covariance\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Diagonal Covariance matrices %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n v=max(v,c); % apply the lower bound\n xs2=xs.^2.*repmat(wx,1,p); % square and weight the data for variance calculations\n \n % If data size is large then do calculations in chunks\n \n nb=min(n,max(1,floor(memsize/(8*p*k)))); % chunk size for testing data points\n nl=ceil(n/nb); % number of chunks\n jx0=n-(nl-1)*nb; % size of first chunk\n \n im=repmat(1:k,1,nb); im=im(:);\n th=(l-floor(l))*n;\n sd=(nargout > 3*(l~=0)); % = 1 if we are outputting log likelihood values\n lp=floor(l)+sd; % extra loop needed to calculate final G value\n \n lpx=zeros(1,n); % log probability of each data point\n wk=ones(k,1);\n wp=ones(1,p);\n wnb=ones(1,nb);\n wnj=ones(1,jx0);\n \n % EM loop\n \n g=0; % dummy initial value for comparison\n gg=zeros(lp+1,1);\n ss=sd; % initialize stopping count (0 or 1)\n for j=1:lp\n g1=g; % save previous log likelihood (2*pi factor omitted)\n m1=m; % save previous means, variances and weights\n v1=v;\n w1=w;\n vi=-0.5*v.^(-1); % data-independent scale factor in exponent\n lvm=log(w)-0.5*sum(log(v),2); % log of external scale factor (excluding -0.5*p*log(2pi) term)\n \n % first do partial chunk (of length jx0)\n \n jx=jx0;\n ii=1:jx; % indices of data points in this chunk\n kk=repmat(ii,k,1); % kk(jx,k): one row per data point, one column per mixture\n km=repmat(1:k,1,jx); % km(jx,k): one row per data point, one column per mixture\n py=reshape(sum((xs(kk(:),:)-m(km(:),:)).^2.*vi(km(:),:),2),k,jx)+lvm(:,wnj); % py(k,jx) pdf of each point with each mixture\n mx=max(py,[],1); % mx(1,jx) find normalizing factor for each data point to prevent underflow when using exp()\n px=exp(py-mx(wk,:)); % find normalized probability of each mixture for each datapoint\n ps=sum(px,1); % total normalized likelihood of each data point\n px=px./ps(wk,:); % relative mixture probabilities for each data point (columns sum to 1)\n lpx(ii)=log(ps)+mx;\n pk=px*wx(ii); % pk(k,1) effective fraction of data points for each mixture (could be zero due to underflow)\n sx=px*xsw(ii,:);\n sx2=px*xs2(ii,:);\n for il=2:nl % process the data points in chunks\n ix=jx+1;\n jx=jx+nb; % increment upper limit\n ii=ix:jx; % indices of data points in this chunk\n kk=repmat(ii,k,1);\n py=reshape(sum((xs(kk(:),:)-m(im,:)).^2.*vi(im,:),2),k,nb)+lvm(:,wnb);\n mx=max(py,[],1); % find normalizing factor for each data point to prevent underflow when using exp()\n px=exp(py-mx(wk,:)); % find normalized probability of each mixture for each datapoint\n ps=sum(px,1); % total normalized likelihood of each data point\n px=px./ps(wk,:); % relative mixture probabilities for each data point (columns sum to 1)\n lpx(ii)=log(ps)+mx;\n pk=pk+px*wx(ii); % pk(k,1) effective fraction of data points for each mixture (could be zero due to underflow)\n sx=sx+px*xsw(ii,:);\n sx2=sx2+px*xs2(ii,:);\n end\n g=lpx*wx; % total log probability summed over all data points\n gg(j)=g; % save log prob at each iteration\n w=pk; % normalize to get the weights\n if pk % if all elements of pk are non-zero\n m=sx./pk(:,wp); % calculate mixture means\n v=sx2./pk(:,wp); % and variances\n else\n wm=pk==0; % mask indicating mixtures with zero weights\n nz=sum(wm); \t% number of zero-weight mixtures\n [vv,mk]=sort(lpx); % find the lowest probability data points\n m=zeros(k,p); % initialize means and variances to zero (variances are floored later)\n v=m;\n m(wm,:)=xs(mk(1:nz),:); \t% set zero-weight mixture means to worst-fitted data points\n w(wm)=1/n; \t% set these weights non-zero\n w=w*n/(n+nz); \t% normalize so the weights sum to unity\n wm=~wm; \t% mask for non-zero weights\n m(wm,:)=sx(wm,:)./pk(wm,wp); % recalculate means and variances for mixtures with a non-zero weight\n v(wm,:)=sx2(wm,:)./pk(wm,wp);\n end\n v=max(v-m.^2,c); % apply floor to variances\n if g-g1<=th && j>1\n if ~ss, break; end % stop\n ss=ss-1; % stop next time\n end\n end\n if sd && ~fv % we need to calculate the final probabilities\n pp=lpx'-0.5*p*log(2*pi)-lsx; % log of total probability of each data point\n gg=gg(1:j)-0.5*p*log(2*pi)-lsx; % average log prob at each iteration\n g=gg(end);\n m=m1; % back up to previous iteration\n v=v1;\n w=w1;\n mm=sum(m,1)/k;\n f=(m(:)'*m(:)-k*mm(:)'*mm(:))/sum(v(:));\n end\n if ~fv\n m=m.*sx0(ones(k,1),:)+mx0(ones(k,1),:);\t% unscale means\n v=v.*repmat(sx0.^2,k,1); % and variances\n else\n v1=v;\n v=zeros(p,p,k);\n mk=eye(p)==1; % mask for diagonal elements\n v(repmat(mk,[1 1 k]))=v1'; % set from v1\n end\nend\nif fv % check if full covariance matrices were requested\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Full Covariance matrices %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n pl=p*(p+1)/2;\n lix=1:p^2;\n cix=repmat(1:p,p,1);\n rix=cix';\n lix(cix>rix)=[]; % index of lower triangular elements\n cix=cix(lix); % index of lower triangular columns\n rix=rix(lix); % index of lower triangular rows\n dix=find(rix==cix);\n lixi=zeros(p,p);\n lixi(lix)=1:pl;\n lixi=lixi';\n lixi(lix)=1:pl; % reverse index to build full matrices\n v=reshape(v,p^2,k);\n v=v(lix,:)'; % lower triangular in rows\n \n % If data size is large then do calculations in chunks\n \n nb=min(n,max(1,floor(memsize/(24*p*k)))); % chunk size for testing data points\n nl=ceil(n/nb); % number of chunks\n jx0=n-(nl-1)*nb; % size of first chunk\n %\n th=(l-floor(l))*n;\n sd=(nargout > 3*(l~=0)); % = 1 if we are outputting log likelihood values\n lp=floor(l)+sd; % extra loop needed to calculate final G value\n %\n lpx=zeros(1,n); % log probability of each data point\n wk=ones(k,1);\n wp=ones(1,p);\n wpl=ones(1,pl); % 1 index for lower triangular matrix\n wnb=ones(1,nb);\n wnj=ones(1,jx0);\n \n % EM loop\n \n g=0; % dummy initial value for comparison\n gg=zeros(lp+1,1);\n ss=sd; % initialize stopping count (0 or 1)\n vi=zeros(p*k,p); % stack of k inverse cov matrices each size p*p\n vim=zeros(p*k,1); \t% stack of k vectors of the form inv(v)*m\n mtk=vim; \t% stack of k vectors of the form m\n lvm=zeros(k,1);\n wpk=repmat((1:p)',k,1);\n for j=1:lp\n g1=g; \t% save previous log likelihood (2*pi factor omitted)\n m1=m; \t% save previous means, variances and weights\n v1=v;\n w1=w;\n for ik=1:k\n \n % these lines added for debugging only\n % vk=reshape(v(k,lixi),p,p);\n % condk(ik)=cond(vk);\n %%%%%%%%%%%%%%%%%%%%\n [uvk,dvk]=eig(reshape(v(ik,lixi),p,p));\t% convert lower triangular to full and find eigenvalues\n dvk=max(diag(dvk),c); \t% apply variance floor to eigenvalues\n vik=-0.5*uvk*diag(dvk.^(-1))*uvk'; % calculate inverse\n vi((ik-1)*p+(1:p),:)=vik; % vi contains all mixture inverses stacked on top of each other\n vim((ik-1)*p+(1:p))=vik*m(ik,:)'; % vim contains vi*m for all mixtures stacked on top of each other\n mtk((ik-1)*p+(1:p))=m(ik,:)'; % mtk contains all mixture means stacked on top of each other\n lvm(ik)=log(w(ik))-0.5*sum(log(dvk)); % vm contains the weighted sqrt of det(vi) for each mixture\n end\n %\n % % first do partial chunk\n %\n jx=jx0;\n ii=1:jx;\n xii=xs(ii,:).';\n py=reshape(sum(reshape((vi*xii-vim(:,wnj)).*(xii(wpk,:)-mtk(:,wnj)),p,jx*k),1),k,jx)+lvm(:,wnj);\n mx=max(py,[],1); % find normalizing factor for each data point to prevent underflow when using exp()\n px=exp(py-mx(wk,:)); % find normalized probability of each mixture for each datapoint\n ps=sum(px,1); % total normalized likelihood of each data point\n px=px./ps(wk,:); % relative mixture probabilities for each data point (columns sum to 1)\n lpx(ii)=log(ps)+mx;\n pk=px*wx(ii); % effective fraction of data points for each mixture (could be zero due to underflow)\n sx=px*xsw(ii,:);\n sx2=px*(xsw(ii,rix).*xs(ii,cix));\t% accumulator for variance calculation (lower tri cov matrix as a row)\n for il=2:nl\n ix=jx+1;\n jx=jx+nb; % increment upper limit\n ii=ix:jx;\n xii=xs(ii,:).';\n py=reshape(sum(reshape((vi*xii-vim(:,wnb)).*(xii(wpk,:)-mtk(:,wnb)),p,nb*k),1),k,nb)+lvm(:,wnb);\n mx=max(py,[],1); % find normalizing factor for each data point to prevent underflow when using exp()\n px=exp(py-mx(wk,:)); % find normalized probability of each mixture for each datapoint\n ps=sum(px,1); % total normalized likelihood of each data point\n px=px./ps(wk,:); % relative mixture probabilities for each data point (columns sum to 1)\n lpx(ii)=log(ps)+mx;\n pk=pk+px*wx(ii); % effective fraction of data points for each mixture (could be zero due to underflow)\n sx=sx+px*xsw(ii,:); % accumulator for mean calculation\n sx2=sx2+px*(xsw(ii,rix).*xs(ii,cix));\t% accumulator for variance calculation\n end\n g=lpx*wx; % total log probability summed over all data points\n gg(j)=g; % save convergence history\n w=pk; \t% w(k,1) normalize to get the column of weights\n if pk % if all elements of pk are non-zero\n m=sx./pk(:,wp); % find mean and mean square\n v=sx2./pk(:,wpl);\n else\n wm=pk==0; % mask indicating mixtures with zero weights\n nz=sum(wm); % number of zero-weight mixtures\n [vv,mk]=sort(lpx); % find the lowest probability data points\n m=zeros(k,p); % initialize means and variances to zero (variances are floored later)\n v=zeros(k,pl);\n m(wm,:)=xs(mk(1:nz),:); % set zero-weight mixture means to worst-fitted data points\n w(wm)=1/n; % set these weights non-zero\n w=w*n/(n+nz); % normalize so the weights sum to unity\n wm=~wm; % mask for non-zero weights\n m(wm,:)=sx(wm,:)./pk(wm,wp); % recalculate means and variances for mixtures with a non-zero weight\n v(wm,:)=sx2(wm,:)./pk(wm,wpl);\n end\n v=v-m(:,cix).*m(:,rix); % subtract off mean squared\n if g-g1<=th && j>1\n if ~ss, break; end % stop\n ss=ss-1; % stop next time\n end\n end\n if sd % we need to calculate the final probabilities\n pp=lpx'-0.5*p*log(2*pi)-lsx; % log of total probability of each data point\n gg=gg(1:j)-0.5*p*log(2*pi)-lsx; % average log prob at each iteration\n g=gg(end);\n % gg' % *** DEBUG ONLY ***\n m=m1; % back up to previous iteration\n v=zeros(p,p,k); % reserve spave for k full covariance matrices\n trv=0; % sum of variance matrix traces\n for ik=1:k % loop for each mixture to apply variance floor\n [uvk,dvk]=eig(reshape(v1(ik,lixi),p,p));\t% convert lower triangular to full and find eigenvectors\n dvk=max(diag(dvk),c); % apply variance floor to eigenvalues\n v(:,:,ik)=uvk*diag(dvk)*uvk'; % reconstitute full matrix\n trv=trv+sum(dvk); % add trace to the sum\n end\n w=w1;\n mm=sum(m,1)/k;\n f=(m(:)'*m(:)-k*mm(:)'*mm(:))/trv;\n else\n v1=v; % lower triangular form\n v=zeros(p,p,k); % reserve spave for k full covariance matrices\n for ik=1:k % loop for each mixture to apply variance floor\n [uvk,dvk,]=eig(reshape(v1(ik,lixi),p,p));\t% convert lower triangular to full and find eigenvectors\n dvk=max(diag(dvk),c); % apply variance floor\n v(:,:,ik)=uvk*diag(dvk)*uvk'; % reconstitute full matrix\n end\n end\n m=m.*sx0(ones(k,1),:)+mx0(ones(k,1),:); % unscale means\n v=v.*repmat(sx0'*sx0,[1 1 k]);\nend\nif l==0 % suppress the first three output arguments if l==0\n m=g;\n v=f;\n w=pp;\nend\n\n", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_gaussmix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6864203582856013}} {"text": "function F = spm_Tcdf(x,v)\n% Cumulative Distribution Function (CDF) of Students t distribution\n% FORMAT p = spm_Tcdf(x,v)\n%\n% x - T-variate (Student's t has range (-Inf,Inf)\n% v - degrees of freedom (v>0, non-integer d.f. accepted)\n% F - CDF of Student's t-distribution with v degrees of freedom at points x\n%__________________________________________________________________________\n%\n% spm_Tcdf implements the Cumulative Distribution of the Students t-distribution.\n%\n% Definition:\n%--------------------------------------------------------------------------\n% The CDF F(x) of the Student's t-distribution with v degrees of\n% freedom is the probability that a realisation of a t random variable\n% X has value less than x; F(x)=Pr{X0.\n%\n% Variate relationships: (Evans et al., Ch37 & 7)\n%--------------------------------------------------------------------------\n% The Student's t distribution with 1 degree of freedom is the Standard\n% Cauchy distribution, which has a simple closed form CDF.\n%\n% Algorithm:\n%--------------------------------------------------------------------------\n% The CDF of the Student's t-distribution with v degrees of freedom\n% is related to the incomplete beta function by:\n% Pr(|X|0\n%\n% See Abramowitz & Stegun, 26.5.27 & 26.7.1; Press et al., Sec6.4 for\n% definitions of the incomplete beta function. The relationship is\n% easily verified by substituting for v/(v+x^2) in the integral of the\n% incomplete beta function.\n%\n% MATLAB's implementation of the incomplete beta function is used.\n%\n%\n% References:\n%--------------------------------------------------------------------------\n% Evans M, Hastings N, Peacock B (1993)\n% \"Statistical Distributions\"\n% 2nd Ed. Wiley, New York\n%\n% Abramowitz M, Stegun IA, (1964)\n% \"Handbook of Mathematical Functions\"\n% US Government Printing Office\n%\n% Press WH, Teukolsky SA, Vetterling AT, Flannery BP (1992)\n% \"Numerical Recipes in C\"\n% Cambridge\n%\n%__________________________________________________________________________\n% Copyright (C) 1992-2011 Wellcome Trust Centre for Neuroimaging\n\n% Andrew Holmes\n% $Id: spm_Tcdf.m 4182 2011-02-01 12:29:09Z guillaume $\n\n\n%-Format arguments, note & check sizes\n%--------------------------------------------------------------------------\nif nargin<2, error('Insufficient arguments'), end\n\nad = [ndims(x);ndims(v)];\nrd = max(ad);\nas = [[size(x),ones(1,rd-ad(1))];...\n [size(v),ones(1,rd-ad(2))]];\nrs = max(as);\nxa = prod(as,2)>1;\nif all(xa) && any(diff(as(xa,:)))\n error('non-scalar args must match in size');\nend\n\n\n%-Computation\n%--------------------------------------------------------------------------\n%-Initialise result to zeros\nF = zeros(rs);\n\n%-Only defined for strictly positive v. Return NaN if undefined.\nmd = ( ones(size(x)) & v>0 );\nif any(~md(:))\n F(~md) = NaN;\n warning('Returning NaN for out of range arguments');\nend\n\n%-Special case: f is 0.5 when x=0 (where betainc involves log of zero)\nF( md & x==0 ) = 0.5;\n\n%-Special case: Standard Cauchy distribution when v=1\nml = ( md & v==1 ); if xa(1), mlx=ml; else mlx=1; end\nF(ml) = 0.5 + atan(x(mlx))/pi;\n\n%-Compute where defined & not special cases\nQ = find( md & x~=0 & v~=1 );\nif isempty(Q), return, end\nif xa(1), Qx=Q; else Qx=1; end\nif xa(2), Qv=Q; else Qv=1; end\n\n%-Compute\nxQxPos = x(Qx)>0;\nF(Q) = xQxPos -(xQxPos*2-1).*0.5.*betainc(v(Qv)./(v(Qv)+x(Qx).^2),v(Qv)/2,1/2);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_Tcdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6864203523735586}} {"text": "function pass = test_jacobian( ) \n% Test jacobian\n\ntol = 1e2*chebfunpref().cheb2Prefs.chebfun2eps;\n\n% Check jacobian of an empty diskfunv is an empty diskfun.\nu = diskfunv;\nf = jacobian(u);\npass(1) = isempty(f) & isa(f,'diskfun');\n\n% Check definition: \nF = diskfunv(@(x,y) cos(pi*x.*y), @(x,y) sin(pi*y).*cos(pi*x)); \nFx = diffx(F); \nFy = diffy(F); \npass(2) = ( norm(jacobian(F) - (Fx(1).*Fy(2)-Fy(1).*Fx(2)) ) < tol );\n\n%check against true value\ntrue = diskfun(@(x,y)-pi^2*y.*sin(pi*x.*y).*cos(pi*y).*cos(pi.*x)-...\n pi^2*x.*sin(pi*x.*y).*sin(pi*y).*sin(pi*x)); \npass(3) = ( norm(jacobian(F)-true) < 4*tol ) ; \n\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/diskfunv/test_jacobian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6864105319044531}} {"text": "function [dir,x0,y0] = boundarydir(x,y,orderout) \n%BOUNDARYDIR Determine the direction of a sequence of planar points.\n% DIR = BOUNDARYDIR(X,Y) determines the direction of travel of a\n% closed, nonintersecting sequence of planar points with coordinates\n% contained in column vectors X and Y. Values of DIR are 'cw'\n% (clockwise) and 'ccw' (counterclockwise). The direction of travel is\n% with respect to the image coordinate system defined in Chapter 2 of\n% the book.\n%\n% [DIR,X0,Y0] = BOUNDARYDIR(X,Y,ORDEROUT) determines the direction DIR\n% of the input sequence, and also outputs the sequence with its\n% direction of travel as specified in ORDEROUT. Valid values of this\n% parameter as 'cw' and 'ccw'. The coordinates of the output sequence\n% are column vectors X0 and Y0.\n%\n% The input sequence is assumed to be nonintersecting, and it cannot\n% have duplicate points, with the exception of the first and last\n% points possibly being the same, a condition often resulting from\n% boundary-following functions, such as bwboundaries.\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\n% Preliminaries.\n% Make sure coordinates are column vectors.\nx = x(:);\ny = y(:);\n\n% If the first and last points are the same, delete the last point.\n% The point will be restored later.\nrestore = false;\nif x(1) == x(end) && y(1) == y(end)\n x = x(1:end-1);\n y = y(1:end-1);\n restore = true;\nend\n% Check for duplicate points.\nif length([x y]) ~= length(unique([x y],'rows')) \n error('No duplicate points except first and last are allowed.')\nend\n\n% The topmost, leftmost point in the sequence is always a convex\n% vertex.\nx0 = x; \ny0 = y;\ncx = find(x0 == min(x0));\ncy = find(y0 == min(y0(cx)));\nx1 = x0(cx(1));\ny1 = y0(cy(1));\n% Scroll data so that the first point in the sequence is (x1, y1),\n% the guaranteed convex point.\nI = find(x0 == x1 & y0 == y1);\nx0 = circshift(x0, [-(I - 1), 0]);\ny0 = circshift(y0, [-(I - 1), 0]);\n\n% Form the matrix needed to check for travel direction. Only three\n% points are needed: (x1, y1), the point before it, and the point\n% after it.\nA = [x0(end) y0(end) 1; x0(1) y0(1) 1; x0(2) y0(2) 1];\ndir = 'cw';\nif det(A) > 0\n dir = 'ccw';\nend\n\n% Prepare outputs.\nif nargin == 3\n x0 = x; % Reuse x0 and y0.\n y0 = y;\n if ~strcmp(dir,orderout)\n x0(2:end) = flipud(x0(2:end)); % Reverse order of travel.\n y0(2:end) = flipud(y0(2:end));\n end\n if restore\n x0(end + 1) = x0(1);\n y0(end + 1) = y0(1);\n end\nend\n \n\n\n\n\n\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/boundarydir.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893520001, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.686283622861928}} {"text": "function [res, diams] = imOrientedGranulo(img, angleList, granuloType, strelSizes, varargin)\n% Gray level granulometry mean size for various orientations.\n%\n% Compute typical size of bright or dark structures within images by\n% performing gray-level granulometries with horizontal structuring\n% elements and for various rotations of the input image.\n% The function \"imDirectionalGranulo\" is an alternative approach based on\n% line structuring elements with various orientations.\n%\n% Usage\n% RES = imOrientedGranulo(IMG, ANGLES, TYPE, SIZES)\n% IMG should be a 2D image (binary, grayscale or color)\n% ANGLES is the list of angles to consider, in degrees, as a 1-by-N row\n% vector\n% GRTYPE can be one of {'opening', 'closing', 'erosion', 'dilation'}.\n% SIZES are given as radius in pixels. Diameters of strels are obtained\n% as 2*R+1. \n% The result GR is a 1-by-N array with as many columns as the number of\n% elements provided in ANGLES array.\n%\n% [RES, DIAMS] = imOrientedGranulo(...)\n% Also returns the diameters used for each morphological filtering step.\n%\n%\n% Example\n% imOrientedGranulo\n%\n% See also\n% imGranulometry, imDirectionalGranulo, imGranulo, imGranuloByRegion,\n% granuloMeanSize \n%\n% Reference\n% The methodology is described in the following article:\n% \"Exploring the microstructure of natural fibre composites by confocal\n% Raman imaging and image analysis\", by Antoine Gallos, Gabriel Pa\u00ebs,\n% David Legland, Florent Allais, Johnny Beaugrand (2017).\n% Composites Part A: Applied Science and Manufacturing 94, p. 32-40. \n% doi: https://doi.org/10.1016/j.compositesa.2016.12.005\n%\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% Created: 2015-12-02, using Matlab 8.6.0.267246 (R2015b)\n% Copyright 2015 INRAE - Cepia Software Platform.\n\n\n% how to interpolate images\nif islogical(img)\n interp = 'nearest';\nelse\n interp = 'linear';\nend\n\n% convert sizes from radius to diameter\ndiams = 2 * strelSizes + 1;\n\n% allocate result array\nnAngles = length(angleList);\nres = zeros(1, nAngles);\n\n% iterate over the orientations\nfor iAngle = 1:nAngles\n angle = angleList(iAngle);\n imgr = imrotate(img, angle, interp);\n grCurve = imGranulo(imgr, granuloType, 'lineh', strelSizes);\n res(iAngle) = granuloMeanSize(grCurve, diams);\nend\n\n ", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imGranulometry/imOrientedGranulo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.686283621788276}} {"text": "function [VELperm, VELsystemC, VELsystemCT, rhsbcUx, rhsbcUy] = ...\n CurvedINSViscousSetUp2D(dt, nu, g0, BCfunction)\n\n% function [VELperm, VELsystemC, VELsystemCT, rhsbcUx, rhsbcUy] = ...\n% CurvedINSViscousSetUp2D(dt, nu, g0, BCfunction)\n% Purpose: build velocity system and boundary forcing terms\n\nGlobals2D;\n\n% choose order to integrate exactly\nNint = ceil(3*N/2);\n\n% build cubature nodes for all elements\nCubatureOrder = 2*(Nint+1); cub = CubatureVolumeMesh2D(CubatureOrder);\n\n% build Gauss node data for all element faces\nNGauss = (Nint+1); gauss = GaussFaceMesh2D(NGauss);\n\n% Convert boundary conditions to Dirichlet & Neumann\nsaveBCType = BCType;\nids = find(saveBCType==In | saveBCType==Wall | saveBCType==Cyl); BCType(ids) = Dirichlet;\nids = find(saveBCType==Out); BCType(ids) = Neuman;\n\n% Form inhomogeneous boundary term for rhs data (assumes time independent forcing)\n[bcUx,bcUy,bcPR] = feval(BCfunction, gauss.x, gauss.y, gauss.nx, gauss.ny, gauss.mapI, gauss.mapO, gauss.mapW, gauss.mapC, 0, nu); \n\n% Build pressure boundary condition forcing vector\n[VELsystemBC] = CurvedPoissonIPDGbc2D();\nrhsbcUx = VELsystemBC*bcUx(:); rhsbcUy = VELsystemBC*bcUy(:);\n\n% Build velocity system \n[VELsystem, mm] = CurvedPoissonIPDG2D();\nVELsystem = g0*mm/(dt*nu) + VELsystem;\n\n% Restore original boundary types\nBCType = saveBCType;\n\n% Find Reverse-Cuthill-Mckee ordering to reduce bandwith of velocity system\nVELperm = symrcm(VELsystem);\n\n% Apply row and column permutation to velocity matrix\nVELsystem = VELsystem(VELperm,VELperm);\n\n% Compute Cholesky factorization of velocity matrix\nVELsystemC = chol(VELsystem); VELsystemCT = transpose(VELsystemC);\nreturn\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/JSHesthaven&TWarburton/CFD2D/CurvedINSViscousSetUp2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605947, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6862460024984177}} {"text": "% Figure 10.54 Feedback Control of Dynamic Systems, 6e\n% Franklin, Powell, Emami\n%\n% fig10_54.m is a script to generate Fig. 10.54, the step response\n% for the fuel/air ratio with a nonlinear sensor. A (3,3)\n% Pade approximant is used to approximate the delay.\nclf;\n% construct the F/A dynamics with the sensor time-constant too\nf =[-50 0 0;\n 0 -1 0;\n 10 10 -10];\n\ng =[25.0000;\n 0.5000;\n 0];\nh =[0 0 1];\nj=0;\n[f3,g3,h3,j3 ]=pade(.2,3); % the delay Pade model\n% put the plant and the delay in series\n[fp,gp,hp,jp]=series(f,g,h,j,f3,g3,h3,j3); \n% construct the controller\nnc=.1*[1 .3];\ndc=[1 0]; % the PI controller in polynomial form\n[fc,gc,hc,jc]= tf2ss(nc, dc); % put the controller in state space form\n[fol,gol,hol,jol] = series(fc,gc,hc,jc,fp,gp,hp,jp);\n% get a discrete model for Ts = .01\n[phi,gam] = c2d(fol,gol,.01);\n% \n% form the closed-loop difference equation\nx=[0 0 0 0 0 0 0]';\nyout=[];\n\nfor t=0:.01:20;\n y=hol*x ;\n e=.4*sat(150*(.068-y));\n x=phi*x+gam*e;\n yout=[yout [e;y]];\nend\n\nt=0:.01:20;\nsubplot(211); \nplot(t,yout(1,:));\naxis( [0 20 -.6 .6]);\nxlabel('Time (sec)');\nylabel('e');\ntitle('Fig. 10.54 (b) Error plot for nonlinear control of F/A')\ngrid on;\n\nsubplot(212);\nplot(t,yout(2,:));\naxis([0 20 0 .09]);\nxlabel('Time (sec)');\nylabel('F/A');\ntitle('Fig. 10. 54 (c) Output F/A ratio for nonlinear control')\nhold off;\n%grid\nnicegrid\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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig10_54bc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.686245992235219}} {"text": "function W = compute_mesh_weight(vertices,faces,type,options)\n\n% compute_mesh_weight - compute a weight matrix\n%\n% W = compute_mesh_weight(vertices,faces,type,options);\n%\n% W is sparse weight matrix and W(i,j)=0 is vertex i and vertex j are not\n% connected in the mesh.\n%\n% todo:\n% 1. validate spring weights\n% 2. add Mean_curvature weights\n% type is either \n% 'combinatorial': W(i,j)=1 is vertex i is conntected to vertex j.\n% 'distance': W(i,j) = 1/d_ij^2 where d_ij is distance between vertex\n% i and j.\n% 'spring': W(i,j) = 1/d_ij where d_ij is distance between vertex\n% i and j.\n% 'conformal' or 'dcp': W(i,j) = cot(alpha_ij)+cot(beta_ij) where alpha_ij and\n% beta_ij are the adjacent angle to edge (i,j). Refer to Skeleton\n% Extraction by Mesh Extraction_08, and Intrinsic Parameterizations of Surface Meshes_02.\n% 'Laplace-Beltrami': W(i,j) = (cot(alpha_ij)+cot(beta_ij))/2 where alpha_ij and\n% beta_ij are the adjacent angle to edge (i,j). Refer to Computing discrete minimal surfaces\n% andtheir conjugates_93, Lemma 2 of On the convergence of metric and geometric properties of\n% polyhedral surfaces_06, and Characterizing Shape Using Conformal Factors_08, and ,\n% 'Mean_curvature',W(i,j) = (1/area_i)*(cot(alpha_ij)+cot(beta_ij))/2 where alpha_ij and\n% beta_ij are the adjacent angle to edge (i,j), area_i is the\n% area of vertex i's Voroni vicinity. Refer to ??\n% 'mvc': W(i,j) = [tan(/_kij/2)+tan(/_jil/2)]/d_ij where /_kij and /_jil\n% are angles at i\n%\n% If options.ring is offered, the computation of it can be avoided.\n%\n% Add spring and mvc weight (JJCAO, 2009)\n% Add options.ring (JJCAO, 2009)\n% Copyright (c) 2007 Gabriel Peyre\n\noptions.null = 0;\n[vertices,faces] = check_face_vertex(vertices,faces);\n\nn = max(max(faces));\n\nif isfield(options, 'verb')\n verb = options.verb;\nelse\n verb = n>5000;\nend\n\nif nargin<3\n type = 'dcp';\nend\n\nswitch lower(type)\n case 'combinatorial'\n W = triangulation2adjacency(faces);\n case 'distance'\n W = my_euclidean_distance_2(triangulation2adjacency(faces),vertices);\n W(W>0) = 1./W(W>0);\n case 'spring'\n W = sqrt(my_euclidean_distance(triangulation2adjacency(faces),vertices));\n W(W>0) = 1./W(W>0);\n case {'conformal','dcp'} % conformal laplacian \n W = compute_mesh_weight_dcp(vertices, faces, verb); \n case 'laplace-beltrami' %\n W = compute_mesh_weight_dcp(vertices, faces, verb)*0.5; \n case 'mvc'% mvc laplacian\n if isfield(options, 'rings')\n rings = options.rings;\n else\n rings = compute_vertex_face_ring(faces);\n end\n W = sparse(n,n);\n for i = 1:n\n if verb\n progressbar(i,n);\n end\n for b = rings{i}\n % b is a face adjacent to a\n bf = faces(:,b);\n % compute complementary vertices\n if bf(1)==i\n v = bf(2:3);\n elseif bf(2)==i\n v = bf([1 3]);\n elseif bf(3)==i\n v = bf(1:2);\n else\n error('Problem in face ring.');\n end\n j = v(1); k = v(2);\n vi = vertices(:,i);\n vj = vertices(:,j);\n vk = vertices(:,k);\n % angles\n alpha = myangle(vi-vk,vi-vj);\n % add weight\n W(i,j) = W(i,j) + tan( 0.5*alpha )/sqrt(sum((vi-vj).^2));\n W(i,k) = W(i,k) + tan( 0.5*alpha )/sqrt(sum((vi-vk).^2));\n end\n end \n otherwise\n error('Unknown type.')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction W = compute_mesh_weight_dcp(verts, faces, verb)\nn = size(verts,2);\nW = sparse(n,n);\n% new implementation\nfor i = 1:size(faces,2)\n c = faces(:,i);\n \n v1 = verts(:,c(1));\n v2 = verts(:,c(2));\n v3 = verts(:,c(3));\n \n cot1 = dot(v2-v1,v3-v1)/norm(cross(v2-v1,v3-v1));\n cot2 = dot(v3-v2,v1-v2)/norm(cross(v3-v2,v1-v2));\n cot3 = dot(v1-v3,v2-v3)/norm(cross(v1-v3,v2-v3));\n \n W(c(2),c(3)) = W(c(2),c(3)) + cot1;\n W(c(3),c(2)) = W(c(3),c(2)) + cot1;\n W(c(3),c(1)) = W(c(3),c(1)) + cot2;\n W(c(1),c(3)) = W(c(1),c(3)) + cot2;\n W(c(1),c(2)) = W(c(1),c(2)) + cot3;\n W(c(2),c(1)) = W(c(2),c(1)) + cot3; \nend\n\n%%\n% old implementation\n% for i = 1:n\n% if verb\n% progressbar(i,n);\n% end\n% for b = rings{i}\n% % b is a face adjacent to a\n% bf = faces(:,b);\n% % compute complementary vertices\n% if bf(1)==i\n% v = bf(2:3);\n% elseif bf(2)==i\n% v = bf([1 3]);\n% elseif bf(3)==i\n% v = bf(1:2);\n% else\n% error('Problem in face ring.');\n% end\n% j = v(1); k = v(2);\n% vi = verts(:,i);\n% vj = verts(:,j);\n% vk = verts(:,k);\n% \n% u = vk-vi; v = vk-vj;\n% W(i,j) = W(i,j) + dot(u,v)/norm(cross(u,v));\n% u = vj-vi; v = vj-vk;\n% W(i,k) = W(i,k) + dot(u,v)/norm(cross(u,v));\n% end\n% end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction beta = myangle(u,v)\ndu = sqrt( sum(u.^2) );\ndv = sqrt( sum(v.^2) );\ndu = max(du,eps); dv = max(dv,eps);\nbeta = acos( sum(u.*v) / (du*dv) );\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction W = my_euclidean_distance_2(A,vertex)\n% square euclidean distance\nif size(vertex,1) 6) \n error('Invalid number of input arguments.');\nend\n\nansi = 0;\niec = 0;\nif nargin > 4\n if strcmp(lower(s),'ansi')\n ansi = 1;\n if nargin == 5\n n = 3;\n end\n elseif strcmp(lower(s),'cei') | strcmp(lower(s),'iec')\n iec = 1;\n if nargin == 5\n n = 1\n end\n if (n < 0) | (n > 3) \n error('IEC class must be 0, 1, or 2');\n end\n end\nend\n\nN = 512;\npi = 3.14159265358979;\nF = logspace(log10(Fc/10),log10(min(Fc*10,Fs/2)),N);\nH = freqz(B,A,2*pi*F/Fs);\nG = 20*log10(abs(H));\n\n% Set output variables. \nif nargout ~= 0\n g = G; f = F; \n return\nend\n\n% Generate the plot\nif (ansi) \t\t\t\t% ANSI Order-n specification\n f = logspace(log10(Fc/10),log10(Fc*10),N);\n f1 = Fc/sqrt(2);\n f2 = Fc*sqrt(2);\n Qr = Fc/(f2-f1);\n Qd = (pi/2/n)/(sin(pi/2/n))*Qr;\n Af = 10*log10(1+Qd^(2*n)*((f/Fc)-(Fc./f)).^(2*n));\n semilogx(F,G,f,-Af,'--');\n legend('Filter',['ANSI order-' int2str(n)],0); \nelseif (iec) \t\t\t\t\t% CEI specification\n semilogx(F,G);\n hold on\n if n == 0 \n tolup = [ .15 .15 .15 .15 .15 -2.3 -18.0 -42.5 -62 -75 -75 ];\n tollow = [ -.15 -.2 -.4 -1.1 -4.5 -realmax -inf -inf -inf -inf -inf ];\n elseif n == 1\n tolup = [ .3 .3 .3 .3 .3 -2 -17.5 -42 -61 -70 -70 ];\n tollow = [ -.3 -.4 -.6 -1.3 -5 -realmax -inf -inf -inf -inf -inf ];\n elseif n == 2\n tolup = [ .5 .5 .5 .5 .5 -1.6 -16.5 -41 -55 -60 -60 ];\n tollow = [ -.5 -.6 -.8 -1.6 -5.5 -realmax -inf -inf -inf -inf -inf ];\n end\n U = 2; \n f = Fc * U.^[ 0 1/8 1/4 3/8 1/2 1/2 1 2 3 4 NaN ]; \n ff = Fc * U.^[ 0 -1/8 -1/4 -3/8 -1/2 -1/2 -1 -2 -3 -4 NaN ]; \n f(length(f)) = realmax; \n ff(length(ff)) = realmin; \n semilogx(F,G,f,tolup,'--');\n semilogx(F,G,f,tollow,'--');\n semilogx(F,G,ff,tolup,'--');\n semilogx(F,G,ff,tollow,'--');\n hold off\n legend('Filter',['IEC class ' int2str(n)],0); \nelse\n semilogx(F,G);\nend\nxlabel('Frequency [Hz]'); ylabel('Gain [dB]');\ntitle(['Octave filter: Fc =',int2str(Fc),' Hz, Fs = ',int2str(Fs),' Hz']);\naxis([Fc/10 Fc*10 -80 5]);\ngrid on\n\n \n\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/69-octave/octave/octspec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.6862143772684849}} {"text": "function daub10_scale_plot ( n )\n\n%*****************************************************************************80\n%\n%% DAUB10_SCALE_PLOT plots the DAUB10 scaling function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 August 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the recursion level.\n%\n x = linspace ( 0.0, 10.0, 801 );\n\n y = daub10_scale ( n, x );\n\n plot ( x, y, 'LineWidth', 2 );\n\n grid on\n xlabel ( '<---X--->' );\n ylabel ( '<---Y--->' );\n title ( sprintf ( 'DAUB10 Scale Function, Recursion level n = %d', 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/wavelet/daub10_scale_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.865224091265267, "lm_q1q2_score": 0.6862143758903484}} {"text": "function x = r8sto_yw_sl ( n, b, x )\n\n%*****************************************************************************80\n%\n%% R8STO_YW_SL solves the Yule-Walker equations for a R8STO matrix.\n%\n% Discussion:\n%\n% The R8STO storage format is used for a symmetric Toeplitz matrix.\n% It stores the N elements of the first row.\n%\n% The matrix is also required to be positive definite.\n%\n% This implementation of the algorithm assumes that the diagonal element\n% is 1.\n%\n% The real symmetric Toeplitz matrix can be described by N numbers, which,\n% for convenience, we will label B(0:N-1). We assume there is one more\n% number, B(N). If we let A be the symmetric Toeplitz matrix whose first\n% row is B(0:N-1), then the Yule-Walker equations are:\n%\n% A * X = -B(1:N)\n%\n% Example:\n%\n% To solve\n%\n% 1.0 0.5 0.2 x1 0.5\n% 0.5 1.0 0.5 * x2 = 0.2\n% 0.2 0.5 1.0 x3 0.1\n%\n% we input:\n%\n% N = 3\n% B(1:3) = (/ 0.5, 0.2, 0.1 /)\n%\n% with output:\n%\n% X(1:3) = (/ -75, 12, -5 /) / 140\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 March 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Gene Golub and Charles Van Loan,\n% Section 4.7.2, \"Solving the Yule-Walker Equations\",\n% Matrix Computations,\n% Third Edition,\n% Johns Hopkins, 1996.\n%\n% Parameters:\n%\n% Input, integer N, the order of the system.\n%\n% Input, real B(N), defines the linear system. The first entry of A is\n% a 1, followed by B(1) through B(N-1). The right hand side of the\n% system is -B(1:N).\n%\n% Output, real X(N), the solution of the linear system.\n%\n x(1) = -b(1);\n beta = 1.0E+00;\n alpha = -b(1);\n\n for i = 1 : n-1\n beta = ( 1.0E+00 - alpha * alpha ) * beta;\n alpha = - ( b(i+1) + b(i:-1:1) * x(1:i)' ) / beta;\n x(1:i) = x(1:i) + alpha * x(i:-1:1);\n x(i+1) = alpha;\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/r8sto_yw_sl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.686214374512212}} {"text": "function kpu_sparse_test ( )\n\n%*****************************************************************************80\n%\n%% KPU_SPARSE_TEST uses the KPU function to build a sparse grid.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 April 2012\n%\n% Author:\n%\n% Original MATLAB version by Florian Heiss, Viktor Winschel.\n% This MATLAB version by John Burkardt.\n%\n% Local parameters:\n%\n% Local, integer D, the spatial dimension.\n%\n% Local, integer MAXK, the maximum level to check.\n%\n d = 10;\n maxk = 4;\n func = 'prod( exp(-(x/2).^2/2)/2/sqrt(2*pi), 2)';\n trueval = fu_integral ( d );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'KPU_SPARSE_TEST:\\n' );\n fprintf ( 1, ' KPU sparse grid:\\n' );\n fprintf ( 1, ' Sparse nested, unweighted quadrature over [0,1].\\n' );\n fprintf ( 1, ' Exact integral is %g\\n', trueval );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' D Level Nodes SG error MC error\\n' );\n fprintf ( 1, '\\n' );\n\n for k = 2 : maxk\n%\n% Compute sparse grid estimate.\n%\n [ x, w ] = nwspgr ( 'kpu', d, k );\n fx = eval ( func );\n SGappr = w' * fx;\n SGerror = sqrt((SGappr - trueval).^2)/trueval;\n%\n% Average 1000 Monte Carlo estimates.\n%\n numnodes = length ( w );\n sim = zeros(1000,1);\n for r = 1 : 1000\n x = rand ( numnodes, d );\n fx = eval ( func );\n sim(r) = mean ( fx );\n end\n simerror = sqrt ( mean( ( sim - trueval).^2) ) / trueval;\n\n fprintf( ' %2d %2d %6d %10.5g %10.5g\\n', ...\n d, k, numnodes, SGerror, simerror )\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_hw/kpu_sparse_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.686214371115239}} {"text": "%This Matlab script can be used to reproduce Figure 1.18 in the monograph:\n%\n%Emil Bjornson, Jakob Hoydis and Luca Sanguinetti (2017), \n%\"Massive MIMO Networks: Spectral, Energy, and Hardware Efficiency\", \n%Foundations and Trends in Signal Processing: Vol. 11, No. 3-4, \n%pp. 154-655. DOI: 10.1561/2000000093.\n%\n%For further information, visit: https://www.massivemimobook.com\n%\n%This is version 1.01 (Last edited: 2019-04-17)\n%\n%License: This code is licensed under the GPLv2 license. If you in any way\n%use this code for research that results in publications, please cite our\n%monograph as described above.\n\n\n%Empty workspace and close figures\nclose all;\nclear;\n\n\n%Define the SNR\nSNR = 1;\n\n%Define betabar (strength of inter-cell interference)\nbetabar = 1e-1;\n\n%Define the range of number of UEs\nK = 1:20;\n\n%Define range of antenna-UE ratios\nc = [1 2 4 8];\n\n%Extract the maximal number of UEs and BS antennas\nKmax = max(K);\nMmax = Kmax*max(c);\n\n%Select number of Monte Carlo realizations for the line-of-sight (LoS)\n%angles and of the non-line-of-sight (NLoS) Rayleigh fading\nnumberOfRealizations = 10000;\n\n\n%Generate NLoS channels using uncorrelated Rayleigh fading\nH_NLoS_desired = sqrt(1/2)*(randn(Mmax,Kmax,numberOfRealizations)+1i*randn(Mmax,Kmax,numberOfRealizations));\nH_NLoS_interfering = sqrt(betabar/2)*(randn(Mmax,Kmax,numberOfRealizations)+1i*randn(Mmax,Kmax,numberOfRealizations));\n\n\n%Preallocate matrices for storing the simulation results\nSE_MMSE_NLoS_montecarlo = zeros(length(K),length(c));\nSE_MMSE_NLoS_nonlinear = zeros(length(K),length(c));\n\n\n%% Go through all Monte Carlo realizations\nfor n = 1:numberOfRealizations\n \n %Output simulation progress\n disp([num2str(n) ' realizations out of ' num2str(numberOfRealizations)]);\n \n %Go through the range of number of UEs\n for kindex = 1:length(K)\n \n %Go through the range of antenna-UE ratios\n for cindex = 1:length(c)\n \n %Compute the number of antennas\n M = K(kindex)*c(cindex);\n \n \n %Compute the SE with non-linear processing under NLoS propagation\n %for one realization of the Rayleigh fading. We use the classic\n %log-det formula for the uplink sum SE, when treating the\n %inter-cell interference as colored noise\n SE_MMSE_NLoS_nonlinear(kindex,cindex) = SE_MMSE_NLoS_nonlinear(kindex,cindex) + real(log2(det(eye(M) + SNR* H_NLoS_desired(1:M,1:K(kindex),n)*H_NLoS_desired(1:M,1:K(kindex),n)' + SNR*H_NLoS_interfering(1:M,1:K(kindex),n)*H_NLoS_interfering(1:M,1:K(kindex),n)' )) - log2(det(eye(M)+SNR*H_NLoS_interfering(1:M,1:K(kindex),n)*H_NLoS_interfering(1:M,1:K(kindex),n)')))/numberOfRealizations;\n\n \n %Compute the SE with M-MMSE under NLoS propagation for one\n %realization of the Rayleigh fading\n \n %Compute the M-MMSE combining vectors\n MMMSEfilter = ( SNR* H_NLoS_desired(1:M,1:K(kindex),n)*H_NLoS_desired(1:M,1:K(kindex),n)' + SNR* H_NLoS_interfering(1:M,1:K(kindex),n)*H_NLoS_interfering(1:M,1:K(kindex),n)' + eye(M) ) \\ (SNR*H_NLoS_desired(1:M,1:K(kindex),n));\n \n %Compute the intra-cell channel powers after M-MMSE combining\n channelgainsIntracell = abs(MMMSEfilter'*H_NLoS_desired(1:M,1:K(kindex),n)).^2;\n \n %Extract the desired signal power for each UE\n signalpowers = diag(channelgainsIntracell);\n \n %Extract and compute interference powers for each UE\n interferencepowers = sum(channelgainsIntracell,2) - signalpowers + sum(abs(MMMSEfilter'*H_NLoS_interfering(1:M,1:K(kindex),n)).^2,2);\n \n %Compute the effective 1/SNR after noise amplification\n scalednoisepower = (1/SNR)*sum(abs(MMMSEfilter').^2,2);\n \n %Compute the uplink SE with M-MMSE combining\n SE_MMSE_NLoS_montecarlo(kindex,cindex) = SE_MMSE_NLoS_montecarlo(kindex,cindex) + sum(log2(1 + signalpowers./(interferencepowers+scalednoisepower)))/numberOfRealizations;\n \n \n end\n \n end\n \nend\n\n\n\n%% Plot the simulation results\nfigure(1);\nhold on; box on;\n\nplot(K,SE_MMSE_NLoS_montecarlo(:,4)./SE_MMSE_NLoS_nonlinear(:,4),'r-','LineWidth',1);\nplot(K,SE_MMSE_NLoS_montecarlo(:,3)./SE_MMSE_NLoS_nonlinear(:,3),'k-.','LineWidth',1);\nplot(K,SE_MMSE_NLoS_montecarlo(:,2)./SE_MMSE_NLoS_nonlinear(:,2),'b--','LineWidth',1);\nplot(K,SE_MMSE_NLoS_montecarlo(:,1)./SE_MMSE_NLoS_nonlinear(:,1),'k:','LineWidth',1);\n \nxlabel('Number of UEs (K)');\nylabel('Fraction of non-linear performance');\n\nlegend('M/K=8','M/K=4','M/K=2','M/K=1','Location','SouthWest');\nylim([0.5 1]);\n", "meta": {"author": "emilbjornson", "repo": "massivemimobook", "sha": "4e429497dea72d52172972f3f686b34d1d047013", "save_path": "github-repos/MATLAB/emilbjornson-massivemimobook", "path": "github-repos/MATLAB/emilbjornson-massivemimobook/massivemimobook-4e429497dea72d52172972f3f686b34d1d047013/Code/section1_figure18.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6861811521612496}} {"text": "function value = r8_epsilon ( )\n\n%*****************************************************************************80\n%\n%% R8_EPSILON returns the R8 roundoff unit.\n%\n% Discussion:\n%\n% The roundoff unit is a number R which is a power of 2 with the \n% property that, to the precision of the computer's arithmetic,\n% 1 < 1 + R\n% but \n% 1 = ( 1 + R / 2 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 August 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real VALUE, the roundoff unit.\n%\n value = eps;\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/r8_epsilon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867969424067, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.6861722525971967}} {"text": "function [I J K]=sphere_index(r,Ic,Jc,Kc)\n\n% function [I J K]=sphere_index(r)\n% ------------------------------------------------------------------------\n% This function generates the indices 'I', 'J' and 'K' of voxel centers\n% found within a sphere of radius 'r' (in voxels). The indices are not\n% 'real' indices but are 'centered around zero'. They can be used to\n% generate the indices of voxels found inside a sphere around point 'n' by\n% adding In,Jn,Kn to I,J and K.\n%\n%\n% Kevin Mattheus Moerman\n% kevinmoerman@hotmail.com\n% 07/08/2008\n% ------------------------------------------------------------------------\n\nif nargin == 1\n Ic=0; Jc=0; Kc=0;\nend\n\n%Set-up mesh calculate radius\n[X,Y,Z] = meshgrid((-round(r+1)):1:(round(r+1)));\nX=X+Jc; Y=Y+Ic; Z=Z+Kc;\nradius = hypot(hypot(X,Y),Z);\n[I,J,K]=ind2sub(size(X),find(radius<=r)); \nIJK_middle=round(size(X)/2);\nI=I-IJK_middle(1);\nJ=J-IJK_middle(2);\nK=K-IJK_middle(3);\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/sphere_index.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.6861722472130375}} {"text": "function r=roteu2ro(m,t)\n%ROTEU2QR converts a sequence of Euler angles to a real unit quaternion\n% Inputs:\n%\n% M(1,n) a string of n characters from the set {'x','y','z'}\n% or, equivalently, a vector whose elements are 1, 2, or 3\n% T(n,1) n rotation angles. A positive rotation is clockwise if\n% looking along the axis away from the origin.\n%\n% Outputs:\n%\n% R(3,3) Input rotation matrix\n% Plots a diagram if no output specified\n%\n% The string M specifies the axes about which the rotations are performed.\n% You cannot have the same axis in adjacent positions and so there are 12\n% possibilities. Common ones are \"ZXZ\" and \"ZYX\". A positive rotation is clockwise\n% if looking along the axis away from the origin; thus a rotation of +pi/2\n% around Z rotates [1 0 0]' to [0 1 0]'.\n% \n% Inverse conversion: If m has length 3 with adjacent characters distinct,\n% then rotro2eu(m,roteu2ro(m,t))=t.\n%\n% Inverse rotation: roteu2ro(m,t)*roteu2ro(fliplr(m),-fliplr(t))=eye(3)\n\n%\n% Copyright (C) Mike Brookes 2007-2012\n% Version: $Id: roteu2ro.m 2171 2012-07-12 07:33:03Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\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 can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nr=rotqr2ro(roteu2qr(m,t));", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/roteu2ro.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.6861722364447179}} {"text": "function value = p16_f ( dim_num, point_num, x )\n\n%*****************************************************************************80\n%\n%% P16_F evaluates the integrand for problem 16.\n%\n% Discussion:\n%\n% The integrand can be regarded as the L1 norm of X - Z.\n%\n% It would be nice to allow the use to specify several\n% base points Z, to make the function more jagged more places%\n%\n% Dimension:\n%\n% DIM_NUM arbitrary.\n%\n% Region:\n%\n% 0 <= X(1:DIM_NUM) <= 1\n%\n% Integral Parameters:\n%\n% The integrand can be regarded as the L1 norm of X - Z.\n%\n% There is a basis point Z associated with the integrand.\n% Z(1:DIM_NUM) defaults to ( 0.5, 0.5, ..., 0.5 ).\n% The user can set, get, or randomize this value by calling\n% P16_R8VEC.\n%\n% Integrand:\n%\n% sum ( abs ( x(1:dim_num) - z(1:dim_num) ) )\n%\n% Exact Integral:\n%\n% The integral is separable into\n%\n% Int ( A(1) <= X(1) <= B(1) ) abs ( X(1) - Z(1) ) \n% * Product ( B(1:N)-A(1:N), skip index 1 )\n% + Int ( A(2) <= X(2) <= B(2) ) abs ( X(2) - Z(2) )\n% * Product ( B(1:N)-A(1:N), skip index 2 )\n% ...\n% + Int ( A(N) <= X(N) <= B(N) ) abs ( X(N) - Z(N) )\n% * Product ( B(1:N)-A(1:N), skip index N )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 June 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the dimension of the argument.\n%\n% Input, integer POINT_NUM, the number of points.\n%\n% Input, real X(DIM_NUM,POINT_NUM), the evaluation points.\n%\n% Output, real VALUE(POINT_NUM), the integrand values.\n%\n z = [];\n z = p16_r8vec ( 'G', 'Z', dim_num, z );\n\n value(1:point_num) = 0.0;\n\n for point = 1 : point_num\n\n value(point) = sum ( abs ( x(1:dim_num,point) - z(1:dim_num)' ) );\n\n end\n\n p16_i4 ( 'I', '#', point_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/p16_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.6861722249654787}} {"text": "clc;\nclear;\nclose all;\n\nT0 = 500 ; % initial temperature\nr = 0.997 ; % temperature damping rate\nTs = 1 ; % stop temperature\niter = 300;\n\nmodel = initModel();\nset(gcf,'unit','normalized','position',[0,0.35,1,0.7]);\n\nflag = 0;\n\n% initialization\nwhile(1)\nroute = randomSol(model);\nif(isFeasible(route,model)) \n break; \nend\nend\n\ncost = calculateCost(route,model);\nT = T0;\n\ncnt = 1;\nminCost = cost;\nminRoute = route;\n \nmaxIterate = 2100;\ncostArray = zeros(maxIterate,1);\n\n% SA\nwhile(T > Ts)\n for k = 1:iter\n mode = randi([1 3]);\n newRoute = createNeibor(route,model,mode);\n newCost = calculateCost(newRoute,model);\n delta = newCost - cost;\n \n if(delta < 0)\n cost = newCost;\n route = newRoute;\n else\n p=exp(-delta/T);\n if rand() <= p \n cost = newCost;\n route = newRoute;\n \n end\n end\n end\n \n costArray(cnt) = cost;\n if cost 0\n % error(sprintf('There are %d non-manifold edges',S.num_nonmanifold_edges));\n %end\n\n switch size(F,2)\n case 3\n % number of vertices\n n = size(V,1);\n % number of faces\n m = size(F,1);\n % Compute cotangents\n C = cotangent(V,F);\n % Map each face-edge to a unique edge\n F2E = reshape(1:3*m,m,3);\n % Assemble entries\n % R S S R S S R S S\n LI = [ F2E(:,[1 1 1 2 2 2 3 3 3]) ];\n LJ = [ F(:,[1 2 3 2 3 1 3 1 2]) ];\n LV = [ ...\n C(:,2)+C(:,3), -C(:,3), -C(:,2) ...\n C(:,3)+C(:,1), -C(:,1), -C(:,3) ...\n C(:,1)+C(:,2), -C(:,2), -C(:,1)];\n\n %warning('only spokes');\n %LI = LI(:,[2 3 5 6 8 9]);\n %LJ = LJ(:,[2 3 5 6 8 9]);\n %LV = LV(:,[2 3 5 6 8 9]);\n %warning('only rims');\n %LI = LI(:,[1 4 7]);\n %LJ = LJ(:,[1 4 7]);\n %LV = LV(:,[1 4 7]);\n\n assert(all(size(LI)==size(LJ)));\n assert(all(size(LI)==size(LV)));\n % Throw contribution at each edge\n L = sparse(LI,LJ,LV,3*m,n);\n\n allE = [F(:,[2 3]);F(:,[3 1]);F(:,[1 2])];\n % Map duplicate edges to first instance\n [E,~,EMAP] = unique(sort(allE,2),'rows');\n\n L = sparse(EMAP,F2E(:),1,size(E,1),3*m) * L;\n\n % Q: What's going on for boundary edges?\n % A: Interior edges are integrating around butterly. Boundary edges are only\n % integrating around half what would be their butterfly. They \"should\" also\n % integrate along themselves to enclose an area. Since they don't they\n % amount to computing minus the normal derivative.\n case 4\n [Lcr,E] = crouzeix_raviart_cotmatrix(V,F); \n A = sparse(E(:),repmat(1:size(E,1),1,3)',1,size(V,1),size(E,1))';\n Df = diag(sparse(sum(A,2)));\n % Legacy factor of 2 to match triangle version\n L = 0.5*3*Lcr*(Df\\A);\n % Lv == 0.5*A'*Lf;\n end\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/facet_laplacian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6861634687123164}} {"text": "function[]=makefigs_morsebox\n%MAKEFIGS_MORSEBOX Makes a sample figure for MORSEBOX.\n\nga1=(1/3:.1:11);\nbe1=(1/3:.1:10);\n\n[ga,be]=meshgrid(ga1,be1);\n[fm,fe,fi,cf] = morsefreq(ga,be);\na=morsebox(ga,be);\n\nfigure\ncontourf(ga1,be1,a,(.5:.01:.6))\nhold on, contour(ga1,be1,a,(.500:.002:.51),'k:')\ncolormap gray,flipmap,\naxis([1 10 1 10])\nxtick(1:10),ytick(1:10)\nax=gca;\nhc=colorbar;\n\ncontour(ga1,be1,(fm-fe)./(2*pi),[ 0 0],'k','linewidth',2)\ncontour(ga1,be1,(fm-fi)./(2*pi),[ 0 0],'k','linewidth',2)\ncontour(ga1,be1,cf./(2*pi),[ 0 0],'k','linewidth',2)\ncaxis([.5 .6])\nvlines(3,'k--')\nplot(ga1,12./ga1,'k')\n \ntitle('Morse Wavelet Area and Transitions')\nxlabel('Gamma Parameter')\nylabel('Beta Parameter')\nplot([1+sqrt(-1)*0 10+sqrt(-1)*9/2],'k','linewidth',3)\nplot([1+sqrt(-1)*0 10+sqrt(-1)*9/2],'w--','linewidth',2)\n\n\n\n", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jfigures/makefigs_morsebox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6861634585699953}} {"text": "function Problem2_26\n%Problem 2.26 Ternary condensation inside a vertical tube.\n% Uses the function BVP4C to numerically solve the boundary-value problem.\n% BVPINIT is used to form an initial guess for the solution on \n% a mesh of ten equally spaced points. A guess for unknown parameters \n% (the two fluxes) is the last argument of BVPINIT.\n% BVP4C returns the solution as the structure 'sol'. The computed fluxes are \n% returned in the field sol.parameters.\n% The calculated concentration profiles are plotted.\n\n% Calculate the mass-transfer coefficients\nRe = 9574;\ndensity = 0.882;\nviscosity = 0.00001602;\ndiameter = 0.0254;\n% MS diffusion coefficients\nD = [1.6*10^-5 1.444*10^-5 3.873*10^-5];\n% Calculate Schmidt numbers\nSc(1) = viscosity/(density*D(1));\nSc(2) = viscosity/(density*D(2));\nSc(3) = viscosity/(density*D(3));\n% Calculate Sherwood numbers\nSh(1) = 0.023*Re^0.83*Sc(1)^0.44;\nSh(2) = 0.023*Re^0.83*Sc(2)^0.44;\nSh(3) = 0.023*Re^0.83*Sc(3)^0.44;\n% Molecular weight of pure components\nM = [60.1 18 28];\ny1 = [0.1123\n 0.4246\n 0.4631];\nMav1 = M*y1;\ny2 = [0.1457\n 0.1640\n 0.6903];\nMav2 = M*y2;\nMav = (Mav1+Mav2)/2;\n% Calculate total molar density\nc = density/Mav;\nF12 = Sh(1)*c*D(1)*1000/diameter;\nF13 = Sh(2)*c*D(2)*1000/diameter;\nF23 = Sh(3)*c*D(3)*1000/diameter;\nsolinit = bvpinit(linspace(0,1,10),[1, 1], [1, 1]);\noptions = bvpset('stats','on'); \nsol = bvp4c(@prob226ode,@prob226bc,solinit,options,F12,F13,F23);\nx = sol.x;\ny = sol.y;\ny(3,:) = 1-y(1,:) -y(2,:);\nfprintf('\\n');\nfprintf('Computed Mass-Transfer Coefficients:');\nfprintf('\\n');\nfprintf('F12, mole/m2-s = %7.4f.\\n',F12);\nfprintf('\\n');\nfprintf('F13, mole/m2-s = %7.4f.\\n',F13);\nfprintf('\\n');\nfprintf('F23, mole/m2-s = %7.4f.\\n',F23);\nfprintf('\\n');\nfprintf(' Computed N1 in mole/m2-s =%7.4f.\\n',sol.parameters(1))\nfprintf('\\n')\nfprintf(' Computed N2 in mole/m2-s=%7.4f.\\n',sol.parameters(2))\nfprintf('\\n')\nclf reset\nplot(x,y(1,:),'k-*',x,y(2,:),'k:+',x,y(3,:),'k-.o')\naxis([0 1 0 0.7])\ntitle('Concentration profiles in Problem 2.26') \nxlabel('Distance along the diffusion path, cm.')\nylabel('Mole fraction')\nlegend('Isopropanol', 'Water', 'Nitrogen')\nshg\n\n\n% --------------------------------------------------------------------------\n\nfunction dydx = prob226ode(x,y,N,F12,F13,F23)\nN3 = 0;\n\n%F12 = 0.933;\n%F13 = 0.880;\n%F23 = 1.530;\ndydx = [ (y(1)*N(2)-y(2)*N(1))/F12+(y(1)*N3-(1-y(1)-y(2))*N(1))/F13\n (y(2)*N(1)-y(1)*N(2))/F12+(y(2)*N3-(1-y(1)-y(2))*N(2))/F23 ];\n\n% --------------------------------------------------------------------------\n \nfunction res = prob226bc(ya,yb,N,F12,F13,F23)\nres = [ya(2)-0.4246 \n yb(2) - 0.1640 \n ya(1) - 0.1123\n yb(1) - 0.1457 ];\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/2970-principles-and-modern-applications-of-mass-transfer-operations/MatlabExamples/Problem2_26.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6861634567793792}} {"text": "function psnr= PSNR(X,Y)\n%Calculates the Peak-to-peak Signal to Noise Ratio of two images X and Y\n[M,N]=size(X);\nm=double(0);\nX=cast(X,'double');\nY=cast(Y,'double');\nfor i=1:M\n for j=1:N\n m=m+((X(i,j)-Y(i,j))^2);\n end\nend\nm=m/(M*N);\npsnr=10*log10(255*255/m);", "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/37326-psnr-image-processing/PSNR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6861217502510737}} {"text": "function out = DN_Spread(y,spreadMeasure)\n% DN_Spread Measure of spread of the input time series.\n%\n% Returns the spread of the raw data vector, as the standard deviation,\n% inter-quartile range, mean absolute deviation, or median absolute deviation.\n%\n%---INPUTS:\n% y, the input data vector\n%\n% spreadMeasure, the spead measure:\n% (i) 'std': standard deviation\n% (ii) 'iqr': interquartile range\n% (iii) 'mad': mean absolute deviation\n% (iv) 'mead': median absolute deviation\n\n% ------------------------------------------------------------------------------\n% Copyright (C) 2020, Ben D. Fulcher ,\n% \n%\n% If you use this code for your research, please cite the following two papers:\n%\n% (1) B.D. Fulcher and N.S. Jones, \"hctsa: A Computational Framework for Automated\n% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).\n% DOI: 10.1016/j.cels.2017.10.001\n%\n% (2) B.D. Fulcher, M.A. Little, N.S. Jones, \"Highly comparative time-series\n% analysis: the empirical structure of time series and their methods\",\n% J. Roy. Soc. Interface 10(83) 20130048 (2013).\n% DOI: 10.1098/rsif.2013.0048\n%\n% This function is free software: you can redistribute it and/or modify it under\n% the terms of the GNU General Public License as published by the Free Software\n% Foundation, either version 3 of the License, or (at your option) any later\n% version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT\n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n% details.\n%\n% You should have received a copy of the GNU General Public License along with\n% this program. If not, see .\n% ------------------------------------------------------------------------------\n\n% ------------------------------------------------------------------------------\n% Check Inputs\n% ------------------------------------------------------------------------------\nif nargin < 2 || isempty(spreadMeasure)\n spreadMeasure = 'std'; % return std by default\nend\n\n% ------------------------------------------------------------------------------\n% Evaluate the spread measure\n% ------------------------------------------------------------------------------\nswitch spreadMeasure\n\tcase 'std'\n % Standard deviation\n\t\tout = std(y);\n\n\tcase 'iqr'\n % Interquartile range\n\t\tout = iqr(y);\n\n\tcase 'mad'\n % Mean absolute deviation\n\t\tout = mad(y,0);\n\n case 'mead'\n % Median absolute deviation\n out = mad(y,1);\n\n otherwise\n error('Unknown spread measure ''%s''',spreadMeasure)\nend\n\nend\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Operations/DN_Spread.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.686046565063321}} {"text": "function [x, L]= time_step_RBF_new(W,x,lambda,timestep,time_step_value)\n\n\n% build the degree function ( d_i = sum_j w_ij)\nW=sparse(W);\nD=sum(W,2);\nlaplacian = 1;\n[dim num] = size(x);\nif nargin<5\n \n time_step_value=0.25;\n time_step_value=0.1;\n time_step_value=0.25;\n time_step_value=0.1;\n time_step_value=0.2;%% for depth \n time_step_value=0.1;\nend\n\n% checks if elements of the degree function are zero and correct this\nif(sum(D==0)>0)\n disp('Warning, Elements of d are zero');\n for i=1:num\n if(D(i)==0), D(i)=1; end\n end\nend\n% type of Laplacian (normalized, unnormalized)\n\n% build the final weight matrix - reweighted by some power of the degree\n% function \\tilde{k}_ij = k_ij / pow(d_i d_j, lambda)\nif(lambda~=0)\n f=spdiags(1./(D.^lambda), 0, num, num);\n W=1/(num)*f*W*f;\n clear f;\nend\nclear d\n\n% final degree function of weights \\tilde{k}\ne=sum(W,2);\nif(sum(e==0)>0)\n disp('Warning, Elements of e are zero');\n for i=1:num\n if(e(i)==0), e(i)=1/(num); end\n end\nend\n\n% for the time step it is easier to have the transpose of x\nx=x';\n\ntic\nif(timestep==0)\n % explicit timestep\n D=spdiags(e,0,num,num);\n L=D-W;\n step=-0.1*L*x;\n x = x + step;\nelse\n % implicit timestep\n D=spdiags(e,0,num,num);\n \n \n \n L=sparse(D-W);\n %L=sparse(L);\n switch laplacian\n case 0,\n %normalized, solve L*x_new =x_old, where L=Id - E^{-1}W\n \n z=(D+0.25*L)\\(D*x);\n % z=(D+0.1*L)\\(D*x);\n diff = z - x;\n for i=1:num\n x(i,:) = x(i,:) + diff(i,:);\n end\n case 1,\n %unnormalized\n % z=cholmod(speye(num) + 0.5*L,x);\n\n \n z = (speye(num) + time_step_value*L)\\x;\n diff = z - x;\n \n \n parfor i=1:num\n x(i,:) = x(i,:) + diff(i,:);\n end\n \n \n end\nend\n\nx=x'; % transform the data back in column format (one data point=one column in x)\nt=toc;\n% disp(['Time for time step: ', num2str(t),' seconds']);\n% time_step_value", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u53bb\u566a\u7b97\u6cd5/Robust-Manifold-Denoising--master/time_step_RBF_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6860465610527043}} {"text": "function [fAlpha, fDmax] = calc_KStestGR(mCatalog, fBinning, fBValue, fMc)\n% [mAlphaVal] = calc_KStestGR(mCatalog, fBinning, fBValue)\n% ------------------------------------------------------------------------\n% Calculate Koglomorov-Smirnov-test with constant b-value\n% Reference for equations to calculate the statistics nD:\n% Y.Y. Kagan, Accuracy of modern global earthquake catalogs, Physics of the Earth and Planetary Interiors\n% 4179, 1-37, 2002\n%\n% Incoming variables:\n% mCatalog : Earthquake catalog\n% fBinning : Binning interval\n% fBValue : Fix b-value\n%\n% Outgoing variables:\n% mAlphaVal(:,1) : Significance level Alpha according to ascending magnitudes\n% mAlphaVal(:,2) : Ascending magnitudes\n%\n% Author: J. Woessner\n% last update: 25.03.03\n\n% Initialize\nmAlphaVal = [];\nvD = [];\n\n% Select data above Mc\nvSel = (mCatalog(:,6) >= fMc);\nmCatalog = mCatalog(vSel,:);\n\n% Set fix values\nfMaxMag = ceil(10 * max(mCatalog(:,6))) / 10;\nfMinMag = (round(min(mCatalog(:,6)*10)))/10;\nvMag = fMinMag:0.1:fMaxMag;\n\n% Using Bath's law : see Reference Console\n% Beta-value\nfBeta = log(10)*fBValue;\n\n% Probability density function\n% vPdf = fBeta*exp(-fBeta*(vMag-fMc))\n%\n% % Cumulative density function\n% vCdf = cumsum(vPdf);\n% %vCdf = vCdf/max(vCdf);\n% vCdf = [vCdf; vMag];\n% vCdf = vCdf';\n\n% CDF theoretically\nvCdf = (1-exp(-fBeta*(vMag-fMc)))./(1-exp(-fBeta*(fMaxMag-2-fMc)));\nvCdf = [vCdf; vMag];\nvCdf = vCdf';\n\n% Use Kagan 2002 approach\n% Sort catalog with ascending magnitude\n[mCatSorted,vIndex] = sort(mCatalog(:,6));\nmCat = mCatalog(vIndex(:,1),:);\n\n% Calulate statistic fD = max_(1==2\n Q2 = diag(diag(A,0)) + diag(diag(A,-n),-n) + diag(diag(A,n),n) ...\n + diag(diag(A,-n-1),-n-1) + diag( diag(A,-1),-1) ...\n + diag(diag(A,n-1),n-1);\n [L2,U2] = lu(Q2);\n if sweeps>=3\n Q3 = triu(A,-1);\n [L3,U3] = lu(Q3);\n if sweeps==4\n Q4 = diag(diag(A,0)) + diag(diag(A,-n),-n) + diag(diag(A,n),n) ...\n + diag(diag(A,n+1),n+1) + diag( diag(A,1),1) ...\n + diag(diag(A,-n+1),-n+1);\n [L4,U4] = lu(Q4);\n else\n L4=sparse(N,N); U4=L4;\n end\n else\n L3=sparse(N,N); U3=L3; L4=L3; U4=L3;\n end\n else\n L2=sparse(N,N); U2=L2; L3=L2; U3=L2; L4=L2; U4=L2;\n end\nelse\n % point smoothers\n if smooth==3,\n % ILU\n [L1,U1]=ilu0(A);\n L2=sparse(size(L1)); U2=L2; L3=L2; U3=L2; L4=L2; U4=L2;\n elseif smooth==2,\n % point Gauss-Seidel\n Q1 = tril(A,0); [L1,U1] = lu(Q1);\n L2=sparse(size(L1)); U2=L2; L3=L2; U3=L2; L4=L2; U4=L2;\n else\n % point damped Jacobi\n omega=8/9; % relaxation factor for damped Jacobi\n Q1 = (1/omega)*spdiags(diag(A),0,n*n,n*n);[L1,U1] = lu(Q1);\n L2=sparse(size(L1)); U2=L2; L3=L2; U3=L2; L4=L2; U4=L2;\n end\nend\nQ = struct('L1',L1,'L2',L2,'L3',L3,'L4',L4, ...\n 'U1',U1,'U2',U2,'U3',U3,'U4',U4); \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/toms866/solvers/mg_ns_smooth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6859954333300106}} {"text": "function Y = pdist(X,s,varargin)\n%PDIST Pairwise distance between observations.\n% Y = PDIST(X) returns a vector Y containing the Euclidean distances\n% between each pair of observations in the M-by-N data matrix X. Rows of\n% X correspond to observations, columns correspond to variables. Y is an\n% (M*(M-1)/2)-by-1 vector, corresponding to the M*(M-1)/2 pairs of\n% observations in X.\n%\n% Y = PDIST(X, DISTANCE) computes Y using DISTANCE. Choices are:\n%\n% 'euclidean' - Euclidean distance\n% 'seuclidean' - Standardized Euclidean distance, each coordinate\n% in the sum of squares is inverse weighted by the\n% sample variance of that coordinate\n% 'cityblock' - City Block distance\n% 'mahalanobis' - Mahalanobis distance\n% 'minkowski' - Minkowski distance with exponent 2\n% 'cosine' - One minus the cosine of the included angle\n% between observations (treated as vectors)\n% 'correlation' - One minus the sample correlation between\n% observatons (treated as sequences of values).\n% 'hamming' - Hamming distance, percentage of coordinates\n% that differ\n% 'jaccard' - One minus the Jaccard coefficient, the\n% percentage of nonzero coordinates that differ\n% function - A distance function specified using @, for\n% example @DISTFUN\n%\n% A distance function must be of the form\n%\n% function D = DISTFUN(XI, XJ, P1, P2, ...),\n%\n% taking as arguments two L-by-N matrices XI and XJ each of which\n% contains rows of X, plus zero or more additional problem-dependent\n% arguments P1, P2, ..., and returning an L-by-1 vector of distances D,\n% whose Kth element is the distance between the observations XI(K,:)\n% and XJ(K,:).\n%\n% Y = PDIST(X, DISTFUN, P1, P2, ...) passes the arguments P1, P2, ...\n% directly to the function DISTFUN.\n%\n% Y = PDIST(X, 'minkowski', P) computes Minkowski distance using the\n% positive scalar exponent P.\n%\n% The output Y is arranged in the order of ((1,2),(1,3),..., (1,M),\n% (2,3),...(2,M),.....(M-1,M)), i.e. the upper right triangle of the full\n% M-by-M distance matrix. To get the distance between the Ith and Jth\n% observations (I < J), either use the formula Y((I-1)*(M-I/2)+J-I), or\n% use the helper function Z = SQUAREFORM(Y), which returns an M-by-M\n% square symmetric matrix, with the (I,J) entry equal to distance between\n% observation I and observation J.\n%\n% Example:\n%\n% X = randn(100, 5); % some random points\n% Y = pdist(X, 'euclidean'); % unweighted distance\n% Wgts = [.1 .3 .3 .2 .1]; % coordinate weights\n% Ywgt = pdist(X, @weucldist, Wgts); % weighted distance\n%\n% function d = weucldist(XI, XJ, W) % weighted euclidean distance\n% d = sqrt((XI-XJ).^2 * W');\n%\n% See also SQUAREFORM, LINKAGE, SILHOUETTE.\n\n% An example of distance for data with missing elements:\n%\n% X = randn(100, 5); % some random points\n% X(unidrnd(prod(size(X)),1,20)) = NaN; % scatter in some NaNs\n% D = pdist(X, @naneucdist);\n%\n% function d = naneucdist(XI, XJ) % euclidean distance, ignoring NaNs\n% sqdx = (XI-XJ).^2;\n% nk = sum(~isnan(sqdx),2); nk(nk == 0) = NaN;\n% d = sqrt(nansum(sqdx')' .* size(XI,2) ./ nk); %correct for missing coords\n\n% Copyright 1993-2002 The MathWorks, Inc.\n% $Revision: 1.15 $\n\nif nargin < 2\n s = 'euc';\n distfun = @distcalc;\n distargs = {s};\nelse\n if ischar(s)\n methods = strvcat('euclidean','seuclidean','cityblock','mahalanobis','minkowski','cosine','correlation','hamming','jaccard');\n i = strmatch(lower(s), methods);\n if length(i) > 1\n error(sprintf('Ambiguous ''DISTANCE'' argument: %s.', s));\n elseif isempty(i)\n % error(sprintf('Unknown ''DISTANCE'' argument: %s.', s));\n distfun = str2func(s);\n distargs = varargin;\n s = 'usr';\n else\n s = lower(methods(i,1:3));\n distfun = @distcalc;\n distargs = {s};\n end\n elseif isa(s, 'function_handle') | isa(s, 'inline')\n distfun = s;\n distargs = varargin;\n s = 'usr';\n else\n error('The ''DISTANCE'' argument must be a string or a function.');\n end\nend\n\n[m, n] = size(X);\nif any(imag(X(:))) & ~isequal(s,'usr')\n error('PDIST does not accept complex inputs.');\nend\n\nswitch s\ncase 'seu' % Standardized Euclidean weights by coordinate variance\n distargs{end+1} = 1 ./ var(X)';\ncase 'mah' % Mahalanobis\n distargs{end+1} = inv(cov(X));\ncase 'min' % Minkowski distance needs a third argument\n if nargin < 3 % use default value for exponent\n distargs{end+1} = 2;\n elseif varargin{1} > 0\n distargs{end+1} = varargin{1}; % get exponent from input args\n else\n error('The exponent for the Minkowski metric must be positive.');\n end\ncase 'cos' % Cosine\n Xnorm = sqrt(sum(X.^2, 2));\n if min(Xnorm) <= eps * max(Xnorm)\n error(['Some points have small relative magnitudes, making them ', ...\n 'effectively zero.\\nEither remove those points, or choose a ', ...\n 'distance other than cosine.'], []);\n end\n X = X ./ Xnorm(:,ones(1,n));\ncase 'cor' % Correlation\n X = X - repmat(mean(X,2),1,n);\n Xnorm = sqrt(sum(X.^2, 2));\n if min(Xnorm) <= eps * max(Xnorm)\n error(['Some points have small relative standard deviations, making ', ...\n 'them effectively constant.\\nEither remove those points, or ', ...\n 'choose a distance other than correlation.'], []);\n end\n X = X ./ Xnorm(:,ones(1,n));\nend\n\nif m < 2\n % Degenerate case, just return an empty of the proper size.\n Y = zeros(1,0);\n return;\nend\n\n% Create (I,J) defining all pairs of points\np = (m-1):-1:2;\nI = zeros(m*(m-1)/2,1);\nI(cumsum([1 p])) = 1;\nI = cumsum(I);\nJ = ones(m*(m-1)/2,1);\nJ(cumsum(p)+1) = 2-p;\nJ(1)=2;\nJ = cumsum(J);\n\n% For large matrices, process blocks of rows as a group\nn = length(I);\nncols = size(X,2);\nblocksize = 1e4; % # of doubles to process as a group\nM = max(1,ceil(blocksize/ncols)); % # of rows to process as a group\nnrem = rem(n,M);\nif nrem==0, nrem = min(M,n); end\n\nY = zeros(1,n);\nii = 1:nrem;\ntry\n Y(ii) = feval(distfun,X(I(ii),:),X(J(ii),:),distargs{:})';\ncatch\n if isa(distfun, 'inline')\n error(['The inline distance function generated the following ', ...\n 'error:\\n%s'], lasterr);\n elseif strfind(lasterr, ...\n sprintf('Undefined function ''%s''', func2str(distfun)))\n error('The distance function ''%s'' was not found.', func2str(distfun));\n else\n error(['The distance function ''%s'' generated the following ', ...\n 'error:\\n%s'], func2str(distfun),lasterr);\n end\nend;\nfor j=nrem+1:M:n\n ii = j:j+M-1;\n try\n Y(ii) = feval(distfun,X(I(ii),:),X(J(ii),:),distargs{:})';\n catch\n if isa(distfun, 'inline')\n error(['The inline distance function generated the following ', ...\n 'error:\\n%s'], lasterr);\n else\n error(['The distance function ''%s'' generated the following', ...\n 'error:\\n%s'], func2str(distfun),lasterr);\n end;\n end;\nend\n\n% ----------------------------------------------\nfunction d = distcalc(XI,XJ,s,arg)\n%DISTCALC Perform distance calculation for PDIST.\nswitch s\ncase 'euc', d = sqrt(sum((XI-XJ).^2,2)); % Euclidean\ncase 'seu', d = sqrt(((XI-XJ).^2) * arg); % Standardized Euclidean\ncase 'cit', d = sum(abs((XI-XJ)),2); % City Block\ncase 'mah', Y = XI - XJ;\n d = sqrt(sum((Y*arg).*Y,2)); % Mahalanobis\ncase 'min', d = sum(abs((XI-XJ)).^arg,2).^(1/arg); % Minkowski\ncase 'cos', d = 1 - sum(XI.*XJ,2); % Cosine\ncase 'cor', d = 1 - sum(XI.*XJ,2); % Correlation\ncase 'ham', d = sum(XI ~= XJ,2) / size(XI,2); % Hamming\ncase 'jac', nz = XI ~= 0 | XJ ~= 0;\n ne = XI ~= XJ;\n d = sum(ne&nz,2) ./ sum(nz,2); % Jaccard\nend", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/Support_functions/pdist1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6859954310597149}} {"text": "function [ortirfmatrix]=irfsim_new(beta,D,n,m,p,k,horizon)\n\n\n\n% [irfmatrix ortirfmatrix]=bear.irfsim(beta,D,n,m,p,k,horizon)\n% computes IRF matrices and orthogonalised IRF matrices\n% inputs: - vector 'beta': vectorised form of VAR coefficients (defined in 1.1.12)\n% - matrix 'D': structural matrix for the OLS model (defined in 2.3.3)\n% - integer 'n': number of endogenous variables in the BVAR model (defined p 7 of technical guide)\n% - integer 'm': number of exogenous variables in the BVAR model (defined p 7 of technical guide)\n% - integer 'p': number of lags included in the model (defined p 7 of technical guide)\n% - integer 'k': number of coefficients to estimate for each equation in the BVAR model (defined p 7 of technical guide)\n% - integer 'horizon': number of IRF periods\n% outputs: - matrix 'irfmatrix': record of the series of irf matrices\n% - matrix 'ortirfmatrix': record of the series of orthogonalised irf matrices\n\n\n\n% first reshape beta to obtain B\nB=reshape(beta,k,n);\n\n% deal with shocks in turn\nfor ii=1:n\n\n\n% create a matrix of zeros of dimension p*n\nY=zeros(p,n);\n% set the value of the last row, column i, equal to 1\nY(p,ii)=1;\n\n\n % repeat the algorithm from period T+1 to period T+h\n for jj=1:horizon-1\n\n % step 1\n % use the function lagx to obtain the matrix temp, containing the endogenous regressors\n temp=bear.lagx(Y,p-1);\n\n % step 2\n % define the vector X\n X=[temp(end,:) zeros(1,m)];\n\n % step 3\n % obtain the predicted value for T+jj\n yp=X*B;\n\n % step 4\n % concatenate yp at the top of Y\n Y=[Y;yp];\n\n % repeat until values are obtained for T+h\n end\n\n% consider 'Y' and trim the (p-1) initial periods: what remains is the series of IRFs for period T to period T+h-1\nY=Y(p:end,:);\n\n\n% record the results in the matrix irfmatrix\n\n % loop over periods\n for jj=1:horizon\n \n % loop over variables\n for kk=1:n\n irfmatrix(kk,ii,jj)=Y(jj,kk);\n end\n\n end\n\n% conduct the same process with shocks in other variables\nend\n\n\n% obtain now orthogonalised IRFs\n% loop over periods\nfor ii=1:horizon\nortirfmatrix(:,:,ii)=irfmatrix(:,:,ii)*D;\nend\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/irfsim_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6859954264512398}} {"text": "function [ f ] = pendulumF( y )\n%pendulumf Pendulum equations.\n\n g = 1;\n m = 1;\n l = 1;\n \n f(1,1) = y(3,:);\n f(2,1) = y(4,:);\n f(3,1) = -y(1,:).*y(5,:)/m;\n f(4,1) = (-y(2,:).*y(5,:)-g)/m;\n f(5,1) = y(1,:).*y(3,:) + y(2,:).*y(4,:);\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/39857-runge-kutta-dae-solver/rungekuttadae_v4/testcase/pendulumF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6859954194367013}} {"text": "function [w, g_sqr] = adagrad(w, g_sqr, grad, opts, lr)\n%ADAGRAD\n% Example AdaGrad solver, for use with CNN_TRAIN and CNN_TRAIN_DAG.\n%\n% Set the initial learning rate for AdaGrad in the options for\n% CNN_TRAIN and CNN_TRAIN_DAG. Note that a learning rate that works for\n% SGD may be inappropriate for AdaGrad; the default is 0.001.\n%\n% If called without any input argument, returns the default options\n% structure.\n%\n% Solver options: (opts.train.solverOpts)\n%\n% `epsilon`:: 1e-10\n% Small additive constant to regularize variance estimate.\n%\n% `rho`:: 1\n% Moving average window for variance update, between 0 and 1 (larger\n% values result in slower/more stable updating). This is similar to\n% RHO in AdaDelta and RMSProp. Standard AdaGrad is obtained with a RHO\n% value of 1 (use total average instead of a moving average).\n%\n% A possibly undesirable effect of standard AdaGrad is that the update\n% will monotonically decrease to 0, until training eventually stops. This\n% is because the AdaGrad update is inversely proportional to the total\n% variance of the gradients seen so far.\n% With RHO smaller than 1, a moving average is used instead. This\n% prevents the final update from monotonically decreasing to 0.\n\n% Copyright (C) 2016 Joao F. Henriques.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nif nargin == 0 % Return the default solver options\n w = struct('epsilon', 1e-10, 'rho', 1) ;\n return ;\nend\n\ng_sqr = g_sqr * opts.rho + grad.^2 ;\n\nw = w - lr * grad ./ (sqrt(g_sqr) + opts.epsilon) ;\n", "meta": {"author": "phoenix104104", "repo": "LapSRN", "sha": "95154bba82a3aab9bdaec8e0eedd4187babc5ed2", "save_path": "github-repos/MATLAB/phoenix104104-LapSRN", "path": "github-repos/MATLAB/phoenix104104-LapSRN/LapSRN-95154bba82a3aab9bdaec8e0eedd4187babc5ed2/matconvnet/examples/+solver/adagrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6859827005688574}} {"text": "function result = ball_f1_nd ( func, n, xc, r )\n\n%*****************************************************************************80\n%\n%% BALL_F1_ND approximates an integral inside a ball in ND.\n%\n% Integration region:\n%\n% Points X(1:N) such that:\n%\n% Sum ( X(1:N) - XC(1:N) )**2 <= R**2.\n%\n% Discussion:\n%\n% An (N+1)*2**N point 5-th degree formula is used, Stroud number SN:5-6.\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% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Arthur H Stroud,\n% Approximate Calculation of Multiple Integrals,\n% Prentice Hall, 1971.\n%\n% Parameters:\n%\n% Input, external FUNC, the name of the user supplied\n% function which evaluates F at the N-vector X, of the form\n% function value = func ( n, x )\n%\n% Input, integer N, the dimension of the space.\n%\n% Input, real XC(N), the center of the ball.\n%\n% Input, real R, the radius of the ball.\n%\n% Output, real RESULT, the approximate integral of the function.\n%\n if ( r == 0.0E+00 )\n result = 0.0E+00;\n return\n end\n\n u2 = ( 1.0E+00 - 2.0E+00 * sqrt ( 1.0E+00 / ( n + 4 ) ) ) / ( n + 2 );\n u = sqrt ( u2 );\n x(1:n) = xc(1:n) - r * u;\n\n w = 1.0E+00 / ( ( n + 1 ) * 2^n );\n\n quad = 0.0E+00;\n ihi = 2^n;\n\n for i = 1 : ihi\n\n itemp = i - 1;\n\n for j = 1 : n\n\n u = ( xc(j) - x(j) ) / r;\n\n if ( mod ( itemp, 2 ) == 1 )\n x(j) = xc(j) - abs ( x(j) - xc(j) );\n else\n x(j) = xc(j) + abs ( x(j) - xc(j) );\n end\n\n itemp = floor ( itemp / 2 );\n\n end\n\n quad = quad + w * feval ( func, n, x );\n\n end\n\n temp = sqrt ( n + 4 );\n\n t = sqrt ( 2.0E+00 * ( n + 1 ) / ( n + 2 ) ) / ( n * temp );\n\n y = ( 1.0E+00 + 2.0E+00 / ( n * temp ) ) / ( n + 2 );\n v = sqrt ( y - t );\n u = sqrt ( y + ( n - 1 ) * t );\n\n khi = 2^n;\n\n for i = 1 : n\n\n x(1:n) = xc(1:n) - r * v;\n\n x(i) = xc(i) - r * u;\n\n for k = 1 : khi\n\n ktemp = k - 1;\n\n for j = 1 : n\n\n if ( mod ( ktemp, 2 ) == 1 )\n x(j) = xc(j) - abs ( x(j) - xc(j) );\n else\n x(j) = xc(j) + abs ( x(j) - xc(j) );\n end\n\n ktemp = floor ( ktemp / 2 );\n\n end\n\n quad = quad + w * feval ( func, n, x );\n\n end\n\n x(i) = xc(i) - r * v;\n\n end\n\n volume = ball_volume_nd ( n, r );\n result = quad * volume;\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_f1_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024554, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.6859747440799066}} {"text": "function F = spm_Ncdf_jdw(x,u,v)\n% Cumulative Distribution Function (CDF) for univariate Normal distributions: J.D. Williams aproximation\n% FORMAT F = spm_Ncdf_jdw(x,u,v)\n%\n% x - ordinates\n% u - mean [Defaults to 0]\n% v - variance (v>0) [Defaults to 1]\n% F - pdf of N(u,v) at x (Lower tail probability)\n%__________________________________________________________________________\n%\n% spm_Ncdf implements the Cumulative Distribution Function (CDF) for\n% the Normal (Gaussian) family of distributions.\n%\n% References:\n%--------------------------------------------------------------------------\n% An Approximation to the Probability Integral\n% J. D. Williams \n% The Annals of Mathematical Statistics, Vol. 17, No. 3. (Sep., 1946), pp.\n% 363-365. \n%\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_Ncdf_jdw.m 4836 2012-08-10 15:55:21Z karl $\n\n\n%-Format arguments\n%--------------------------------------------------------------------------\nif nargin < 3, v = 1; end\nif nargin < 2, u = 0; end\n\n%-Approximate integral\n%--------------------------------------------------------------------------\nx = (x - u)./sqrt(abs(v));\nF = sqrt(1 - exp(-(2/pi)*x.^2))/2;\ni = x < 0;\nF(i) = -F(i);\nF = F + 1/2;", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_Ncdf_jdw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552536, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.685973182327181}} {"text": "function res = backtest(rex,Nh);\n% PURPOSE: Backtesting of temporal disaggregation. \n% -----------------------------------------------------------------------\n% SYNTAX: res = backtest(rex,Nh);\n% -----------------------------------------------------------------------\n% OUTPUT: res: a structure with...\n% rex : reference structure\n% yh : recursive estimations from FROM T=N+Nh T=N\n% yrev : revision as %, compared with final (full info) estimation\n% -----------------------------------------------------------------------\n% INPUT: rex: a structure generated by chowlin(), fernandez(), litterman()\n% or ssc()\n% Nh: 1x1 --> number of low-freq. to compute revisions\n% -----------------------------------------------------------------------\n% LIBRARY: chowlin, fernandez, litterman, ssc\n% -----------------------------------------------------------------------\n% NOTE: Revision of estimates when adding low-frequency data from T=N-Nh to\n% T=N\n\n% written by:\n% Enrique M. Quilis\n% Macroeconomic Research Department\n% Ministry of Economy and Competitiveness\n% \n\n% Version 2.1 [May 2008]\n\nt0 = clock;\n\n% ------------------------------------------------------------\n% Loading the structure\n\nY \t\t= rex.Y;\nx \t\t= rex.x(:,2:end); %Excluding intercept\nta \t = rex.ta;\nsc \t = rex.sc;\ntype \t= rex.type;\nopC = rex.opC;\n \n% ------------------------------------------------------------\n% Size of the problem\n\nN = rex.N; % Size of low-frequency input\nn = rex.n; % Size of high-frequency input\np = rex.p - 1; % Number of regressors (without intercept)\n\n% ------------------------------------------------------------\n% BACKTEST: REVISIONS OF ESTIMATES, AS Y EXPANDS (x all sample)\n% ------------------------------------------------------------\n\nx = x(1:sc*N,:);\nyh = NaN * ones(n,Nh+1);\nfor h=Nh:-1:0\n Yh = Y(1:end-h);\n % Calling temporal disaggregation function\n switch rex.meth\n case {'Chow-Lin'}\n rl = rex.rl;\n res1 = chowlin(Yh,x,ta,sc,type,opC,rl);\n case {'Fernandez'}\n res1 = fernandez(Yh,x,ta,sc,opC);\n case {'Litterman'}\n rl = rex.rl;\n res1 = litterman(Yh,x,ta,sc,type,opC,rl);\n case {'Santos Silva-Cardoso'}\n rl = rex.rl;\n res1 = ssc(Yh,x,ta,sc,type,opC,rl);\n otherwise\n error ('*** BACKTESTING IS NOT AVAILABLE FOR THIS METHOD ***');\n end\n % Generating yh\n yh(:,Nh-h+1) = res1.y;\nend\n\n% Computation of revisons as percentages\nyrev = (yh - kron(ones(1,Nh+1),yh(:,end))) ./ yh;\n\n% -----------------------------------------------------------\n% Loading the structure\n% -----------------------------------------------------------\n\n% Reference structure\nres.rex = rex;\n% Sequence of estimates\nres.yh = yh;\n% Revisions of stimates\nres.yrev = yrev;\n% Elapsed time\nres.et = etime(clock,t0);\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/39770-temporal-disaggregation-library/backtest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6859707439749905}} {"text": "function varargout = transformPoint(varargin)\n%TRANSFORMPOINT Apply an affine transform to a point or a point set.\n%\n% PT2 = transformPoint(PT1, TRANSFO);\n% Returns the result of the transformation TRANSFO applied to the point\n% PT1. PT1 has the form [xp yp], and TRANSFO is either a 2-by-2, a\n% 2-by-3, or a 3-by-3 matrix, \n%\n% Format of TRANSFO can be one of :\n% [a b] , [a b c] , or [a b c]\n% [d e] [d e f] [d e f]\n% [0 0 1]\n%\n% PT2 = transformPoint(PT1, TRANSFO);\n% Also works when PTA is a N-by-2 array representing point coordinates.\n% In this case, the result PT2 has the same size as PT1.\n%\n% [X2, Y2] = transformPoint(X1, Y1, TRANS);\n% Also works when PX1 and PY1 are two arrays the same size. The function\n% transforms each pair (PX1, PY1), and returns the result in (X2, Y2),\n% which has the same size as (PX1 PY1). \n%\n%\n% See also \n% points2d, transforms2d, translation, rotation\n%\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2004-04-06\n% Copyright 2004-2022 INRA - TPV URPOI - BIA IMASTE\n\n% parse input arguments\nif length(varargin) == 2\n var = varargin{1};\n px = var(:,1);\n py = var(:,2);\n trans = varargin{2};\nelseif length(varargin) == 3\n px = varargin{1};\n py = varargin{2};\n trans = varargin{3};\nelse\n error('wrong number of arguments in \"transformPoint\"');\nend\n\n\n% apply linear part of the transform\npx2 = px * trans(1,1) + py * trans(1,2);\npy2 = px * trans(2,1) + py * trans(2,2);\n\n% add translation vector, if exist\nif size(trans, 2) > 2\n px2 = px2 + trans(1,3);\n py2 = py2 + trans(2,3);\nend\n\n% format output arguments\nif nargout < 2\n varargout{1} = [px2 py2];\nelseif nargout\n varargout{1} = px2;\n varargout{2} = py2;\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/geom2d/transformPoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6859707430195282}} {"text": "function [mu, muw]= ViscosityCO2Water(T, p, x_CO2)\n% This function calculates the viscosity of the pure water, brine, and\n% water-CO2, and brine-CO2 systems\n% p is in Pa, T in K, x_CO2 is the mole fraction of CO2, mu in Pa.s\n% Written by Ali A. Eftekhari at TU Delft\n% See the license file\nMwater = 0.0180153; % kg/mol\n% MCO2 = 0.04401; % kg/mol\n\nP = p/1e6; % convert Pa to MPa\nm_CO2 = DuanSun(T, p, 0); % CO2 equilibrium molality (mol CO2/kg water)\nx_CO2_eq = m_CO2/(m_CO2+1/Mwater);\nmuw = IAPWS_IF97('mu_pT', P, T); % pure water viscosity in Pa.s\nvis_ratio = 1+(-4.069e-3*(T-273.15)+0.2531)*x_CO2/x_CO2_eq;\nmu = muw*vis_ratio;\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/PhysicalProperties/ViscosityCO2Water.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6859577373447046}} {"text": "%Test script to run SVP for matrix completion using uniformly sampled random matrices\n%Written by: Prateek Jain (pjain@cs.utexas.edu) and Raghu Meka (meka@cs.utexas.edu)\n%Last updated: October, 2009\n\nm = 5000;\nn = 2000;\nk = 10; %rank of the optimal matrix\np = 0.2; %fraction of known entries\nparams.tol=1e-3;\nparams.vtol=1e-4;\nparams.mxitr=100;\nparams.verbosity=1;\n\nM = randn(m,k)*randn(k,n); %Generate the underlying matrix\nrandom_permutation=randperm(m*n);\nOmega=random_permutation(1:p*m*n)'; %Generate samples with uniform density p\nOmega=sort(Omega);\n\nfprintf('Running SVP with m=%d, n=%d, p=%f...\\n',m,n,p);\nt=cputime;\n[U,S,V,num_iter] = svp(Omega, M(Omega), m, n, k, params); %Run SVP\nt = cputime-t;\nfprintf('SVP finished with RMSE=%f in time t=%f\\n',norm(M-U*diag(S)*V','fro')/sqrt(length(Omega)),t);\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/mc/SVP/test_svp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6859292746088951}} {"text": "function [varargout]=rigidTransformationMatrixDirect(V1,V2)\n\n%%\n%Force input to 3D\nif size(V1,2)==2 \n V1(:,3)=0; \nend\n\nif size(V2,2)==2\n V2(:,3)=0; \nend\n\n[Q]=kabschRotationMatrix(V1,V2);\n\nV1_m=mean(V1,1);\nV2_m=mean(V2,1);\n\nT1=eye(4,4);\nT1(1:3,end)=V2_m(:);\n\nR=eye(4,4);\nR(1:3,1:3)=Q;\n\nT2=eye(4,4);\nT2(1:3,end)=-V1_m;\n\nT=T1*R*T2;\n\nvarargout{1}=T;\nvarargout{2}=R(1:3,1:3);\n\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/rigidTransformationMatrixDirect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6859292695987973}} {"text": "function plotkde(X, sigma2)\n% Plot 2d kernel density.\n% Written by Mo Chen (sth4nth@gmail.com).\nif nargin < 2\n sigma2 = 1e-1;\nend\nlevel = 64;\nn = 256;\n\nX = standardize(X);\n\nspread(X);\nx_range = xlim;\ny_range = ylim;\n\nx = linspace(x_range(1),x_range(2), n);\ny = linspace(y_range(2),y_range(1), n);\n\n[a,b] = meshgrid(x,y);\n\nz = exp(logkdepdf([a(:)';b(:)'],X,sigma2));\n\nz = z-min(z);\nz = floor(z/max(z)*(level-1));\n\nfigure;\nimage(reshape(z,n,n));\ncolormap(jet(level));\nset(gca, 'XTick', [1 256]);\nset(gca, 'XTickLabel', [min(x) max(x)]);\nset(gca, 'YTick', [1 256]);\nset(gca, 'YTickLabel', [min(y) max(y)]);\naxis off\n", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/common/plotkde.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347124, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.685929260258502}} {"text": "function boolVal=linTargetIsUntrackable(targetParams,PD,lambda,AbsTol,RelTol,maxIter)\n%%LINTARGETISUNTRACKABLE Assuming that an asymptotic inoovation covariance\n% is available or that a target follows a particular specified\n% linear dynamic model (e.g. position, velocity, and\n% acceleration, and it could have correlation terms like a Gauss-\n% Markov model) with known process noise covariance and Cartesian\n% measurement covariance, and assuming that a probability of\n% detection is known, determine whether a target is untrackable.\n% A target is deemed untrackable if the cost function used in a\n% multiple hypothesis tracker (MHT) is always greater than or\n% equal to the null hypothesis than for any track hypothesis\n% when given asymptotic track accuracy parameters. If a track is\n% untrackable, even an MHT of infinite length would not be able\n% to track the target. This assumes Cartesian measurements. The\n% use of range rate, complex target amplitude, micro-Doppler and\n% other information could potentially render untrackable targets\n% trackable.\n%\n%INPUTS: targetParams This can be one of two types of inputs. If an\n% asymptotic innovation covariance matrix is known, then this is\n% the innovation covariance matrix. Otherwise, this is a structure\n% holding parameters for a linear system so that an asymptotic\n% innovation covariance matrix can be computed. The members of the\n% structure are:\n% H The zDim X xDim measurement matrix such that H*x+w is the\n% measurement, where x is the state and w is zero-mean Gaussian\n% noise with covariance matrix R.\n% F The xDim X xDim state transition matrix The state at\n% discrete-time k+1 is modeled as F times the state at time k\n% plus zero- mean Gaussian process noise with covariance matrix\n% Q.\n% R The zDim X zDim measurement covariance matrix.\n% Q The xDim X xDim process noise covariance matrix. This can\n% not be a singular matrix.\n% PD The optional detection probability of the target at each scan.\n% PD should not be 1.\n% lambda The false alarm density in Cartesian coordinates. For example,\n% this might be 1e-8 false alarms per unit volume in cubic meters.\n% RelTol The maximum relative error tolerance allowed when computing the\n% asymptotic predictive covariance matrix. This is a positive\n% scalar. If omitted or an empty matrix is passed, the default\n% value of 1e-13 is used. This value is only used if targetParams\n% is a structure. \n% AbsTol The absolute error tolerance allowed, a positive scalar. When\n% computing the asymptotic predictive covariance matrix. This is a\n% positive scalar. If omitted or an empty matrix is passed, the\n% default value of 1e-10 is used. This value is only used if\n% targetParams is a structure. \n% maxIter An optional integer specifying the maximum number of iterations\n% to use when cmputing the asymptotic predictive covariance\n% matrix. By default, if omitted, this is 5000. This value is only\n% used if targetParams is a structure. \n%\n%As discussed in Chapter 7.5 of [1], track oriented MHTs declare target\n%existence based on finite sums of log-likelihood ratios. These ratios are\n%typically made into dimensionless score functions as in Chapter 7.5 of [1]\n%and in [2]. For the probability that a measurement z is from a particular\n%target, the contribution to the score function is f(z)*PD/lambda, where\n%f(z) is the likelihood of the measurement conditioned on the predicted\n%state estimate. The null hypothesis receives a score of 1-PD. If the null\n%hypothesis is always greater than or equal to the track association\n%hypothesis then a target is untrackable.\n%\n%Given a Cartesian measurement model (z=H*x+w where x is the target state,\n%w is measurement noise with covariance matrix R and H is the measurement\n%matrix) and assuming a linear dynamic model (xpredicted=F*xPrior+v where v\n%is noise with covariance matrix Q) where the state transition matrix F and\n%the process noise covariance matrix Q are constant (implying a uniform\n%revisit rate) as well as having a known detection probability of PD, one\n%determine an asymptotic lower bound on the estimation accuracy of a\n%predicted state measurement using the RiccatiPredNoClutter function. Given\n%PPred, a lower bound on the state precision covariance, the score function\n%contribution for a target-originated measurement is maximum when the\n%predicted measurement equals the measurement value. From Chapter 7.5.3 of\n%[1], for a linear measurement model, this is\n%PD/(lambda*sqrt(det(2*pi*SPred))) where SPred is the innovation covariance\n%matrix, which as given in the derivation of the Kalman filter in Chapter 5\n%of [3] is H*PPred*H'+R. Thus, this function determines whether this\n%maximum score for a track-originated measurement is greater than the\n%alternative (1-PD). If not, then the target is untrackable.\n%\n%The trackability bound here can be considered something of a \"stealth\"\n%bound, because for a fixed false alarm level in a system, a target can\n%become untrackable either by lowing its detection probability sufficiently\n%(becoming \"stealth\") and/or by increasing its maneuverability, which,\n%here, is reflected in increasign the process noise covariance.\n%\n%Note that if the innovation covariance matrix is passed for targetParams,\n%this function just uses its size and determiniant.\n%\n%EXAMPLE:\n% T=1;\n% targetParams=[];\n% targetParams.F=FPolyKal(T,6,1);\n% q0=1;\n% targetParams.Q=QPolyKal(T,6,1,q0);\n% targetParams.R=diag([10;10;10]);\n% targetParams.H=[1,0,0,0,0,0;\n% 0,1,0,0,0,0;\n% 0,0,1,0,0,0];\n% PD=0.5;\n% lambda=1e-8;\n% boolVal=linTargetIsUntrackable(targetParams,PD,lambda)\n% %The above example is trackable (boolVal=false). However, if the\n% %detection probability decreases/ the false alarm rate increases, then\n% %one gets an untrackable target. Consider:\n% PD=0.1;\n% lambda=1e-6;\n% boolVal1=linTargetIsUntrackable(targetParams,PD,lambda)\n%\n%REFERENCES:\n%[1] Y. Bar-Shalom, P. K. Willett, and X. Tian, Tracking and Data Fusion.\n% Storrs, CT: YBS Publishing, 2011.\n%[2] Y. Bar-Shalom, S. S. Blackman, and R. J. Fitzgerald, \"Dimensionless\n% score function for multiple hypothesis tracking,\" IEEE Transactions on\n% Aerospace and Electronic Systems, vol. 43, no. 1, pp. 392-400, Jan.\n% 2007.\n%[3] Y. Bar-Shalom, X. R. Li, and T. Kirubarajan, Estimation with\n% Applications to Tracking and Navigation. New York: John Wiley and\n% Sons, Inc, 2001.\n%\n%January 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<4||isempty(AbsTol))\n AbsTol=1e-13;\nend\n\nif(nargin<5||isempty(RelTol))\n RelTol=1e-10;\nend\n\nif(nargin<6||isempty(maxIter))\n maxIter=5000; \nend\n\nif(isstruct(targetParams))\n H=targetParams.H;\n F=targetParams.F;\n R=targetParams.R;\n Q=targetParams.Q;\n m=size(H,1);\n\n %Asymptotic predicted state covariance matrix with given PD assuming\n %completely correct association hypotheses.\n PPred=RiccatiPredNoClutter(H,F,R,Q,PD,AbsTol,RelTol,maxIter);\n\n %Asymptotic innovation covariance matrix.\n detSPred=det(H*PPred*H'+R);\nelse\n S=targetParams;\n m=size(S,1);\n detSPred=det(S);\nend\n\nmaxIsTargetScore=PD/(lambda*sqrt((2*pi)^m*detSPred));\nmissedDetectScore=1-PD;\n\nboolVal=maxIsTargetScore<=missedDetectScore;\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/Dynamic_Estimation/Performance_Prediction/linTargetIsUntrackable.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6859110698542714}} {"text": "% SB1_EXAMPLECLASSIFY Example of Sparse Bayes Classification\n%\n% SB1_EXAMPLECLASSIFY(N,KERNEL,WIDTH,MAXITS)\n%\n% INPUT ARGUMENTS:\n%\n% N Number of training points (up to 250)\n% KERNEL Kernel function to use (see SB1_KERNELFUNCTION)\n% WIDTH Kernel length scale parameter\n% MAXITS Maximum number of iterations to run for\n% \n% NOTES: The data is taken from the book \"Pattern Recognition for\n% Neural Networks\" (Ripley). Running SB1_EXAMPLECLASSIFY with\n% no arguments will result in sensible defaults.\n%\n%\n% Copyright 2009 :: Michael E. Tipping\n%\n% This file is part of the SPARSEBAYES baseline implementation (V1.10)\n%\n% Contact the author: m a i l [at] m i k e t i p p i n g . c o m\n%\nfunction SB1_ExampleClassify(N,kernel_,width,maxIts)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Set verbosity of output (0 to 4)\nsetEnvironment('Diagnostic','verbosity',3);\n% Set file ID to write to (1 = stdout)\nsetEnvironment('Diagnostic','fid',1);\n\n%\n% Set default values for data and model\n% \nuseBias\t= true;\n%\nrand('state',1)\nif nargin==0\n % Some acceptable defaults\n % \n N\t\t= 100;\n kernel_\t= 'gauss';\n width\t\t= 0.5;\n maxIts\t= 1000;\nend\nmonIts\t\t= round(maxIts/10);\nN\t\t= min([250 N]); % training set has fixed size of 250\nNt\t\t= 1000;\n%\n% Load Ripley's synthetic training data (see reference in doc)\n% \nload synth.tr\nsynth\t= synth(randperm(size(synth,1)),:);\nX\t= synth(1:N,1:2);\nt\t= synth(1:N,3);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nCOL_data1\t= 'k';\nCOL_data2\t= 0.75*[0 1 0];\nCOL_boundary50\t= 'r';\nCOL_boundary75\t= 0.5*ones(1,3);\nCOL_rv\t\t= 'r';\n\n%\n% Plot the training data\n% \nfigure(1)\nwhitebg(1,'w')\nclf\nh_c1\t= plot(X(t==0,1),X(t==0,2),'.','MarkerSize',18,'Color',COL_data1);\nhold on\nh_c2\t= plot(X(t==1,1),X(t==1,2),'.','MarkerSize',18,'Color',COL_data2);\nbox\t= 1.1*[min(X(:,1)) max(X(:,1)) min(X(:,2)) max(X(:,2))];\naxis(box)\nset(gca,'FontSize',12)\ndrawnow\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\n% Set up initial hyperparameters - precise settings should not be critical\n% \ninitAlpha\t= (1/N)^2;\n% Set beta to zero for classification\ninitBeta\t= 0;\t\n%\n% \"Train\" a sparse Bayes kernel-based model (relevance vector machine)\n% \n[weights, used, bias, marginal, alpha, beta, gamma] = ...\n SB1_RVM(X,t,initAlpha,initBeta,kernel_,width,useBias,maxIts,monIts);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\n% Load Ripley's test set\n% \nload synth.te\nsynth\t= synth(randperm(size(synth,1)),:);\nXtest\t= synth(1:Nt,1:2);\nttest\t= synth(1:Nt,3);\n%\n% Compute RVM over test data and calculate error\n% \nPHI\t= SB1_KernelFunction(Xtest,X(used,:),kernel_,width);\ny_rvm\t= PHI*weights + bias;\nerrs\t= sum(y_rvm(ttest==0)>0) + sum(y_rvm(ttest==1)<=0);\nSB1_Diagnostic(1,'RVM CLASSIFICATION test error: %.2f%%\\n', errs/Nt*100)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\n% Visualise the results over a grid\n% \ngsteps\t\t= 50;\nrange1\t\t= box(1):(box(2)-box(1))/(gsteps-1):box(2);\nrange2\t\t= box(3):(box(4)-box(3))/(gsteps-1):box(4);\n[grid1 grid2]\t= meshgrid(range1,range2);\nXgrid\t\t= [grid1(:) grid2(:)];\nsize(Xgrid)\n%\n% Evaluate RVM\n% \nPHI\t\t= SB1_KernelFunction(Xgrid,X(used,:),kernel_,width);\ny_grid\t\t= PHI*weights + bias;\n\n% apply sigmoid for probabilities\np_grid\t\t= 1./(1+exp(-y_grid)); \n\n%\n% Show decision boundary (p=0.5) and illustrate p=0.25 and 0.75\n% \n[c,h05]\t\t= ...\n contour(range1,range2,reshape(p_grid,size(grid1)),[0.5],'-');\n[c,h075]\t= ...\n contour(range1,range2,reshape(p_grid,size(grid1)),[0.25 0.75],'--');\nset(h05, 'Color',COL_boundary50,'LineWidth',3);\nset(h075,'Color',COL_boundary75,'LineWidth',2);\n%\n% Show relevance vectors\n% \nh_rv\t= plot(X(used,1),X(used,2),'o','LineWidth',2,'MarkerSize',10,...\n\t 'Color',COL_rv);\n%\nlegend([h_c1 h_c2 h05 h075(1) h_rv],...\n 'Class 1','Class 2','Decision boundary','p=0.25/0.75','RVs',...\n 'Location','NorthWest')\n%\nhold off\ntitle('RVM Classification of Ripley''s synthetic data','FontSize',14)\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/toolboxes/rvmbox/SB1_ExampleClassify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6859110554339956}} {"text": "%[ P, inls ] = ht_simple_ransac_p3p( u, X, rthr, maxiter )\n%u: 3 x n image points\n%X: 3 x n 3D points\n%rthr: inlier threshold\n%maxiter: default=1000\n\nfunction [ P, inls ] = ht_simple_ransac_p3p( u, X, rthr, max_iter )\nif nargin < 4\n max_iter = 1000;\nend\n\n%initialization\nu = bsxfun(@rdivide, u, sqrt(sum(u.^2, 1)));\nNpts = size(u, 2);\nrthr = cos(rthr);\nmax_inlsnum = 3;\nno_iter = 0;\nP = [];\ninls = false(1, Npts);\n%ransac\nwhile no_iter < max_iter\n no_iter = no_iter + 1;\n \n idx = randperm(Npts, 3);\n P_cand = P3PSolver([u(:, idx); X(:, idx)]);\n [inls_cand, inls_cand_num] = calculate_inls_angular(P_cand, u, X, rthr);\n if length(P_cand) > 1\n [inls_cand_num, inls_cand_idx] = max(inls_cand_num);\n inls_cand = inls_cand{inls_cand_idx};\n P_cand = P_cand{inls_cand_idx};\n else\n inls_cand_num = inls_cand_num(1);\n inls_cand = inls_cand{1};\n P_cand = P_cand{1};\n end\n \n \n if inls_cand_num >= max_inlsnum\n max_inlsnum = inls_cand_num;\n P = P_cand;\n inls = inls_cand;\n max_iter = min([max_iter, nsamples(max_inlsnum, Npts, 3, 0.95)]);\n end\n \nend\n\n\nend\n\n\nfunction [SampleCnt, q] = nsamples(ni, ptNum, pf, conf)\n q = prod (((ni-pf+1) : ni) ./ ((ptNum-pf+1) : ptNum));\n if q < eps\n SampleCnt = Inf;\n else\n % SampleCnt = log(1 - conf) / log(1 - q);\n if q > conf\n SampleCnt = 1;\n else\n SampleCnt = log(1 - conf) / log(1 - q);\n end\n end\nend\n\nfunction [inls, inls_num] = calculate_inls_angular(Pcand, u, X, rthr)\n inls = cell(1, length(Pcand));\n inls_num = zeros(1, length(Pcand));\n for ii = 1:1:length(Pcand)\n X_reproj = Pcand{ii} * [X; ones(1, size(X, 2))];\n X_reproj = bsxfun(@rdivide, X_reproj, sqrt(sum(X_reproj.^2, 1)));\n\n res = sum(u .* X_reproj, 1);\n inls{ii} = res > rthr;\n inls_num(ii) = sum(inls{ii});\n end\n \nend\n", "meta": {"author": "HajimeTaira", "repo": "InLoc_demo", "sha": "b4c42de09d288f35e65ec0156608c704d6176b4f", "save_path": "github-repos/MATLAB/HajimeTaira-InLoc_demo", "path": "github-repos/MATLAB/HajimeTaira-InLoc_demo/InLoc_demo-b4c42de09d288f35e65ec0156608c704d6176b4f/functions/ht_pnp_function/ht_simple_ransac_p3p.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6859110532849962}} {"text": "function raeq = eqxra (tjd, k)\n\n% this function computes the intermediate right ascension\n% of the equinox at julian date tjd, using an analytical expression\n% for the accumulated precession in right ascension. for the\n% true equinox the result is the equation of the origins.\n\n% input\n\n% tjd = tdb julian date\n\n% k = equinox selection code\n\n% set k = 0 for mean equinox\n% set k = 1 for true equinox (equation of the origins)\n\n% output\n\n% raeq = intermediate right ascension of the equinox, in hours (+ or -)\n\n% NOTE: this function computes the accumulated precession in right\n% ascension using the analytic equation in capitaine et al. (2003),\n% astronomy and astrophysics 412, 567-586, eq. (42).\n\n% ported from NOVAS 3.0\n\n%%%%%%%%%%%%%%%%%%%%%%%\n\n% t0 = tdb julian date of epoch j2000.0 (tt)\n\nt0 = 2451545.0d0;\n\nt = (tjd - t0) / 36525.0d0;\n\n% for the true equinox, obtain the equation of the equinoxes in time seconds\n\nif (k == 1)\n \n [a, a, ee, a, a] = etilt (tjd);\n \n eqeq = ee;\n \nelse\n \n eqeq = 0.0d0;\n \nend\n\n% precession in ra in arcseconds taken from capitaine et al. (2003),\n% astronomy and astrophysics 412, 567-586, eq. (42)\n\nprecra = 0.014506d0 + ...\n (((( -0.0000000368d0 * t ...\n - 0.000029956d0) * t ...\n - 0.00000044d0) * t ...\n + 1.3915817d0) * t ...\n + 4612.156534d0) * t;\n\nraeq = -(precra / 15.0d0 + eqeq) / 3600.0d0;\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/39846-a-matlab-script-for-calculating-greenwich-sidereal-time-with-novas/eqxra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6858949062386341}} {"text": "function transm = transformmatrix(s,r,t)\n% *** Homogeneous transformation matrix ***\n% Function transformmatrix returns transformation matrix from object to image space.\n%\n% transm = transformmatrix (s,r,t)\n%\n% inputs,\n% s = Zoom factor\n% r = Rotation vector (rotx,roty,rotz)\n% t = Translation Vector [x,y,z]\n%\n% transm = Rotation Matrix\n%\n\nS=[s 0 0 0;\n 0 s 0 0;\n 0 0 s 0;\n 0 0 0 1];\n\nRx=[1 0 0 0;\n 0 cos(r(1)) -sin(r(1)) 0;\n 0 sin(r(1)) cos(r(1)) 0;\n 0 0 0 1];\n\nRy=[cos(r(2)) 0 sin(r(2)) 0;\n 0 1 0 0;\n -sin(r(2)) 0 cos(r(2)) 0;\n 0 0 0 1];\n\nRz=[cos(r(3)) -sin(r(3)) 0 0;\n sin(r(3)) cos(r(3)) 0 0;\n 0 0 1 0;\n 0 0 0 1];\n\nR=Rx*Ry*Rz;\n\nT=[1 0 0 t(1);\n 0 1 0 t(2);\n 0 0 1 t(3);\n 0 0 0 1];\n\ntransm = S*R*T;", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/meshTools/renderpatch_version0/transformmatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6858949033955922}} {"text": "function Cct=clg2cct(Clg,lat,lon)\n% CLG2CCT Convert local geodetic covariance matrix to CT.\n% Vectorized. Requires rotlg2ct. See also CCT2CLG.\n% Version: 2011-04-05\n% Useage: Cct=clg2cct(Clg,lat,lon)\n% Input: Clg - LG covariance matrix\n% lat - vector of station latitudes (rad)\n% lon - vector of station longitudes (rad)\n% Output: Cct - CT covariance matrix\n\n% Copyright (c) 2011, Michael R. Craymer\n% All rights reserved.\n% Email: mike@craymer.com\n\nn=length(lat);\nif (n*3 ~= max(size(Clg)) )\n error('Size of lat,lon does not match size of Clg');\nend\n\nfor i=1:n\n sinlat=sin(lat(i));\n coslat=cos(lat(i));\n sinlon=sin(lon(i));\n coslon=cos(lon(i));\n Ji=rotlg2ct(lat(i),lon(i));\n indi=(i-1)*3+[1:3];\n for j=1:n\n sinlat=sin(lat(j));\n coslat=cos(lat(j));\n sinlon=sin(lon(j));\n coslon=cos(lon(j));\n Jj=rotlg2ct(lat(j),lon(j));\n indj=(j-1)*3+[1:3];\n Cct(indi,indj)=Ji*Clg(indi,indj)*Jj';\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/15285-geodetic-toolbox/geodetic/clg2cct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6858949005525503}} {"text": "function [fx,fy,ft] = computeDerivatives2(im1,im2)\n% \n% function [fx,fy,fz] = computeDerivatives2(im1,im2)\n%\n% im1 and im2 are images\n%\n% [fx,fy,ft] are images, derivatives of the input images\n\nfilter = [0.03504 0.24878 0.43234 0.24878 0.03504];\ndfilter = [0.10689 0.28461 0.0 -0.28461 -0.10689];\n\ndx1 = conv2sep(im1,dfilter,filter,'valid');\ndy1 = conv2sep(im1,filter,dfilter,'valid');\nblur1 = conv2sep(im1,filter,filter,'valid');\ndx2 = conv2sep(im2,dfilter,filter,'valid');\ndy2 = conv2sep(im2,filter,dfilter,'valid');\nblur2 = conv2sep(im2,filter,filter,'valid');\n\nfx=(dx1+dx2)/2;\nfy=(dy1+dy2)/2;\nft=(blur2-blur1);\n\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/computeDerivatives2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6858948980227738}} {"text": "% 15.7.02\n%\n% Unscented Kalman Filter (UKF) applied to FitzHugh-Nagumo neuron dynamics. \n% Voltage observed, currents and inputs estimated.\n% \n% FitzHughNagumo() is the main program and calls the other programs.\n% \n% A detailed description is provided in\n% H.U. Voss, J. Timmer & J. Kurths, Nonlinear dynamical system identification from uncertain and indirect measurements, Int. J. Bifurcation and Chaos 14, 1905-1933 (2004).\n% I will be happy to email this paper on request. It contains a tutorial about the estimation of hidden states and unscented Kalman filtering.\n%\n% For commercial use and questions, please contact me.\n% \n% ++++++++++++++++++++++++++++++++++++++++++++++\n% Henning U. Voss, Ph.D.\n% Associate Professor of Physics in Radiology\n% Citigroup Biomedical Imaging Center\n% Weill Medical College of Cornell University\n% 516 E 72nd Street\n% New York, NY 10021\n% Tel. 001-212 746-5216, Fax. 001-212 746-6681\n% Email: hev2006@med.cornell.edu\n% ++++++++++++++++++++++++++++++++++++++++++++++\n\nfunction FitzHughNagumo()\n\nglobal dT\n\norient tall\n\n% Dimensions: dq for param. vector, dx augmented state, dy observation\ndq=1; dx=dq+2; dy=1; \n\nfct='FitzHughNagumo_fct'; % model function F(x)\nobsfct='FitzHughNagumo_obsfct'; % observation function G(x)\n\nll=800; % number of data samples\ndT=0.2; % sampling time step (global variable)\n\n% Simulating data: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nx0=zeros(2,ll); x0(:,1)=[0; 0]; % true trajectory\ndt=.1*dT; nn=fix(dT/dt); % the integration time step is smaller than dT\n\n% External input, estimated as parameter p later on:\nz=[1:ll]/250*2*pi; z=-.4-1.01*abs(sin(z/2));\n\n% 4th order Runge-Kutta integrator:\n\nfor n=1:ll-1;\n xx=x0(:,n);\n for i=1:nn\n k1=dt*FitzHughNagumo_int(xx,z(n));\n k2=dt*FitzHughNagumo_int(xx+k1/2,z(n));\n k3=dt*FitzHughNagumo_int(xx+k2/2,z(n));\n k4=dt*FitzHughNagumo_int(xx+k3,z(n));\n xx=xx+k1/6+k2/3+k3/3+k4/6;\n end;\n x0(:,n+1)=xx;\nend;\n\nx=[z; x0]; % augmented state vector (notation a bit different to paper)\n\nR=.2^2*var(FitzHughNagumo_obsfct(x))*eye(dy,dy); % observation noise covariance matrix\nrandn('state',0); y=feval(obsfct,x)+sqrtm(R)*randn(dy,ll); % noisy data\n\n% Initial conditions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nxhat=zeros(dx,ll); \nxhat(:,2)=x(:,2); % first guess of x_1 set to observation \n\nQ=.015; % process noise covariance matrix\n\nPxx=zeros(dx,dx,ll); \nPxx(:,:,1)=blkdiag(Q,R,R);\n\nerrors=zeros(dx,ll); % not so important\nKs=zeros(dx,dy,ll); % Kalman gains\n\n% Main loop for recursive estimation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfor k=2:ll \n\n[xhat(:,k),Pxx(:,:,k),Ks(:,:,k)]=ut(xhat(:,k-1),Pxx(:,:,k-1),y(:,k),fct,obsfct,dq,dx,dy,R);\n\nPxx(1,1,k)=Q;\n\nerrors(:,k)=sqrt(diag(Pxx(:,:,k)));\n\nend; % k\n\n% Results %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nchisq=mean((x(1,:)-xhat(1,:)).^2+(x(2,:)-xhat(2,:)).^2+(x(3,:)-xhat(3,:)).^2)\nest=xhat(1:dq,ll)'\nerror=errors(1:dq,ll)'\n\nfigure(1)\n\nsubplot(2,1,1)\nplot(y,'bd','MarkerEdgeColor','blue', 'MarkerFaceColor','blue','MarkerSize',3);\nhold on; \nplot(x(dq+1,:),'black','LineWidth',2);\n%plot(xhat(dq+1,:),'r','LineWidth',2); \nxlabel(texlabel('t'));\nylabel(texlabel('x_1, y'));\nhold off;\naxis tight\ntitle('(a)')\ndrawnow\n\nsubplot(2,1,2)\nplot(x(dq+2,:),'black','LineWidth',2);\nhold on\nplot(xhat(dq+2,:),'r','LineWidth',2); \nplot(x(1,:),'black','LineWidth',2); \nfor i=1:dq; plot(xhat(i,:),'m','LineWidth',2); end;\nfor i=1:dq; plot(xhat(i,:)+errors(i,:),'m'); end;\nfor i=1:dq; plot(xhat(i,:)-errors(i,:),'m'); end;\nxlabel(texlabel('t'));\nylabel(texlabel('z, estimated z, x_2, estimated x_2'));\nhold off\naxis tight\ntitle('(b)')\n\nfunction r=FitzHughNagumo_int(x,z)\n% Function for modeling data, not for UKF execution\na=.7; b=.8; c=3.;\nr=[c*(x(2)+x(1)-x(1)^3/3+z); -(x(1)-a+b*x(2))/c];\n\nfunction r=FitzHughNagumo_obsfct(x)\n% Observation function\nr=x(2,:);\n\nfunction r=FitzHughNagumo_fct(dq,x)\n% Runge-Kutta integrator for FitzHugh-Nagumo system with parameters\n\nglobal dT\ndt=.02; % local integration step\nnn=fix(dT/dt);\n\np=x(1:dq,:);\nxnl=x(dq+1:size(x(:,1)),:);\nfor n=1:nn\nk1=dt*fc(xnl,p);\nk2=dt*fc(xnl+k1/2,p);\nk3=dt*fc(xnl+k2/2,p);\nk4=dt*fc(xnl+k3,p);\nxnl=xnl+k1/6+k2/3+k3/3+k4/6;\nend\nr=[x(1:dq,:); xnl];\n\nfunction r=fc(x,p);\na=.7; b=.8; c=3.;\nr=[c*(x(2,:)+x(1,:)-x(1,:).^3/3+p); -(x(1,:)-a+b*x(2,:))/c];\n\nfunction [xhat,Pxx,K]=ut(xhat,Pxx,y,fct,obsfct,dq,dx,dy,R);\n% Unscented transformation. Not specific to FitzHugh-Nagumo model\n\n N=2*dx;\n\n xsigma=chol( dx*Pxx )'; % Pxx=root*root', but Pxx=chol'*chol\n Xa=xhat*ones(1,N)+[xsigma, -xsigma];\n X=feval(fct,dq,Xa);\n\n xtilde=sum(X')'/N;\n\n Pxx=zeros(dx,dx);\n for i=1:N;\n Pxx=Pxx+(X(:,i)-xtilde)*(X(:,i)-xtilde)'/N;\n end;\n\n Y=feval(obsfct,X);\n\n ytilde=sum(Y')'/N;\n Pyy=R;\n for i=1:N;\n Pyy=Pyy+(Y(:,i)-ytilde)*(Y(:,i)-ytilde)'/N;\n end;\n Pxy=zeros(dx,dy); \n for i=1:N;\n Pxy=Pxy+(X(:,i)-xtilde)*(Y(:,i)-ytilde)'/N;\n end;\n \n K=Pxy*inv(Pyy);\n xhat=xtilde+K*(y-ytilde);\n Pxx=Pxx-K*Pxy';\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/37355-unscented-kalman-filter-ukf-modeling-of-fitzhugh-nagumo-dynamics/FitzHughNagumo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6858742616022018}} {"text": "function vEst=RROnlyStaticVelEst(rr,xTx,xRx,zTar)\n%%RRONLYSTATICVELEST Perform unweighted least-squares estimation of a\n% target velocity vector given only range rate measurements from\n% different bistatic channels (or from multiple receivers if the\n% target is the transmitter). This function can work in 2D and\n% 3D space and it will produce a least-squares estimate when more\n% than the minimum number of range rate measurements needed is\n% given. This uses a non-relativistic model for the range rates\n% and ignores possible atmospheric effects. \n%\n%INPUTS: rr A numMeasX1 or 1XnumMeas vector of range rates. numMeas>=3 for\n% the velocity vector to be observable in 3D and numMeas>=2 in\n% 2D.\n% xTx A 6XnumMeas matrix (in 3D or a 4XnumMeas matrix in 2D) of\n% stacked transmitter position and velocity vectors. If the\n% target is the transmitter, then an empty matrix should be\n% passed. xTx(:,n)=[x;y;z;xDot;yDot;zDot] is the state (3\n% position and 3 velocity components) corresponding to the nth\n% range rate measurement. If all of the transmitters are in the\n% same spot, then a single 6X1 or 4X1 vector can be passed.\n% xRx A 6XnumMeas matrix (in 3D or a 4XnumMeas matrix in 2D) of\n% stacked transmitter position and velocity vectors.\n% states1(:,n)=[x;y;z;xDot;yDot;zDot] is the state (3 position\n% and 3 velocity components) corresponding to the nth range rate\n% measurement. If all of the receivers are in the same spot, then\n% a single 6X1 or 4X1 vector can be passed.\n% zTar The 3X1 (in 3D) or 2X1 (in 2D) Cartesian position of the\n% target.\n%\n%OUTPUTS: vEst The 3X1 (in 3D) or 2X1 (in 2D) least squares Cartesian\n% velocity estimate of the target.\n%\n%This implements the least squares velocity vector estimation procedure of\n%Equation 41 in Section IV E of [1]. The case of the transmitter being the\n%target is handled specially (to get rid fo the singulaity).\n%\n%EXAMPLE 1:\n%This is just a simple example showing that for three range rate values,\n%one can get back the orignal velocity value in 3D.\n% zTar=[0;40e3;40e3];\n% vTar=[400;-200;100];\n% xTx1=[100;10e3;3e3;50;50;-50];\n% xTx2=[0;0;0;0;0;-20];\n% xTx3=[10e3;10e3;3e3;100;-100;100];\n% \n% xRx1=[-10e3;0;3e3;100;100;100];\n% xRx2=[0;10e3;30;-80;-200;-20];\n% xRx3=xRx2;\n% \n% states1=[xTx1,xTx2,xTx3];\n% states2=[xRx1,xRx2,xRx3];\n% \n% xTar=[zTar;vTar];\n% \n% useHalfRange=false;\n% rr=zeros(3,1);\n% rr(1)=getRangeRate(xTar,useHalfRange,xTx1,xRx1);\n% rr(2)=getRangeRate(xTar,useHalfRange,xTx2,xRx2);\n% rr(3)=getRangeRate(xTar,useHalfRange,xTx3,xRx3);\n% \n% vEst=RROnlyStaticVelEst(rr,states1,states2,zTar)\n%One will see that vEst=vzTar.\n%\n%EXAMPLE 2:\n%This is the same as example 1, except the demonstration is now occurring\n%in 2D.\n% zTar=[0;40e3];\n% vTar=[400;-200];\n% xTx1=[100;10e3;50;50];\n% xTx2=[0;0;0;0];\n% xTx3=[10e3;10e3;100;-100];\n% \n% xRx1=[-10e3;0;100;100];\n% xRx2=[0;10e3;-80;-200];\n% xRx3=xRx2;\n% \n% states1=[xTx1,xTx2,xTx3];\n% states2=[xRx1,xRx2,xRx3];\n% \n% xTar=[zTar;vTar];\n% \n% useHalfRange=false;\n% rr=zeros(3,1);\n% rr(1)=getRangeRate(xTar,useHalfRange,xTx1,xRx1);\n% rr(2)=getRangeRate(xTar,useHalfRange,xTx2,xRx2);\n% rr(3)=getRangeRate(xTar,useHalfRange,xTx3,xRx3);\n% \n% vEst=RROnlyStaticVelEst(rr,states1,states2,zTar)\n%One will see that vEst=vzTar.\n%\n%EXAMPLE 3:\n%In this example, the range rate is one-way from the target (e.g. the\n%target is an emitter). The relative error of the velocity estimate with\n%the truth (noiseless scenario) is within finite precision limits.\n% zTar=randn(3,1);\n% vTar=randn(3,1);\n% numMeas=5;\n% xRx=randn(6,numMeas);\n% xTar=[zTar;vTar];\n% useHalfRange=false;\n% rr=zeros(numMeas,1);\n% for k=1:numMeas\n% rr(k)=getRangeRate(xTar,useHalfRange,xTar,xRx(:,k));\n% end\n% vEst=RROnlyStaticVelEst(rr,[],xRx,zTar);\n% RelErr=max(abs((vTar-vEst)./vTar))\n%\n%REFERENCES:\n%[1] David F. Crouse , \"Basic tracking using nonlinear 3D monostatic and\n% bistatic measurements,\" IEEE Aerospace and Electronic Systems \n% Magazine, vol. 29, no. 8, Part II, pp. 4-53, Aug. 2014.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumMeas=length(rr);\nrr=rr(:);\n\nif(size(xTx,2)==1)\n xTx=repmat(xTx,1,numMeas);\nend\n\nif(size(xRx,2)==1)\n xRx=repmat(xRx,1,numMeas);\nend\n\nposDim=length(zTar);\n\nzRx=xRx(1:posDim,:);\nvRx=xRx((posDim+1):(2*posDim),:);\n\nh=bsxfun(@minus,zTar,zRx);\nhNorm=sqrt(sum(h.*h,1));\nh=bsxfun(@rdivide,h,hNorm);\n\nif(~isempty(xTx))\n %The target is not the transmitter.\n zTx=xTx(1:posDim,:);\n vTx=xTx((posDim+1):(2*posDim),:);\n hi=bsxfun(@minus,zTar,zTx);\n hiNorm=sqrt(sum(hi.*hi,1));\n hi=bsxfun(@rdivide,hi,hiNorm);\n\n rDotB=rr+sum(h.*vRx,1)'+sum(hi.*vTx,1)';\n Hv=bsxfun(@plus,h',hi');\nelse\n %The target is the transmitter.\n rDotB=rr+sum(h.*vRx,1)';\n Hv=h';\nend\n\nvEst=lsqminnorm(Hv,rDotB);\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/Static_Estimation/RROnlyStaticVelEst.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6858742527563937}} {"text": "% feldkamp_example.m\n% example of how to use feldkamp.m for cone-beam CT reconstruction\n% Copyright 2004-8-28, Nicole Caparanis, Patty Laskowsky, Taka Masuda,\n% and Jeff Fessler, The University of Michigan\n\nif ~isvar('proj'), disp 'proj'\n\tdown = 8;\n\tnh = 256/down;\n\tnv = 240/down;\n\tna = 224/down;\n\tds = 1024/nh;\n\tdt = ds;\n\tdis_src_det = 949.075;\n\tdis_iso_det = 408.075;\n\tdis_src_iso = dis_src_det - dis_iso_det;\n%\tdis_foc_src = inf; % flat detector panel\n\tdis_foc_src = 0; % arc detector\n\toffset_det_h = 0.25; % quarter detector\n\toffset_det_v = 0.0;\n\thoriz = ([-(nh-1)/2:(nh-1)/2]' - offset_det_h) * ds;\n\tverti = ([-(nv-1)/2:(nv-1)/2]' - offset_det_v) * dt;\n\tprintf('rmax=%g', dis_src_iso*sin(atan(max(abs(horiz)) / dis_src_det)))\n\n\tell = [ ...\n\t\t[20 0 0 150 150 200 0 0.01]; % 30cm diam \"cylinder\"\n\t\t[80 0 0 50 50 30 0 0.01]; % bone-like inserts\n\t\t[0 0 75 40 40 40 0 0.01];\n\t\t[0 70 0 30 30 30 0 0.01];\n\t];\n\n\tproj = ellipsoid_proj(ell, horiz, verti, na, ...\n\t\tdis_src_iso, dis_iso_det, dis_foc_src);\n\n\tnx = 256/down;\n\tny = 240/down;\n\tnz = 200/down;\n\tdx = 2*down; dy = dx; dz = dx; % 2mm voxels * down-sampling\n\txtrue = ellipsoids(nx, ny, nz, ell, dx, dy, dz);\n\n\t% cone-beam system geometry, generalized from fan-beam geometry.\n\t% see ASPIRE users guide under tech. reports on web page for details.\n\targs = arg_pair('system', NaN, 'nx', nx, 'ny', ny, 'nz', nz, ...\n\t\t'nv', nv, 'nh', nh, 'na', na, 'support', 'all', ...\n\t\t'orbit', 360, 'orbit_start', 0, ...\n\t\t'pixel_size', dx, 'ray_spacing', ds, 'strip_width', 0, ...\n\t\t'dis_src_det', dis_src_det, ...\n\t\t'dis_iso_det', dis_iso_det, ...\n\t\t'dis_foc_src', dis_foc_src, ...\n\t\t'offset_source', 0, ...\n\t\t'offset_det_h', offset_det_h, ...\n\t\t'offset_det_v', offset_det_v);\n\n\tpl=330;\n\tim(pl+1, xtrue, 'x true'), cbar\n\tim(pl+4, proj, 'true projections'), cbar\n\tdrawnow\nprompt\nend\n\n% noisy data and estimated line integrals\nif ~isvar('li_hat'), disp 'li_hat'\n\t% noisy data, if blank scan value has been specified.\n\tif isvar('bi') && isvar('ri')\n\t\tyb = bi .* exp(-proj) + ri;\n\t\tyi = poisson(yb);\n\t\tli_hat = -log((yi-ri) ./ bi);\n\t\tli_hat(yi-ri <= 0) = 0; % fix: need something better here...\n\telse\n\t\tli_hat = proj; % noiseless\n\tend\nend\n\n% FDK cone-beam reconstruction\nif ~isvar('xfdk'), disp 'fdk'\n\tmask = true([nx ny nz]);\n\txfdk = feldkamp_old(li_hat, 'ramp', mask, args);\nend\n\nif 1\n\t% show results (off-center slices worse than central slice)\n\tim(pl+2, xfdk, 'FDK recon'), cbar\n\tim(pl+3, xfdk - xtrue, 'FDK error'), cbar\n\n\tsubplot(pl+5)\n\tix = 1:nx; iy = ceil(ny/2); iz = ceil(nz/2);\n\tplot(ix, xtrue(ix,iy,iz), '-', ix, xfdk(ix,iy,iz), '--')\n\taxis([1 nx -0.005 0.025]), legend('true', 'FDK recon', 2)\n\ttitle 'middle slice', xlabel 'ix'\n\n\tsubplot(pl+6)\n\tiz=1:nz; ix = 1+floor(nx/2); iy = 1+floor(ny/2);\n\tplot(iz, squeeze(xtrue(ix,iy,iz)), '-', iz, squeeze(xfdk(ix,iy,iz)), '--')\n\taxis([1 nz -0.005 0.025]), legend('true', 'FDK recon', 2), xlabel 'iz'\n\ttitle(sprintf('profile at (ix,iy)=(%g,%g)', ix,iy))\n\nprompt\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/fbp/arch/feldkamp_example_old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6858742505449416}} {"text": "%% CUBEAFEMQUADCURL quad curl equations on the unit cube\n%\n% CUBEAFEMQUADCURL computes ND0-(CR-P0)-ND0 nonconforming approximations \n% of the quad curl equations in the unit cube. The mesh is refined\n% adaptively guided by a residual-based estimator.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclose all; clear;\n\n%% Set up\nmaxN = 5e5;\nmaxIt = 20;\ntheta = 0.3;\nN = zeros(maxIt,1);\nh = zeros(maxIt,1);\nerru = zeros(maxIt,1); \nerrw = zeros(maxIt,1);\nerrphi = zeros(maxIt,1);\netaTotal = zeros(maxIt,1);\netaw = zeros(maxIt,1);\netaphi = zeros(maxIt,1);\netau = zeros(maxIt,1);\n\n%% Generate initial mesh\nH = pi;\n[node,elem,HB] = cubemesh([0,H,0,H,0,H],H/2);\nbdFlag = setboundary3(node,elem,'Dirichlet');\n\n%% PDE and options\npde = quadCurlDataSmooth1;\n\noption.solver = 'direct';\noption.printlevel = 0;\n\n%% Finite Element Method \nfor k = 1:maxIt\n \n %% SOLVE\n [soln,eqn] = quadcurl3NC(node,elem,bdFlag,pde,option);\n N(k) = 2*length(soln.u)+3*length(soln.phi);\n %% ESTIMATE\n [erru(k), errK] = getHcurlerror3ND(node,elem,pde.curlu,soln.u);\n [etaK, est] = estimatequadcurl(node,elem,soln,pde,option);\n etaTotal(k) = sqrt(sum(etaK.^2));\n etaw(k) = sqrt(sum((est.eta1).^2));\n etaphi(k) = sqrt(sum((est.eta2).^2));\n etau(k) = sqrt(sum((est.eta3).^2));\n fprintf(\"Iter %2d, # Dof= %6d; \\n||curl(u-u_h)|| = %8.6g,eta = %8.6g \\n \\n\",...\n k, N(k), erru(k), etaTotal(k))\n %% Visualize\n figure(1);\n set(gcf, 'Position', [100 600 1000 300])\n subplot(1,3,1)\n showboundary3(node,elem,'z maxN\n break;\n end\n \n markedElem = mark(elem,etaK,theta);\n if k < maxIt\n [node,elem,bdFlag,HB] = bisect3(node,elem,markedElem,bdFlag,HB);\n [elem,bdFlag] = sortelem3(elem,bdFlag);\n end\n \nend\n\n%%\nclose all;\nfigure(1);\nr1 = showrate(N,erru,10,'r-o');\nr2 = showrate(N,etaTotal,10,'b-*');\nr3 = showrate(N,etaw,10,'color',[0.2, 0.8,0.7],'marker','*');\nr4 = showrate(N,etaphi,10,'color',[0.2, 0.8,0.7],'marker','*');\nr5 = showrate(N,etau,10,'color',[0.2, 0.8,0.7],'marker','*');\nset(gca,'xscale','log','yscale','log');\nT = title('Convergence');\nXL = xlabel('$\\#$ DoFs');\nYL = ylabel('Error Magnitudes');\nL = legend('$\\Vert \\nabla\\times(u-u_h)\\Vert$', ...\n ['$N^{' num2str(r1) '}$'],...\n '$\\eta(w_h,\\phi_h,u_h)$', ...\n ['$N^{' num2str(r2) '}$'],...\n '$\\eta_1(w_h)$', ['$N^{' num2str(r3) '}$'],...\n '$\\eta_2(\\phi_h)$', ['$N^{' num2str(r4) '}$'],...\n '$\\eta_3(u_h)$', ['$N^{' num2str(r5) '}$'],...\n 'LOCATION','Best');\nset([XL,YL,L],'Interpreter','latex','FontSize', 12);\nset(T,'Interpreter','latex','FontSize',16);\ngrid on;\nset(gcf,'color','w','Position', [100 200 350 500])\ndrawnow;\n\n\n%% sanity check\nif N<5e3\n figure(2);\n subplot(1,2,1);\n option.scale = 2;\n option.plot = 'quiver3';\n center = (node(elem(:,1),:) + node(elem(:,2),:) + ...\n node(elem(:,3),:) + node(elem(:,4),:))/4;\n showvector3(center,pde.curlu(center),option);\n subplot(1,2,2);\n curluh = curlu3(node,elem,soln.u);\n showvector3(center,curluh,option);\n % showvector3(center,curlwh_comp2,option);\n \n set(gcf,'color','w','Position', [500 600 750 300])\n drawnow;\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/quadCurl/cubeAfemQuadCurl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6858742458247926}} {"text": "function [xs,phid,wlsden,timeiter,niter] = wls_gcd(A, W, yy, xhat, ng, niter, tol)\n%\tweighted least squares minimized by\n%\tgrouped coordinate descent algorithm\n%\tInput\n%\t\tA\t[nn,np]\t\tsystem matrix\n%\t\tW\t[nn,nn]\t\tinverse data covariance\n%\t\tyy\t[nn,1]\t\tnoisy data\n%\t\txhat\t[np,1] or [nx,ny]\tinitial estimate\n%\t\tng\t\t\t# groups, or, if array, groups\n%\t\ttol\t\t\tstopping criterion for convergence\n%\t\tniter\t\t\tmax\n%\n%\tOutput\n%\t\txs\t[np,niter+1]\testimates each iteration\n%\t\tphid\t[niter+1,1]\tobjective decrease\n%\t\twlsden\t[np,1]\t\tcurvature of surrogate\n%\t\ttimeiter [niter+1,1]\tCPU time each iteration\n%\t\tniter\t\t\t# total iterations\n%\t\t\n% Saowapak Sotthivirat\n% 8/15/00\n\n[nx,ny] = size(xhat);\n\nnp = ncol(A);\nyy = yy(:);\nxhat = xhat(:);\nxs(:,1) = xhat;\n\n%\n%\tbuild groups\n%\nif numel(ng) == 1\n\tgroups = zeros(np, ng);\n\tfor ig = 1:ng\n\t\tgg(:,ig) = [ig:ng:np]';\n\t\tgroups(gg(:,ig),ig) = ones(size(gg(:,ig)));\n\tend\nelseif numel(ng) == 2\n\tgroups\t= group2d(nx, ny,ng,ones(ng(1),ng(2)),0);\n\tng\t= ncol(groups);\n\tfor ig = 1:ng\n\t\tgg(:,ig) = find(groups(:,ig).*[1:np]');\n\tend\nelse\n\tgroups\t= ng;\n\tng\t= ncol(groups);\nend\n\n\n%\tprecompute quadratic part of denominator\n%\tchange '1' to 'ig' for overlapping groups\nwlsden = zeros(np, 1);\nfor ig = 1:ng\n\tgr = groups(:,ig);\n\tggi = gg(:,ig);\n\n\tt = A * gr;\t% faster than: sum(A(:,gg)',1)';\n\tt = W * t;\t% only slightly slower than: diag(W) .* t;\n\t\t\t% faster than either: A(:,gg)'*t or A' * t !\n\tt = t' * A;\n\twlsden(ggi) = t(ggi)';\nend\n\nwii = diag(W);\nres = A * xhat - yy;\nphi0 = res'*W*res/2;\nii = 1;\nphid(ii) = 0;\ntimeiter(ii) = 0;\nt0 = cputime;\n\nwhile phid(ii) < tol & ii <= niter\n\t\n\tfor ig = 1:ng\n\t\tggi = gg(:,ig);\n\t\txold = xhat(ggi);\n\t\txnew = xold;\n\t\tader = ((W*res)'*A(:,ggi))';\n\t\tdiff = ader./wlsden(ggi);\n\t\txnew = xnew - diff;\n\t\txhat(ggi) = max(0,xnew);\n\t\tres = res - A(:,ggi) * diff;\n\n\tend\n\tii = ii+1;\n\txs(:,ii) = xhat;\n\tphid(ii) = phi0 - res'*W*res/2;\n\ttimeiter(ii) = cputime - t0;\nend\n\nniter = ii;\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/ppcd/wls_gcd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985636, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.6858403446224665}} {"text": "function [F,sA] = spm_multinomial_log_evidence(qA,pA,rA)\n% Bayesian model reduction for multinomial distibutions\n% FORMAT [F,sA] = spm_multinomial_log_evidence(qA,pA,rA)\n%\n% qA - parameter of posterior of full model\n% pA - parameter of prior of full model\n% rA - parameter of prior of reduced model\n%\n%\n% F - (negative) free energy or log evidence of reduced model\n% sA - parameter of reduced posterior\n%\n% This routine computes the negative log evidence of a reduced model of a\n% mutinomial distribution. This also applies for Bernoulli, Binomial, and\n% Categorical distributions.\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging\n\n% Thomas Parr\n% $Id: spm_multinomial_log_evidence.m 7679 2019-10-24 15:54:07Z spm $\n\n% reduced posteriors\n%--------------------------------------------------------------------------\nsA = spm_softmax(qA + rA - pA);\n\n% change in free energy or log model evidence\n%--------------------------------------------------------------------------\nk = find(rA);\nF = log(rA(k(1))) - log(pA(k(1))) + log(qA(k(1))) - log(sA(k(1)));\n\n\n\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/spm_multinomial_log_evidence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763572, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6858236139524784}} {"text": "function [type,center,theta,foci,ecc,normform] = conic_properties(A,B,C,D,E,F)\n\n[type,x0,y0,theta,A2,B2,C2,D2,E2,F2] = conic_standard_form(A,B,C,D,E,F);\n\n% change from translation followed by rotation to rotation followed by\n% translation\n% x <- (x + u)*R\n% = x*R + u*R\nR = [cos(theta),sin(theta);-sin(theta),cos(theta)];\ncenter = [x0,y0]*R;\nnormform = [A2,B2,C2,D2,E2,F2];\n\nif strcmpi(type,'circle')\n foci = [0,0];\n ecc = 0;\nelseif strcmpi(type,'ellipse') || strcmpi(type,'hyperbola'),\n a2 = 1 / min(abs(A2),abs(C2));\n b2 = 1 / max(abs(A2),abs(C2));\n c2 = sqrt(a2 - b2);\n if A2 < C2,\n foci = [-c2,0;c2,0];\n else\n foci = [0,-c2;0,c2];\n end\n ecc = c2 / a2;\nelseif strcmpi(type,'parabola'),\n if abs(A2) > abs(C2),\n foci = [0,-E2/4];\n else\n foci = [-D2/4,0];\n end\n ecc = 1;\nelse % other\n foci = zeros(0,2);\n ecc = 0;\nend\n\nnfoci = size(foci,2);\nif nfoci > 0,\n % translate\n foci(:,1) = foci(:,1) + x0;\n foci(:,2) = foci(:,2) + y0;\n % rotate\n foci = foci*R;\nend", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/misc/conic_properties.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6858236080173842}} {"text": "function model = glmOmnibus(model, units);\n% \n% model = glmOmnibus(model, [units]);\n%\n% Compute the 'omnibus' contrast for a GLM -- an F test of the significance\n% of all experimental conditions against baseline -- appending the results\n% to a GLM model struct. \n% \n% model: struct produced by the glm function.\n%\n% units: 'F' or 'p', specifies the units to return for each voxel. [Default\n% 'p', p-value associated w/ the F distribution.]\n%\n% Appends a model.omnibus field, containing the results of the contrast\n% for each voxel, as well as an omnibus_units field, specifying the units\n% used.\n%\n% For details see Burock and Dale, \"Estimation and Detection of \n% Event-Related fMRI Signals with Temporally Correlated Noise: A \n% Statistically Efficient and Unbiased Approach\", HBM, 2001.\n%\n% ras, 01/04/2006.\nif ieNotDefined('units'), units = 'p'; end\n\n\n\n% Omnibus Significance Test % (from er_selxavg)\nR = eye(model.nh, Navgs_tot);\nq = R*hhat;\nif model.nh > 1\n qsum = sum(q); % To get a sign %\nelse\n qsum = q;\nend\n\nif (model.nh == 1)\n Fnum = inv(R * model.C * R') * (q.^2) ; %'\nelse\n Fnum = sum(q .* (inv(R*model.C*R') * q)); %'\nend\n\nFden = model.nh * (eres_std.^2);\nind = find(Fden == 0);\nFden(ind) = 10^10;\nF = sign(qsum) .* Fnum ./ Fden;\n\nif (~isempty(fomnibusstem))\n fname = sprintf('%s_%03d.mat',fomnibusstem,slice);\n tmp = reshape(F,[nrows ncols]);\n er_svtfile(tmp,fname,override);\nend\n\nif isequal(lower(units), 'p')\n % convert to p-value, looking it up for the associated F distribution:\n % This will have [J, n-K] degrees of freedom, where J is the number\n % of rows in our restriction matrix R, and n and K are the # of rows\n % and columns in the design matrix X, respectively.\n p = sign(F) .* er_ftest(model.nh, model.dof, abs(F));\n \n % this prevents values from becoming infinite -- but I'm not\n % sure why p(indz) is set to 1 rather than s\n indz = find(p==0);\n p(indz) = 1;\n p = sign(p).*(-log10(abs(p)));\n\n omnibus(1:nrows, 1:ncols, slice) = reshape(p, [nrows ncols]);\nend\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/EventRelated/GLM/glmOmnibus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6857282353558972}} {"text": "function [P orderstruct] = mmtimes(varargin)\n% P = mmtimes(M1, M2, ... Mn)\n% return a chain matrix product P = M1*M2* ... *Mn\n%\n% {Mi} are matrices with compatible dimension: size(Mi,2) = size(Mi+1,1)\n% \n% Because the matrix multiplication is associative; the chain product can\n% be carried out with different order, leading to the same result (up to\n% round-off error). MMTIMES uses \"optimal\" order of binary product to\n% reduce the computational effort (probably the accuracy is also improved).\n%\n% The function assumes the cost of the product of (m x n) with (n x p)\n% matrices is (m*n*p). This assumption is typically true for full matrix.\n%\n% Notes:\n% Scalar matrix are groupped together, and the rest will be\n% multiplied with optimal order.\n%\n% To get the the structure that stores the best order, call with the\n% second outputs:\n% >> [P orderstruct] = mmtimes(M1, M2, ... Mn);\n% % This structure can be used later if the input matrices have the\n% % same sizes as those in the first call (but with different contents)\n% >> P = mmtimes(M1, M2, ... Mn, orderstruct);\n%\n% See also: mtimes\n%\n% Author: Bruno Luong \n% Orginal: 19-Jun-2010\n% 20-Jun-2010: quicker top-down algorithm\n% 23-Jun-2010: treat the case of scalars\n% 16-Aug-2010: passing optimal order as output/input argument\n\nMatrices = varargin;\n\nbuildexpr = false;\nif ~isempty(Matrices) && isstruct(Matrices{end})\n orderstruct = Matrices{end};\n Matrices(end) = [];\nelse\n % Detect scalars\n iscst = cellfun('length',Matrices) == 1;\n if any(iscst)\n % scalars are multiplied apart\n cst = prod([Matrices{iscst}]);\n Matrices = Matrices(~iscst);\n else\n cst = 1;\n end\n % Size of matrices\n szmats = [cellfun('size',Matrices,1) size(Matrices{end},2)];\n s = MatrixChainOrder(szmats);\n\n orderstruct = struct('cst', cst, ...\n 's', s, ...\n 'szmats', szmats);\n \n if nargout>=2\n % Prepare to build the string expression\n vnames = arrayfun(@inputname, 1:nargin, 'UniformOutput', false);\n % Default names, e.g., M1, M2, ..., for inputs that is not single variable \n noname = cellfun('isempty', vnames);\n vnames(noname) = arrayfun(@(i) sprintf('M%d', i), find(noname), 'UniformOutput', false);\n if any(iscst)\n % String '(M1*M2*...)' for constants\n cstexpr = strcat(vnames(iscst),'*');\n cstexpr = strcat(cstexpr{:});\n cstexpr = ['(' cstexpr(1:end-1) ')'];\n else\n cstexpr = '';\n end\n vnames = vnames(~iscst);\n buildexpr = true;\n end\nend\n\nif ~isempty(Matrices)\n P = ProdEngine(1,length(Matrices),orderstruct.s,Matrices); \n if orderstruct.cst~=1\n P = orderstruct.cst*P;\n end\n if buildexpr\n expr = Prodexpr(1,length(Matrices),orderstruct.s,vnames);\n if ~isempty(cstexpr)\n % Concatenate the constant expression in front\n expr = [cstexpr '*' expr];\n end\n orderstruct.expr = expr;\n end\nelse\n P = orderstruct.cst;\n if nargout>=2\n orderstruct.expr = cstexpr; \n end\nend\n\nend % mmtimes\n\n\n%%\nfunction [s qmin] = MatrixChainOrder(szmats)\n% Find the best ordered chain-product, the best splitting index\n% of M(i)*...*M(j) is stored in s(j,i) of the array s (only the lower\n% part is filled)\n% Top-down dynamic programming, complexity O(n^3)\n\nn = length(szmats)-1;\ns = zeros(n);\n\npk = szmats(2:n);\nij = (0:n-1)*(n+1)+1;\nleft = zeros(1,n-1);\nright = zeros(1,n-1);\nL = 1;\nwhile true % off-diagonal offset\n q = zeros(size(pk));\n for j=1:n-L % this is faster and BSXFUN or product with DIAGONAL matrix\n q(:,j) = (szmats(j)*szmats(j+L+1))*pk(:,j);\n end\n q = q + left + right;\n [qmin loc] = min(q, [], 1);\n s(ij(1:end-L)+L) = (1:n-L)+loc;\n \n if L.\n\nif nargin == 1\n y = 1;\nend\n\nalpha = 20*log10(exp(1))*alpha*(2*pi/1e-6)^y/100;", "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/neper2db.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.685671482400419}} {"text": "function y = im2jpeg(x, quality) \n%IM2JPEG Compresses an image using a JPEG approximation.\n% Y = IM2JPEG(X, QUALITY) compresses image X based on 8 x 8 DCT\n% transforms, coefficient quantization, and Huffman symbol\n% coding. Input QUALITY determines the amount of information that\n% is lost and compression achieved. Y is an encoding structure\n% containing fields: \n%\n% Y.size Size of X\n% Y.numblocks Number of 8-by-8 encoded blocks\n% Y.quality Quality factor (as percent)\n% Y.huffman Huffman encoding structure, as returned by\n% MAT2HUFF\n%\n% See also JPEG2IM.\n\n% Copyright 2002-2006 R. C. Gonzalez, R. E. Woods, & S. L. Eddins\n% Digital Image Processing Using MATLAB, Prentice-Hall, 2004\n% $Revision: 1.5 $ $Date: 2006/07/15 20:44:34 $\n%\n% Revised: 3/20/06 by R.Woods to correct an 'eob' coding problem, to\n% check the 'quality' input for <= 0, and to fix a warning when\n% struct y is created.\n\nerror(nargchk(1, 2, nargin)); % Check input arguments\nif ndims(x) ~= 2 | ~isreal(x) | ~isnumeric(x) | ~isa(x, 'uint8')\n error('The input must be a UINT8 image.'); \nend\nif nargin ==2 && quality <= 0\n error('Input parameter QUALITY must be greater than zero.');\nend\nif nargin < 2 \n quality = 1; % Default value for quality.\nend \n\nm = [16 11 10 16 24 40 51 61 % JPEG normalizing array\n 12 12 14 19 26 58 60 55 % and zig-zag redordering\n 14 13 16 24 40 57 69 56 % pattern.\n 14 17 22 29 51 87 80 62\n 18 22 37 56 68 109 103 77\n 24 35 55 64 81 104 113 92\n 49 64 78 87 103 121 120 101\n 72 92 95 98 112 100 103 99] * quality;\n\norder = [1 9 2 3 10 17 25 18 11 4 5 12 19 26 33 ...\n 41 34 27 20 13 6 7 14 21 28 35 42 49 57 50 ...\n 43 36 29 22 15 8 16 23 30 37 44 51 58 59 52 ...\n 45 38 31 24 32 39 46 53 60 61 54 47 40 48 55 ...\n 62 63 56 64];\n\n[xm, xn] = size(x); % Get input size.\nx = double(x) - 128; % Level shift input\nt = dctmtx(8); % Compute 8 x 8 DCT matrix\n\n% Compute DCTs of 8x8 blocks and quantize the coefficients.\ny = blkproc(x, [8 8], 'P1 * x * P2', t, t');\ny = blkproc(y, [8 8], 'round(x ./ P1)', m);\n\ny = im2col(y, [8 8], 'distinct'); % Break 8x8 blocks into columns\nxb = size(y, 2); % Get number of blocks\ny = y(order, :); % Reorder column elements\n\neob = max(y(:)) + 1; % Create end-of-block symbol\nr = zeros(numel(y) + size(y, 2), 1);\ncount = 0;\nfor j = 1:xb % Process 1 block (col) at a time\n i = max(find(y(:, j))); % Find last non-zero element\n if isempty(i) % No nonzero block values\n i = 0;\n end\n p = count + 1;\n q = p + i;\n r(p:q) = [y(1:i, j); eob]; % Truncate trailing 0's, add EOB,\n count = count + i + 1; % and add to output vector\nend\n\nr((count + 1):end) = []; % Delete unusued portion of r\n \ny = struct;\ny.size = uint16([xm xn]);\ny.numblocks = uint16(xb);\ny.quality = uint16(quality * 100);\ny.huffman = mat2huff(r);\n", "meta": {"author": "Ultrasty", "repo": "Digital-Image-Processing", "sha": "dbcad426ff9ae7582d25b6f36de68edbfbd2a3b7", "save_path": "github-repos/MATLAB/Ultrasty-Digital-Image-Processing", "path": "github-repos/MATLAB/Ultrasty-Digital-Image-Processing/Digital-Image-Processing-dbcad426ff9ae7582d25b6f36de68edbfbd2a3b7/\u5188\u8428\u96f7\u65af\u6570\u5b57\u56fe\u50cf\u5904\u7406\u6e90\u4ee3\u7801/im2jpeg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6856714814487676}} {"text": "% test for denoising\n\n\n\nname = 'lena';\nname = 'peppers';\nname = 'boat';\nname = 'lena';\nname = 'polygons_blurred';\nname = 'barb';\n\nn = 128*2;\nM = load_image(name);\neta = 0.12;\nc = size(M)/2;\n% c = [120 200]; % lena hat\nM0 = rescale( M(c(1)-n/2+1:c(1)+n/2,c(2)-n/2+1:c(2)+n/2 ), eta, 1-eta );\n\n% add some noise\nsigma = 0.04 * max( M0(:) );\nrandn('state',1234); % to have reproductible results\nM = M0 + randn(n)*sigma;\n\noptions.sigma = sigma;\noptions.repres2 = 'daub3';\noptions.parent = 1;\nM1 = perform_blsgsm_denoising(M, options);\n\npnoisy = psnr(M,M0);\npwav = psnr(M0,M1);\n\ndisplay_image_layout({M0 M M1}, ...\n {'Original' sprintf('Noisy,psnr=%.2f', pnoisy) sprintf('Denoised,psnr=%.2f', pwav) });", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_wavelets/tests/test_denoising_blsgsm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6856714814487674}} {"text": "function [A, B, C, D] = Digital2Analog(Ap, Bp, Cp, Dp)\n\n% Digital2Analog: bilinear transformation of a discrete system P to analog\n% domain \n%\n% Usage: [A, B, C, D] = Digital2Analog(Ap, Bp, Cp, Dp)\n%\n% INPUTS: state space matrices of the input discrete system P\n%\n% OUTPUT: state space matrices of the output analog system\n%\n% See also: designIIR, Analog2Digital\n\nS = inv(eye(size(Ap,1)) + Ap);\n\nA = (Ap - eye(size(Ap,1))) * S;\nB = (eye(size(A))-A) * Bp;\nC = Cp * S;\nD = Dp - C * Bp;\n\nsys = ss(A,B,C,D);\nsys = sminreal(sys);\n\n[A, B ,C ,D] = ssdata(sys);", "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/22472-hybrid-filter-banks-with-fractional-delays-minimax-design-and-applications-to-multichannel-sampling/HybridFBwFractionalDelays/Digital2Analog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6856262839571886}} {"text": "%The aim of this simple benchmark is to illustrate the interest of restarting\n%Nelder-Mead locally, from the last solution found, until no improvement is\n%reached (to a given accuracy).\n%Moreover, it shows that fminsearch has great difficulties at minimizing\n%the most simple, smooth quadractic, objective function used. But\n%restarting it locally corrects that.\n%On the other hand, Nick Higham implementation of Nelder-Mead works fine,\n%and the accuracy reached is also further improved by restarting it\n%locally. Note that it may still happen that fminsearch performs better on\n%other problems.\n\n%Anyhow in theory, amongst direct search methods, one should not use even\n%the restarted NM but rather MADS (C. Audet, J.E. Dennis, S. Le Digabel), which has \n%guaranteed convergence even on non-smooth Clarke subdifferentiable objective functions.\n%The restarted NM will also lead in practice to locally optimal solutions,\n%although this is not theoretically guaranteed. It may fail in very\n%particular of difficult situations. The reason for its good convergence\n%properties in practice is that restarting it regenerates its search\n%simplex and in the end many search directions are covered, which is a crude \n%alternative to the POLL step of MADS (which is the step ensuring\n%convergence). So the restarted NM will perform well even on non-smooth or\n%discontinuous objective functions (not illustrated with this benchmark, \n%other benchmarks are available on http://arxiv.org/abs/1104.5369).\n%We put forward the restarted NM since it is easily available, and simple\n%to use and will already work well enough in practice. But again, in\n%theory, MADS should be used instead (to get a convergence certificate).\n\n%For related works on optimization in systems and control, see the Matlab\n%files http://www.mathworks.com/matlabcentral/fileexchange/33022 and\n%http://www.mathworks.com/matlabcentral/fileexchange/33219 (and hyperlinked papers).\n\n%Emile Simon, 18th october 2011\n\nclear all\nclose all\nclc\n\n%Choice of the accuracies\nprecf = 10^-4;%'Objective' accuracy\nprecx = 10^-4;%'Simplex' accuracy\nprecs = 10^-4;%'Restarting' accuracy\nNmax = 20;%Number of variables tried% To be changed.\nntests = 10;%Number of tests for each N\ndisp = 0; %Turn to 1 to display the detail of the iterations of Nelder-Mead\nif(disp==1) Disp = 'iter'; else Disp = 'off'; end\n\nObjectif = @(x)sum(x.^2);%The objective function to be minimized, smooth quadratic. Perhaps the simplest objective function possible.\n%func='sq';\n\noptions = optimset('TolF',precf,'TolX',precx,'MaxFunEvals',inf,'MaxIter',inf,'Display','off');%,'GradObj','on');%,'TolCon',precx\n\nfor s=2:Nmax\n for i =1:ntests\n\n x0=randn(s,1)./rand(s,1);%Difficult starting point\n\n tic\n [Sol1,Obj1(s,i)] = fminsearch(Objectif,x0,optimset('TolF',precf,'TolX',precx,'MaxFunEvals',inf,'MaxIter',inf,'Display',Disp));\n T1(s,i) = toc;\n\n acc = 1; Obj2(s,i) = Obj1(s,i); Sol2=Sol1;\n while (acc>precs)\n Objp(s,i) = Obj2(s,i);\n [Sol2,Obj2(s,i)] = fminsearch(Objectif,Sol2,optimset('TolF',precf,'TolX',precx,'MaxFunEvals',inf,'MaxIter',inf,'Display',Disp));\n acc = abs(abs(Objp(s,i)/Obj2(s,i))-1);\n end\n T2(s,i) = toc;\n\n %Nick Higham's implementation of Nelder-Mead\n tic\n [Sol3,Obj3(s,i),N3(s,i)]=nmsmax(@(x)-sum(x.^2),x0,[precx inf inf 0 disp]);\n T3(s,i) = toc;\n Obj3(s,i) = -Obj3(s,i);\n\n acc = 1; Obj4(s,i) = Obj3(s,i); Sol4=Sol3;\n while (acc>precs)\n Objp = Obj4(s,i);\n [Sol4,Obj4(s,i)] = nmsmax(@(x)-sum(x.^2),Sol4,[precx inf inf 0 disp]);\n T4(s,i)=toc;\n Obj4(s,i) = -Obj4(s,i);\n acc = Objp/Obj4(s,i)-1;\n end\n\n \n\n end\n s\nend\n\nfigure\nsubplot(2,1,1)\nsemilogy(mean(Obj1'))\nhold on\nerrorbar(mean(Obj1'),std(Obj1'))\nerrorbar(mean(Obj2'),std(Obj2'),'g')\nerrorbar(mean(Obj3'),std(Obj3'),'r')\nerrorbar(mean(Obj4'),std(Obj4'),'c')\nlegend('fminsearch','fminsearch','restarted fminsearch','nmsmax','restared nmsmax','Location','NorthWest')\ntitle('Performance comparison of different versions of Nelder-Mead on \\bf{min \\Sigma_{i=1}^nx_i^2}')\nylabel('Avg. objective value')\nsubplot(2,1,2)\nsemilogy(mean(T1'))\nhold on\nerrorbar(mean(T1'),std(T1'))\nerrorbar(mean(T2'),std(T2'),'g')\nerrorbar(mean(T3'),std(T3'),'r')\nerrorbar(mean(T4'),std(T4'),'c')\nylabel('Avg. computational time required (s)')\nxlabel('Number of variables (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/33328-improving-the-convergence-of-nelder-mead-and-so-fminsearch/BenchmarkXSquared.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.6856185077471966}} {"text": "function w = rotation_mat_vector_3d ( a, v )\n\n%*****************************************************************************80\n%\n%% ROTATION_MAT_VECTOR_3D applies a marix rotation to a vector in 3d.\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% Parameters:\n%\n% Input, real A(3,3), the matrix defining the rotation.\n%\n% Input, real V(3), the vector to be rotated.\n%\n% Output, real W(3), the rotated vector.\n%\n dim_num = 3;\n%\n% We want V to be a ROW vector.\n% If MATLAB idiocies make it look like a COLUMN vector, please fix that.\n%\n if ( size ( v, 2 ) == 1 )\n v = v';\n end\n \n w(1:dim_num) = a(1:dim_num,1:dim_num) * v(1: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/rotation_mat_vector_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.6856185072602065}} {"text": "function [ a, seed ] = d3_uniform ( n, seed )\n\n%*****************************************************************************80\n%\n%% D3_UNIFORM randomizes a D3 matrix.\n%\n% Discussion:\n%\n% The D3 storage format is used for a tridiagonal matrix.\n% The superdiagonal is stored in entries (1,2:N), the diagonal in\n% entries (2,1:N), and the subdiagonal in (3,1:N-1). Thus, the\n% original matrix is \"collapsed\" vertically into the array.\n%\n% Example:\n%\n% Here is how a D3 matrix of order 5 would be stored:\n%\n% * A12 A23 A34 A45\n% A11 A22 A33 A44 A55\n% A21 A32 A43 A54 *\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 January 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the linear system.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real A(3,N), the D3 matrix.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n a(1,1) = 0.0;\n [ a(1,2:n), seed ] = r8vec_uniform ( n-1, 0.0, 1.0, seed );\n\n [ a(2,1:n), seed ] = r8vec_uniform ( n, 0.0, 1.0, seed );\n\n [ a(3,1:n-1), seed ] = r8vec_uniform ( n-1, 0.0, 1.0, seed );\n a(3,n) = 0.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/spline/d3_uniform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.6856185033877176}} {"text": "function x = l_polynomial_zeros ( n )\n\n%*****************************************************************************80\n%\n%% L_POLYNOMIAL_ZEROS: zeros of the Laguerre polynomial L(n,x).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 March 2012\n%\n% Author:\n%\n% John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer N, the order of the polynomial.\n%\n% Output, real X(N), the zeros.\n%\n\n%\n% Define the zero-th moment.\n%\n zemu = 1.0;\n%\n% Define the Jacobi matrix.\n%\n b = zeros ( n, 1 );\n for i = 1 : n\n bj(i) = i;\n end\n\n x = zeros ( n, 1 );\n for i = 1 : n\n x(i) = 2 * i - 1;\n end\n\n w = zeros ( n, 1 );\n w(1) = sqrt ( zemu );\n%\n% Diagonalize the Jacobi matrix.\n%\n [ x, w ] = imtqlx ( n, x, bj, w );\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/laguerre_polynomial/l_polynomial_zeros.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.6856184912832602}} {"text": "function [Pro,Res] = interpolationAMGn(A,isC) \n%% INTERPOLATIONAMGS construct prolongation and restriction matrices\n%\n% [Pro,Res] = interpolatoinAMGs(A,isC) construct prolongation and\n% restriction matrices use standard matrix-dependent interpolation. \n\n% In the input, A is a SPD matrix and isC is a logical array to indicate\n% nodes in coarse matrix. In the output Pro and Res are prolongation and\n% restriction matrices satisfying Res = Pro'.\n%\n% Example\n% load lakemesh\n% A = assemblematrix(node,elem);\n% [isC,As] = coarsenAMGc(A);\n% [Ac,Pro,Res] = interpolatoinAMGs(As,isC);\n%\n% See also: coarsenAMGc, amg\n% \n% New interpolation added by Xiaozhe Hu. 12/10/2011.\n\n\nN = size(A,1);\n\n%% Index map between coarse grid and fine grid\nallNode = (1:N)'; \nfineNode = allNode(~isC);\nNf = length(fineNode); \nNc = N-length(fineNode);\ncoarseNode = (1:Nc)'; % coarse node index\ncoarse2fine = find(isC); % coarse node index in the fine grid\n% fine2coarse(isC) = coarseNode;\nip = coarse2fine; % coarse node index in the fine grid\njp = coarseNode; % coarse node index\nsp = ones(Nc,1); % identity matrix for coarse nodes in the fine grid\n\n%% Construct prolongation and restriction operator\nAfc = A(fineNode, coarse2fine);\nDsum = spdiags(A(fineNode,fineNode),0);\nalpha = (sum(A(fineNode,:),2) - Dsum)./sum(Afc,2);\nDsum = spdiags(((-1).*alpha)./Dsum, 0, Nf, Nf); \n[ti,tj,tw] = find(Dsum*Afc);\nip = [ip; fineNode(ti)]; % fine node index\njp = [jp; tj]; % coarse node index\nsp = [sp; tw]; % weight\nPro = sparse(ip,jp,sp,N,Nc);\nRes = Pro';", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/solver/interpolationAMGn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6855390912622549}} {"text": "%% IPOPT PARFOR testing\nclc\nclear all\n\n%Objective\nfun = @(x) 20 + x(1)^2 + x(2)^2 - 10*(cos(2*pi*x(1)) + cos(2*pi*x(2)));\n%Constraints\nlb = [5*pi;-20*pi];\nub = [20*pi;-4*pi];\n%Setup Options\nopts = optiset('solver','ipopt');\nOpt = opti('fun',fun,'bounds',lb,ub,'opts',opts);\n\n%Generate a series of starting points\nn = 1000;\nX0 = [linspace(lb(1),lb(end),n); linspace(ub(1),ub(end),n)];\n\n%Preallocate solution vector\nsols = zeros(2,n);\nsolp = zeros(2,n);\n\n%% run serial (8.17s)\ntic\nfor i = 1:n\n sols(:,i) = solve(Opt,X0(:,i));\nend\ntoc\n\n%%\nparpool(4);\n\n%% run parfor (2.6s)\ntic\nparfor i = 1:n\n solp(:,i) = solve(Opt,X0(:,i));\nend\ntoc\n\n%% check results\nerr = norm(sols-solp)", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/math/opti/Test Problems/Development/test_ipopt_parfor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7577943712746407, "lm_q1q2_score": 0.6855390795739421}} {"text": "\n%Plot the original STL mesh:\nfigure\n[stlcoords] = READ_stl('sample.stl');\nxco = squeeze( stlcoords(:,1,:) )';\nyco = squeeze( stlcoords(:,2,:) )';\nzco = squeeze( stlcoords(:,3,:) )';\n[hpat] = patch(xco,yco,zco,'b');\naxis equal\n\n%Voxelise the STL:\n[OUTPUTgrid] = VOXELISE(100,100,100,'sample.stl','xyz');\n\n%Show the voxelised result:\nfigure;\nsubplot(1,3,1);\nimagesc(squeeze(sum(OUTPUTgrid,1)));\ncolormap(gray(256));\nxlabel('Z-direction');\nylabel('Y-direction');\naxis equal tight\n\nsubplot(1,3,2);\nimagesc(squeeze(sum(OUTPUTgrid,2)));\ncolormap(gray(256));\nxlabel('Z-direction');\nylabel('X-direction');\naxis equal tight\n\nsubplot(1,3,3);\nimagesc(squeeze(sum(OUTPUTgrid,3)));\ncolormap(gray(256));\nxlabel('Y-direction');\nylabel('X-direction');\naxis equal tight\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/27390-mesh-voxelisation/Mesh_voxelisation/VOXELISE_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541593883189, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6855011093948923}} {"text": "function pass = test_compose(pref)\n% Test COMPOSE().\n\nif ( nargin == 0 )\n pref = chebfunpref; \nend\ntol = 1e3*pref.cheb2Prefs.chebfun2eps;\n\nF = spherefunv(@(x,y,z) x, @(x,y,z) y, @(x,y,z) z);\ng = chebfun3(@(x,y,z) x + y + z);\nh_true = spherefun(@(x,y,z) x + y + z);\nh = compose(F, g);\npass(1) = ( norm(h - h_true) < tol );\n\nG = chebfun3v(@(x,y,z) x, @(x,y,z) y, @(x,y,z) z);\nH_true = spherefunv(@(x,y,z) x, @(x,y,z) y, @(x,y,z) z);\nH = compose(F, G);\npass(2) = ( norm(H - H_true) < tol );\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/tests/spherefunv/test_compose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6854898611095186}} {"text": "function h = circle(x,y,r)\nhold on\nth = 0:pi/50:2*pi;\nxunit = r * cos(th) + x;\nyunit = r * sin(th) + y;\nh = plot(xunit, yunit);\nhold off\n", "meta": {"author": "deng-haoyang", "repo": "ParNMPC", "sha": "ddbe418e630b49897e8bc17e5c2f9e1ef1ab453b", "save_path": "github-repos/MATLAB/deng-haoyang-ParNMPC", "path": "github-repos/MATLAB/deng-haoyang-ParNMPC/ParNMPC-ddbe418e630b49897e8bc17e5c2f9e1ef1ab453b/Vehicle/circle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.685445622992732}} {"text": "function y=dbp(x)\n% dbp(x) = 10*log10(x): the dB equivalent of the power x\ny = -Inf*ones(size(x));\nnonzero = x~=0;\ny(nonzero) = 10*log10(abs(x(nonzero)));\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/15417-successive-approximation-adc/dbp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.685445614113246}} {"text": "classdef factorization_dense_lu < factorization_generic\n%FACTORIZATION_DENSE_LU dense LU factorization: p*A = L*U\n\n% Copyright 2009, Timothy A. Davis, University of Florida\n\n methods\n\n function F = factorization_dense_lu (A)\n %FACTORIZATION_DENSE_LU dense LU: p*A = L*U\n n = size (A,2) ;\n [F.L U p] = lu (A, 'vector') ;\n assert (nnz (diag (U)) == n, 'Matrix is rank deficient.') ;\n F.p = sparse (1:n, p, 1) ;\n F.U = U ;\n F.A = A ;\n end\n\n function disp (F)\n %DISP displays a dense LU factorization\n fprintf (' dense LU factorization: p*A = L*U\\n') ;\n fprintf (' A:\\n') ; disp (F.A) ;\n fprintf (' L:\\n') ; disp (F.L) ;\n fprintf (' U:\\n') ; disp (F.U) ;\n fprintf (' p:\\n') ; disp (F.p) ;\n fprintf (' is_inverse: %d\\n', F.is_inverse) ;\n end\n\n function x = mldivide_subclass (F,b)\n %MLDIVIDE_SUBCLASS x=A\\b using dense LU\n % x = U \\ (L \\ (p*b)) ;\n if (issparse (b))\n b = full (b) ;\n end\n opL.LT = true ;\n opU.UT = true ;\n x = linsolve (F.U, linsolve (F.L, F.p*b, opL), opU) ;\n end\n\n function x = mrdivide_subclass (b,F)\n %MRDIVIDE_SUBCLASS x = b/A using dense LU\n % x = (P' * (L' \\ (U' \\ b')))'\n bT = b' ;\n if (issparse (bT))\n bT = full (bT) ;\n end\n opUT.UT = true ;\n opUT.TRANSA = true ;\n opLT.LT = true ;\n opLT.TRANSA = true ;\n x = (F.p' * linsolve (F.L, linsolve (F.U, bT, opUT), opLT))' ;\n end\n end\nend\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/external/Factorize/Factorize/factorization_dense_lu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.6854456077682877}} {"text": "%MEANC Mean combining classifier\n% \n% W = MEANC(V)\n% W = V*MEANC\n%\n% INPUT\n% V Set of classifiers (optional)\n%\n% OUTPUT\n% W Mean combiner\n%\n% DESCRIPTION\n% If V = [V1,V2,V3, ... ] is a set of classifiers trained on the same\n% classes and W is the mean combiner: it selects the class with the mean of\n% the outputs of the input classifiers. This might also be used as\n% A*[V1,V2,V3]*MEANC in which A is a dataset to be classified.\n% \n% If it is desired to operate on posterior probabilities then the input\n% classifiers should be extended like V = V*CLASSC;\n%\n% For affine mappings the coefficients may be averaged instead of the\n% classifier results by using AVERAGEC.\n% \n% The base classifiers may be combined in a stacked way (operating in the\n% same feature space by V = [V1,V2,V3, ... ] or in a parallel way\n% (operating in different feature spaces) by V = [V1;V2;V3; ... ]\n%\n% EXAMPLES\n% PREX_COMBINING\n%\n% SEE ALSO (PRTools Guide)\n% MAPPINGS, DATASETS, VOTEC, MAXC, MINC, MEDIANC, PRODC,\n% AVERAGEC, STACKED, PARALLEL\n\n% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com\n% Faculty EWI, Delft University of Technology\n% P.O. Box 5031, 2600 GA Delft, The Netherlands\n\n% $Id: meanc.m,v 1.3 2010/06/01 08:48:55 duin Exp $\n\nfunction w = meanc(p1)\n\n\ttype = 'mean'; % define the operation processed by FIXEDCC.\n\tname = 'Mean combiner'; % define the name of the combiner.\n\n\t% this is the general procedure for all possible\n\t% calls of fixed combiners handled by FIXEDCC\n\tif nargin == 0\n\t\tw = prmapping('fixedcc','combiner',{[],type,name});\n\telse\n\t\tw = fixedcc(p1,[],type,name);\n\tend\n\n\tif isa(w,'prmapping')\n\t\tw = setname(w,name);\n\tend\n\n\treturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/meanc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6854456058659523}} {"text": "function [Cp1,Cp2] = Cpre_q1q1(xy,ev)\n%Cpre_q1q1 generate stabilizations for least sqrs commutator for Q1-Q1 \n% [Cp1,Cp2] = Cpre_q1q1(xy,ev);\n% input\n% xy Q2 nodal coordinate vector \n% ev element mapping matrix\n% output\n% Cp1 pressure stabilization 1 for preconditioner\n% Cp2 pressure stabilization 2 for preconditioner\n% IFISS function: HCE; 7 July 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \n\nnngpt=4; \nx=xy(:,1); y=xy(:,2);\nxp=xy(:,1); yp=xy(:,2);\nnvtx=length(x); nu=2*nvtx; np=length(xp); \nnel=length(ev(:,1)); \n%\n% initialise global matrices\nCp1 = sparse(np,np);\nCp2 = sparse(np,np);\n%\n% Gauss point integration rules\nif (nngpt==4) % 2x2 Gauss points\n gpt=1.0e0/sqrt(3.0e0);\n s(1) = -gpt; t(1) = -gpt; wt(1)=1;\n s(2) = gpt; t(2) = -gpt; wt(2)=1;\n s(3) = gpt; t(3) = gpt; wt(3)=1; \n s(4) = -gpt; t(4) = gpt; wt(4)=1;\nelseif (nngpt==1) % 1x1 Gauss point\n s(1) = 0; t(1) = 0; wt(1)=4;\nelse\n error('Check Gauss point integration specification')\nend\n%\n% inner loop over elements \nfor ivtx = 1:4\n xl_v(:,ivtx) = x(ev(:,ivtx));\n yl_v(:,ivtx) = y(ev(:,ivtx)); \nend\n\n% \n% element assembly into global matrices\ncpe1 = zeros(nel,4,4);\ncpe2 = zeros(nel,4,4);\n \n% loop over Gauss points\nfor igpt = 1:nngpt\n sigpt=s(igpt);\n tigpt=t(igpt);\n wght=wt(igpt);\n [jac,invjac,phi,dphidx,dphidy] = deriv(sigpt,tigpt,xl_v,yl_v);\n for j = 1:4\n for i = 1:4\n cpe1(:,i,j) = cpe1(:,i,j) + .25 * wght*(phi(:,i)-0.25) .*(phi(:,j)-0.25) ;\n cpe2(:,i,j) = cpe2(:,i,j) + (16*jac(:)) .\\ (wght*(phi(:,i)-0.25) .*(phi(:,j)-0.25));\n end\n end\n% end of Gauss point loop\nend \n\n%% element assembly into global matrices\nfor krow=1:4\n nrow=ev(:,krow);\t \n for kcol=1:4\n ncol=ev(:,kcol);\t \n Cp1 = Cp1 + sparse(nrow,ncol,cpe1(:,krow,kcol),nvtx,nvtx);\n Cp2 = Cp2 + sparse(nrow,ncol,cpe2(:,krow,kcol),nvtx,nvtx);\n end\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/toms866/navier_flow/Cpre_q1q1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.7905303236047048, "lm_q1q2_score": 0.6854180679214624}} {"text": "%%***********************************************************\n%% lmiexamp1: generate SDP data for the following LMI problem\n%%\n%% max -eta\n%% s.t. B*P + P*B' <= 0\n%% -P <= -I \n%% P - eta*I <= 0\n%% P(1,1) = 1\n%%***********************************************************\n%% Here is an example on how to use this function to \n%% find an optimal P. \n%%\n%% B = [-1 0 0; 5 -2 0; 1 1 -1];\n%% [blk,At,C,b] = lmiexamp1(B);\n%% [obj,X,y,Z] = sqlp(blk,At,C,b);\n%% P = smat(blk(1,:),y); \n%%*****************************************************************\n%% SDPT3: version 4.0\n%% Copyright (c) 1997 by\n%% Kim-Chuan Toh, Michael J. Todd, Reha H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%*****************************************************************\n\n function [blk,At,C,b] = lmiexamp1(B); \n\n n = length(B); n2 = n*(n+1)/2; \n I = speye(n); \n z0 = sparse(n2,1); \n blktmp{1,1} = 's'; blktmp{1,2} = n;\n%%\n blk{1,1} = 's'; blk{1,2} = n;\n blk{2,1} = 's'; blk{2,2} = n;\n blk{3,1} = 's'; blk{3,2} = n;\n blk{4,1} = 'u'; blk{4,2} = 1; \n%%\n At{1,1} = [lmifun(B,I), z0];\n At{2,1} = [lmifun(-I/2,I), z0]; \n At{3,1} = [lmifun(I/2,I), svec(blktmp,-I,1)]; \n At{4,1} = sparse([1, zeros(1,n2)]); \n%% \n C{1,1} = sparse(n,n); \n C{2,1} = -speye(n); \n C{3,1} = sparse(n,n); \n C{4,1} = 1; \n%%\n b = [zeros(n2,1); -1]; \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/SDPT3-4.0/SDPT3-4.0/Examples/lmiexamp1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6854180430673642}} {"text": "\n\nclear all; close all;\nm=256; n=256;\na=50;\nb=180;\nI=a+(b-a)*rand(m,n);\nfigure;\nsubplot(121); imshow(uint8(I));\nsubplot(122); imhist(uint8(I));\n\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/\u300aMATLAB\u56fe\u50cf\u5904\u7406\u300b\u6e90\u6587\u4ef6/\u672c\u4e66\u6e90\u6587\u4ef6/chap6/chap6_8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.685375780794809}} {"text": "clc;\nclear all;\nwarning off;\nchos=0;\npossibility=11;\n\nwhile chos~=possibility,\n chos=menu('Digital 3-level image watermarking','select the cover image','select the watermark image','show 3-level coverimage','show 3-level watermarkimage','show watermarked image','show extracted image','Calculate MSE for embedding','Calculate PSNR for embedding','Calculate MSE for extraction','Calculate PSNR for extraction','exit');\n if chos==1\n [fname pname]=uigetfile('*.jpg','select the Cover Image');\n %eval('imageinput=imread(fname)');\n imageinput=imread(fname);\n \n\nA=rgb2gray(imageinput);\nP1=im2double(A);\nP=imresize(P1,[2048 2048]);\n%imshow(P);\n%figure(1);\n%title('original image');\n\n[F1,F2]= wfilters('haar', 'd');\n[LL,LH,HL,HH] = dwt2(P,'haar','d');\n[LL1,LH1,HL1,HH1] = dwt2(LL,'haar','d');\n[LL2,LH2,HL2,HH2] = dwt2(LL1,'haar','d');\n%figure(2)\n%imshow(LL2,'DisplayRange',[]), title('3 level dwt of cover image');\n end\n if chos==2\n [fname pname]=uigetfile('*.jpg','select the Watermark');\n %eval('imageinput=imread(fname)');\n %imageinput=imread(fname);\n imw2=imread(fname);\n imw=rgb2gray(imw2);\nwatermark=im2double(imw);\nwatermark=imresize(watermark,[2048 2048]);\n%figure(3)\n%imshow(uint8(watermark));title('watermark image')\n[WF1,WF2]= wfilters('haar', 'd');\n[L_L,L_H,H_L,H_H] = dwt2(watermark,'haar','d');\n[L_L1,L_H1,H_L1,H_H1] = dwt2(L_L,'haar','d');\n[L_L2,L_H2,H_L2,H_H2] = dwt2(L_L1,'haar','d');\n%figure(4)\n%imshow(L_L2,'DisplayRange',[]), title('3 level dwt of watermark image');\n end\n if chos==3\n imshow(LL2,'DisplayRange',[]), title('3 level dwt of cover image')\n end\n if chos==4\n imshow(L_L2,'DisplayRange',[]), title('3 level dwt of watermark image')\n end\n if chos==5\n Watermarkedimage=LL2+0.0001*L_L2;\n\n\n\n%computing level-1 idwt2\nWatermarkedimage_level1= idwt2(Watermarkedimage,LH2,HL2,HH2,'haar');\n%figure(5)\n%imshow(Watermarkedimage_level1,'DisplayRange',[]), title('Watermarkedimage level1');\n\n%computing level-2 idwt2\nWatermarkedimage_level2=idwt2(Watermarkedimage_level1,LH1,HL1,HH1,'haar');\n%figure(6)\n%imshow(Watermarkedimage_level2,'DisplayRange',[]), title('Watermarkedimage level2');\n\n\n%computing level-3 idwt2\nWatermarkedimage_final=idwt2(Watermarkedimage_level2,LH,HL,HH,'haar');\n%figure(7)\nimshow(Watermarkedimage_final,'DisplayRange',[]), title('Watermarkedimage final')\n end\n if chos==6\n [F11,F22]= wfilters('haar', 'd');\n[a b c d]=dwt2(Watermarkedimage_final,'haar','d');\n[aa bb cc dd]=dwt2(a,'haar','d');\n[aaa bbb ccc ddd]=dwt2(aa,'haar','d');\n\nrecovered_image=aaa-LL2;\n%figure(8)\nimshow(recovered_image,[]);\n%title('extracted watermark')\n end\n if chos==7\n \n pic1= P;\n pic2= Watermarkedimage_final;\n mse=MSE(pic1,pic2)\n end\n if chos==8\n pic1= P;\n pic2= Watermarkedimage_final;\npsnr=PSNR(pic1,pic2)\n end\n if chos==9\n clear pic1;\n clear pic2;\n pic1=L_L2;\n pic2=recovered_image;\n mse_extraction=MSE(pic1,pic2)\n end\n if chos==10\n psnr_extraction=PSNR(pic1,pic2)\n end\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/41825-watermarking-gui-using-3rd-level-dwt/Watermarking/GUI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6853406151632255}} {"text": "function F=FPolarCoordTurn2D(T,x,turnType,discPoint,tauTurn,tauLinAccel)\n%%FPOLARCOORDTURN2D The state transition matrix for a two-dimensional\n% coordinated turn model where the velocity is specified in\n% terms of a heading and a speed. The turn rate can be\n% specified in terms of a turn rate in radians per second, or\n% in terms of a transversal acceleration. Additionally, a\n% linear acceleration can be given. The turn rate and linear\n% acceleration can optionally have time constants associated\n% with them, like in the Singer model, modelling a tendancy to\n% eventually want to return to non-accelerating, straight-line\n% motion.\n%\n%INPUTS: T The time-duration of the propagation interval in seconds.\n% x The target state for 2D motion where the velocity is given in\n% terms of heading and speed components. If there is no linear\n% acceleration (acceleration along the direction of motion), then\n% x can either be x=[x;y;h;v;omega], where h is the heading in\n% terms of radians counterclockwise from the x-axis, v is the\n% speed, and omega is the turn rate (the derivative of h with\n% respect to time) or x=[x;y;h;v;at] where at is the transversal\n% acceleration, which is orthogonal to the velocity and is defined\n% such that positive values of at map to positive values of omega.\n% If there is a linear acceleration, then the target state is\n% either x=[x;y;h;v;omega;al] where omega is the turn rate and al\n% is the linear acceleration or the target state is\n% x=[x;y;h;v;at;al] if the turn is expressed in terms of a\n% transversal acceleration. The dimensionality of the state is\n% used to determine whether a linear acceleration component is\n% present. The linear acceleration component changes the speed.\n% That means that it is the derivative of the speed.\n% turnType A string specifying whether the turn is given in terms of a\n% turn rate in radians per second or a transversal acceleration in\n% m/s^2. Possible values are\n% 'TurnRate' The turn is specified in terms of a turn rate\n% (The default if this parameter is omitted).\n% 'TransAccel' The turn is specified in terms of a transversal\n% acceleration.\n% discPoint This optional parameter specified what value of the turn rate\n% is used for the discretized state prediction. The three possible\n% values were suggested in Li's paper, [3]. Possible values are:\n% 0 (The default if omitted) use omega=x(5), or the equivalent\n% value when specifying the turn rate using a transverse\n% acceleration, from the non-predicted target state for\n% building the state transition matrix. \\omega_k\n% 1 Use the average value of the predicted omega (or the average\n% value of the transverse acceleration) over the interval T\n% for building the state transition matrix. \\bar{\\omega}\n% 2 Use the approximate average value of the predicted omega\n% over the interval T for building the state transition\n% matrix. \\bar{\\omega} This is the suggestion of using half\n% the prior and prediction, as was given in Li's paper. When\n% given a transverse acceleration instead of a turn rate, half\n% of the prior and predicted accelerations is used.\n% 3 Use the forward-predicted omega (or transverse acceleration)\n% for building the state transition matrix. \\omega_{k+1}\n% tauTurn The correlation time constant for the turn rate in seconds.\n% tau must be positive but does not have to be finite. If this\n% parameter is omitted, then tauTurn is set to infinity.\n% tauLinAccel The correlation time constant for the linear acceleration (if\n% present) in seconds. This parameter is not needed if there is\n% no linear acceleration. If a linear acceleration is present\n% and this parameter is omitted, then tauLinAccel is set to\n% infinity.\n%\n%OUTPUT: F The state transition matrix under a possibly linearlly\n% accelerating coordinated turn model where the velocity is given\n% by a heading and a speed.\n%\n%The state transition matrix is, in part, a realization of the unnumered\n%transition Equation after equation 1b in [1], which comes from the initial\n%derivation in [2], where a different definition of heading direction is\n%used. Note that the order of the components in the state here is different\n%than the ordering of the components in Blackman's paper. Also, Blackman's\n%paper does not consider linear acceleration terms.\n%\n%Despite the form of the transition matrix without a linear acceleration\n%term, the result is mathematically equivalent to equation 75 in [3]. After\n%being modified to account for a decaying turn rate. It is assumed that the\n%continuous-time turn rate model is\n%omegaDot=-(1/tauTurn)*omega+noise, which discretizes to\n%omega[k+1]=exp(-T/tauTurn)*omega[k]+noise.\n%Analogously, the optional linear acceleration discretizes to\n%al[k+1]=exp(-T/tauLinAccel)*al[k]+noise\n%\n%More information on discrete-time turning models is given in the comments\n%to the function FCoordTurn2D.\n%\n%This state transition matrix goes with the process noise covariance matrix\n%given by QPolarCoordTurn2D.The corresponding continuous-time drift\n%function are aPolarCoordTurn2DOmega and aPolarCoordTurn2Dtrans with the\n%diffusion matrix DPolarCoordTurn2D. Note that this model is a direct-\n%discrete-time model and is not just a discretization of the continuous-\n%time model.\n%\n%REFERENCES:\n%[1] M. Busch and S. Blackman, \"Evaluation of IMM filtering for an air\n% defense system application,\" in Proceedings of SPIE: Signal and Data\n% Processing of Small Targets, vol. 2561, 9 Jul. 1995, pp. 435-447.\n%[2] J. L. Gertz, \"Multisensor surveillance for improved aircraft\n% tracking,\" The Lincoln Laboratory Journal, vol. 2, no. 3, pp. 381-396,\n% 1989.\n%[3] X. R. Li and V. P. Jilkov, \"Survey of maneuvering target tracking.\n% Part I: Dynamic models,\" IEEE Transactions on Aerospace and Electronic\n% Systems, vol. 39, no. 4, pp. 1333-1364, Oct. 2003.\n%\n%July 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%The time constant for the linear acceleration.\nif(nargin<6)\n tauLinAccel=Inf;\nend\n\n%The time constant for the turn.\nif(nargin<5)\n tauTurn=Inf;\nend\n\nif(nargin<4)\n discPoint=0;\nend\n\nif(nargin<3)\n turnType='TurnRate';\nend\n\nbeta=exp(-T/tauTurn);\nswitch(discPoint)\n case 0%Use the prior value of at/omega for the linearization.\n turnVal=x(5);\n case 1\n %Use the average value of at.omega over the prediction\n %interval for the linearization.\n tau=param3;\n turnVal0=x(5);\n turnVal=(tau-beta*tau+T*turnVal0)/T;\n\n %Assume tau=Inf or T=0 was used, in which case the\n %asymptotic average value of at/omega should be used.\n if(~isfinite(tauTurn)||~isfinite(turnVal))\n turnVal=turnVal0;\n end\n case 2%Use the simple mean of at/omega for the linearization.\n turnVal=(beta+1)*x(5)/T;\n case 3%Use the predicted value of at/omega for the linearization.\n turnVal=beta*x(5);\n otherwise\n error('Invalid value entered for discPoint');\nend\n\nv=x(4);%The speed\n\nswitch(turnType)\n case 'TransAccel'%The turn is expressed in terms of a transverse\n %acceleration. \n \n omega=turnVal/v;\n if(~isfinite(omega))%Deal with zero velocity.\n omega=0;\n end\n case 'TurnRate'%The turn is expressed in terms of a turn rate.\n omega=turnVal;\n otherwise\n error('Unknown turn type specified.');\nend\n%We now have the omega term for the turn.\n\ntheta=x(3);%The heading (counterclockwise from the x axis).\n\nsinHead=sin(theta);\ncosHead=cos(theta);\n\nsinVal=sin(omega*T);\ncosVal=cos(omega*T);\n\nsinRat=sinVal/omega;\nif(~isfinite(sinRat))\n sinRat=T;%The limit as omega goes to zero.\nend\ncosRat=(1-cosVal)/omega;\nif(~isfinite(cosRat))\n cosRat=0;%The limit as omega goes to zero.\nend\n\nswitch(turnType)\n case 'TransAccel'%The turn is expressed in terms of a transverse\n F=[1,0,0,cosHead*sinRat-sinHead*cosRat,0;%The x-component.\n 0,1,0,sinHead*sinRat+cosHead*cosRat,0;%The y-component.\n 0,0,1,0, T/v;%The heading component.\n 0,0,0,1, 0;%The speed component\n 0,0,0,0, beta];%The transverse accel component.\n case 'TurnRate'\n F=[1,0,0,cosHead*sinRat-sinHead*cosRat,0;%The x-component.\n 0,1,0,sinHead*sinRat+cosHead*cosRat,0;%The y-component.\n 0,0,1,0, T;%The heading component.\n 0,0,0,1, 0;%The speed component\n 0,0,0,0, beta];%The turn rate component.\nend\nif length(x)==6\n betaLinAccel=exp(-T/tauLinAccel);\n F(4,6)=T;\n F(6,6)=betaLinAccel;\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/Dynamic_Models/Discrete_Time/State_Transition_Matrices/FPolarCoordTurn2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336302, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6853406101279459}} {"text": "function model = svmTrain(X, Y, opts)\n % trains an SVM using minFunc\n % X is NxD features\n % Y is discrete array of labels that must (for now) be 1...K\n \n % opts.type specifies which method to use. \n % 1= linear SVM\n % 2= polynomial Kernel SVM of order opts.polyOrder\n % 3= rbf Kernel SVM with scale parameter opts.rbfScale\n % the scale is used in equation Z = 1/sqrt(2*pi*sigma^2);\n % to scale the output of the exponential, where sigma is the scale\n % 4= l2svm, which unlike normal svm uses squared hinge loss\n \n % model is to be plugged in to yhat = svmTest(model, X)\n \n % TODO: Support labels that are not in 1..K\n % TODO: n-fold Cross validation support\n \n addOnes= false;\n C= 1;\n type= 1;\n rbfScale= 1;\n polyOrder= 2;\n if nargin < 3, opts= struct; end\n if isfield(opts, 'addOnes'), addOnes= opts.addOnes; end\n if isfield(opts, 'C'), C= opts.C; end\n if isfield(opts, 'type'), type= opts.type; end\n if isfield(opts, 'rbfScale'), rbfScale= opts.rbfScale; end\n if isfield(opts, 'polyOrder'), polyOrder= opts.polyOrder; end\n \n if(addOnes), X= [X, ones(size(X,1), 1)]; end\n \n [N, D]= size(X);\n u= unique(Y);\n K = length(u);\n \n minFuncOpts= struct;\n minFuncOpts.display= 0;\n \n if type == 1\n \n % Linear SVM\n funObj = @(w) SSVMMultiLoss(w, X, Y, K);\n wLinear = minFunc(@penalizedL2, zeros(D*K,1), minFuncOpts, funObj, C);\n model.w = reshape(wLinear,[D K]);\n\n elseif type == 2\n \n % Polynomial SVM\n Kpoly = kernelPoly(X, X, polyOrder);\n funObj = @(v) SSVMMultiLoss(v, Kpoly, Y, K);\n uPoly = minFunc(@penalizedKernelL2_matrix, randn(N*K,1), minFuncOpts, Kpoly, K, funObj, C);\n model.X = X; % must save all the training data... (ok only support vectors, todo)\n model.uPoly= reshape(uPoly, [N, K]);\n model.polyOrder= polyOrder;\n \n elseif type == 3\n \n % RBF SVM\n Krbf = kernelRBF(X, X, rbfScale);\n funObj = @(v) SSVMMultiLoss(v, Krbf, Y, K);\n uRBF = minFunc(@penalizedKernelL2_matrix, randn(N*K,1), minFuncOpts, Krbf, K, funObj, C);\n model.X = X; % must save all the training data... (ok only support vectors, todo)\n model.urbf= reshape(uRBF,[N, K]);\n model.rbfScale= rbfScale;\n \n elseif type == 4\n \n % L2 SVM (squares the slack variables, i.e. squared hinge loss)\n funObj = @(v) l2svmloss(v, X, Y, K, C);\n wLinear = minFunc(@penalizedL2, zeros(D*K,1), minFuncOpts, funObj, C);\n model.w = reshape(wLinear,[D K]);\n \n else\n \n fprintf('Unrecognized type %d, exitting...\\n', type);\n model= struct;\n return; \n \n end\n \n model.type= type;\n model.addOnes= addOnes;\n model.C= C;\n model.u= u;\n \n % 1-vs-all L2-svm loss function; similar to LibLinear.\n % Originally taken from Adam Coates' code, slightly adapted\n function [loss, g] = l2svmloss(w, X, y, K, C)\n \n [M,N] = size(X);\n theta = reshape(w, N,K);\n Y = bsxfun(@(y,ypos) 2*(y==ypos)-1, y, 1:K);\n margin = max(0, 1 - Y .* (X*theta));\n loss = (0.5 * sum(theta.^2)) + C*sum(margin.^2);\n loss = sum(loss); \n g = theta - 2 * C * (X' * (margin .* Y));\n g = g(:);\n\n", "meta": {"author": "karpathy", "repo": "Random-Forest-Matlab", "sha": "46aa3d5be31ba25364d087d3e71cdc9bd5f4de18", "save_path": "github-repos/MATLAB/karpathy-Random-Forest-Matlab", "path": "github-repos/MATLAB/karpathy-Random-Forest-Matlab/Random-Forest-Matlab-46aa3d5be31ba25364d087d3e71cdc9bd5f4de18/lib/svmTrain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6853139192108182}} {"text": "function linpack_d_test10 ( )\n\n%*****************************************************************************80\n%\n%% TEST10 tests DGEFA and DGESL.\n%\n% Discussion:\n%\n% Solve A*x = b where A is a given matrix, and B a right hand side.\n%\n% We will also assume that A is stored in the simplest\n% possible way.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 June 2009\n%\n% Author:\n%\n% John Burkardt\n%\n n = 3;\n lda = n;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST10\\n' );\n fprintf ( 1, ' For a general matrix,\\n' );\n fprintf ( 1, ' DGEFA computes the LU factors;\\n' );\n fprintf ( 1, ' DGESL solves a factored linear system;\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The number of equations is N = %d\\n', n );\n%\n% Set the values of the matrix A.\n%\n a = [ 1.0, 2.0, 3.0;\n 4.0, 5.0, 6.0;\n 7.0, 8.0, 0.0 ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The matrix A:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n for j = 1 : n\n fprintf ( 1, ' %12f', a(i,j) );\n end\n fprintf ( 1, '\\n' );\n end\n%\n% Set the values of the right hand side vector B.\n%\n b(1:3) = [ 6.0, 15.0, 15.0 ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The right hand side B is\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %12f\\n', b(i) );\n end\n%\n% Factor the matrix.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Factor the matrix\\n' );\n\n [ a, ipvt, info ] = dgefa ( a, lda, n );\n\n if ( info ~= 0 )\n fprintf ( 1, ' DGEFA returned an error flag INFO = %d\\n', info );\n return\n end\n%\n% If no error occurred, now use DGESL to solve the system.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Solve the linear system.\\n' );\n\n job = 0;\n b = dgesl ( a, lda, n, ipvt, b, job );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' DGESL returns the solution:\\n' );\n fprintf ( 1, ' (Should be (1,1,1))\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n fprintf ( 1, ' %12f\\n', b(i) );\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/linpack_d/linpack_d_test10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706733, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.685293492895844}} {"text": "function bessel_y0_int_values_test ( )\n\n%*****************************************************************************80\n%\n%% BESSEL_YO_INT_VALUES_TEST demonstrates the use of BESSEL_YO_INT_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 February 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BESSEL_YO_INT_VALUES_TEST:\\n' );\n fprintf ( 1, ' BESSEL_Y0_INT_VALUES stores values of \\n' );\n fprintf ( 1, ' the integral of the Bessel function Y0.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X FX\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, x, fx ] = bessel_y0_int_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %12f %24.16f\\n', x, fx );\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/test_values/bessel_y0_int_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.6852934912399897}} {"text": "function [ xyz, face_pointer, face_data ] = xyzf_example ( point_num, ...\n face_num, face_data_num )\n\n%*****************************************************************************80\n%\n%% XYZF_EXAMPLE sets data suitable for a pair of XYZ and XYZF files.\n%\n% Discussion:\n%\n% There are 8 points.\n% There are 6 faces.\n% There are 24 face items.\n%\n% 8------7\n% /| /|\n% / | / |\n% 5------6 |\n% | 4---|--3\n% | / | /\n% |/ |/\n% 1------2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 January 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer POINT_NUM, the number of points.\n%\n% Input, integer FACE_NUM, the number of faces.\n%\n% Input, integer FACE_DATA_NUM, the number of face items.\n%\n% Output, real XY(2,POINT_NUM), the point coordinates.\n%\n% Output, integer FACE_POINTER(FACE_NUM+1), pointers to the\n% first face item for each face.\n%\n% Output, integer FACE_DATA(FACE_DATA_NUM), indices\n% of points that form faces.\n%\n xyz(1:3,1:point_num) = [ ...\n 0.0, 0.0, 0.0; ...\n 1.0, 0.0, 0.0; ...\n 1.0, 1.0, 0.0; ...\n 0.0, 1.0, 0.0; ...\n 0.0, 0.0, 1.0; ...\n 1.0, 0.0, 1.0; ...\n 1.0, 1.0, 1.0; ...\n 0.0, 1.0, 1.0 ]';\n\n face_pointer(1:face_num+1) = [ 1, 5, 9, 13, 17, 21, 25 ];\n\n face_data(1:face_data_num) = [ ...\n 1, 4, 3, 2, ...\n 2, 3, 7, 6, ...\n 5, 6, 7, 8, ...\n 5, 8, 4, 1, ...\n 1, 2, 6, 5, ...\n 3, 4, 8, 7 ];\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/xyz_io/xyzf_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938799869521, "lm_q2_score": 0.826711791935942, "lm_q1q2_score": 0.6852934806453609}} {"text": "function f = p05_f ( m, n, x )\n\n%*****************************************************************************80\n%\n%% P05_F evaluates the objective function for problem 05.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 December 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Marcin Molga, Czeslaw Smutnicki,\n% Test functions for optimization needs.\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of arguments.\n%\n% Input, real X(M,N), the arguments.\n%\n% Output, real F(N), the function evaluated at the arguments.\n%\n f = zeros ( n, 1 );\n\n for j = 1 : n\n\n f(j) = 10 * m;\n\n for i = 1 : m\n f(j) = f(j) + x(i,j)^2 - 10.0 * cos ( 2.0 * pi * x(i,j) );\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/test_optimization/p05_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.6852731584030931}} {"text": "function btv_test03 ( )\n\n%*****************************************************************************80\n%\n%% BTV_TEST03 tests BURGERS_TIME_VISCOUS with the gaussian initial condition.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 April 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BTV_TEST03\\n' );\n fprintf ( 1, ' Test BURGERS_TIME_VISCOUS with the gaussian initial condition.\\n' );\n fprintf ( 1, ' Use a Neumann condition on the right.\\n' );\n\n nx = 81;\n nt = 200;\n t_max = 2.0;\n nu = 0.01;\n bc = 3;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Initial condition: gaussian\\n' );\n fprintf ( 1, ' Number of space nodes = %d\\n', nx );\n fprintf ( 1, ' Number of time steps = %d\\n', nt );\n fprintf ( 1, ' Final time T_MAX = %g\\n', t_max );\n fprintf ( 1, ' Viscosity = %g\\n', nu );\n fprintf ( 1, ' Boundary condition = %d\\n', bc );\n\n U = burgers_time_viscous ( @ic_gaussian, nx, nt, t_max, nu, bc );\n\n x = linspace ( -1.0, +1.0, nx );\n\n figure ( 3 )\n\n plot ( x, U(1:50:(nt+1),:), 'Linewidth', 3 )\n grid on\n xlabel ( '<-- X -->' )\n ylabel ( '<-- U(X,T) -->' )\n title ( 'Burgers equation solutions over time, initial condition gaussian' )\n\n filename = 'btv_test03.png';\n print ( '-dpng', filename )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Saved plot as \"%s\"\\n', filename );\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/burgers_time_viscous/btv_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.6852458106739835}} {"text": "function [C] = aggreg_p(op1,n,sc);\n% PURPOSE: Temporal aggregation matrix preserving input dimension\n% ------------------------------------------------------------\n% SYNTAX: [C] = aggreg_p(op1,n,sc); \n% ------------------------------------------------------------\n% OUTPUT: C: nxn temporal aggregation matrix\n% ------------------------------------------------------------\n% INPUT: op1: type of temporal aggregation \n% op1=1 ---> sum (flow)\n% op1=2 ---> average (index)\n% op1=3 ---> last element (stock) ---> interpolation\n% op1=4 ---> first element (stock) ---> interpolation\n% n: number of high frequency data\n% sc: number of high frequency data points \n% for each low frequency data points (freq. conversion)\n% ------------------------------------------------------------\n% LIBRARY: aggreg_v\n% ------------------------------------------------------------\n% SEE ALSO: aggreg, temporal_agg\n% ------------------------------------------------------------\n% NOTE: Use aggreg_v_X for extended interpolation\n\n% written by:\n% Enrique M. Quilis\n% Macroeconomic Research Department\n% Ministry of Economy and Competitiveness\n% \n\n% Version 1.0 [October 2010]\n\n[op1 n sc]\n\n% ------------------------------------------------------------\n% Computing implicit numer of low-frequency data\nN = fix(n/sc);\n\n% ------------------------------------------------------------\n% Generation of temporal aggregation matrix\nc = aggreg_v(op1,sc);\nC1 = [zeros(sc-1,sc) ; c];\nC = kron(eye(N),C1);\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/39770-temporal-disaggregation-library/aggreg_p.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.685218600697504}} {"text": "%########################################################################\n%\n%\t- PPGI Toolbox - \n% A MATLAB toolbox for Photoplethysmography Imaging (PPGI)\n%\n% Author : Christian S. Pilz\n% Company : The Nature of Space of Time\n% Date : 07.05.2019\n%\n% Contact : cpi@partofthestars.com\n% Web Page : www.partofthestars.com\n%\n% Version : beta0.1\n%\n%########################################################################\n%\n%\ttest_stochastic_resonator.m:\n%\n% Description:\n%\n% \tThe frequency trajectories are drawn randomly such that the\n% \trandom walk (Wiener process) defines a trajectory that is\n% \ttransformed into a frequency time series f (in Hertz). The oscillator state space\n% \tmethod is applied to the data after the simulated signal has been\n% \ttransformed to downsampled observations (defined by dts). The mean\n% \tsquared error results are then captured and visualized.\n%\n\n%\nclose all; %% Simulate M draws\n\n% Number of random draws\nM = 1;\n\n% Different time discretizations (TR) to consider\ndts = [0.01 0.05 0.1:0.1:1 1.2:.2:2.4];\n% Allocate space for results\nMSE = zeros(M,numel(dts));\nC = zeros(M,numel(dts));\n\nfor i=1:M\n\t[MSE(i,:),C(i,:),x,f] = simulate_and_estimate(dts,25);\n\tfigure;\n\tsubplot(2,1,1)\n\tplot(x(1,:),'black');\n\ttitle('Stochastic Oscillator');\n\tylabel('Amplitude');\n\txlabel('Time in seconds')\n\tx_ticks = 0:0.01:25;\n\tset(gca,'XTickLabel',x_ticks(1:2500).*500 );\n\tsubplot(2,1,2)\n\tplot(f,'black')\n\tylabel('Frequency in Hz');\n\txlabel('Time in frames')\n\ttitle('Oscillator Frequency')\nend\n", "meta": {"author": "partofthestars", "repo": "PPGI-Toolbox", "sha": "b7a7945561ccd98bf66ca629ac6d1b4bf4f0ac34", "save_path": "github-repos/MATLAB/partofthestars-PPGI-Toolbox", "path": "github-repos/MATLAB/partofthestars-PPGI-Toolbox/PPGI-Toolbox-b7a7945561ccd98bf66ca629ac6d1b4bf4f0ac34/tests/test_stochastic_resonator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6852185992609433}} {"text": "function z =fonction(input)\n\nx = input(1); \ny = input(2);\n\nz = exp(-(x-0.5)^2)+exp(-(y-0.7)^2)+(1/25)*exp(-(x+0.2)^2)+(1/25)*exp(-(x-0.2)^2)+(1/25)*exp(-(y+1)^2)+(1/25)*exp(-(y-1)^2);\n\ndrawnow;\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/14767-genetic-algorithm/GenAlgo/mafonc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6852185956333264}} {"text": "function f = cumsum3(f)\n%CUMSUM3 Triple indefinite integral of a CHEBFUN3.\n% F = CUMSUM3(F) returns the triple indefinite integral of a CHEBFUN3. \n% That is\n% z y x\n% / / /\n% CUMSUM3(F) = | | | F(x,y,z) dx dy dz\n% / / /\n% e c a\n%\n% where [a,b] x [c,d] x [e,g] is the domain of F.\n% \n% See also CHEBFUN3/CUMSUM, CHEBFUN3/CUMSUM2, CHEBFUN3/SUM, CHEBFUN3/SUM2 \n% and CHEBFUN3/SUM3.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Check for empty:\nif ( isempty(f) ) \n f = [];\n return\nend\n\nf.cols = cumsum(f.cols); % CUMSUM along the cols.\nf.rows = cumsum(f.rows); % CUMSUM along the rows.\nf.tubes = cumsum(f.tubes); % CUMSUM along the tubes.\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun3/cumsum3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7520125793176223, "lm_q1q2_score": 0.6852185948788297}} {"text": "function c = phi1(costgradf,w,param,mu)\n% compute c=cost+mu*dual error\nD = param.D;\nb = param.b;\ndim = param.dim;\nh = param.h;\nm = param.m;\nn = dim(1);\nnx = dim(2);\nny = dim(3);\nnz = dim(4);\nnt = dim(5);\nhx = h(1);\nhy = h(2);\nhz = h(3);\nht = h(4);\n\npx = w(1:n*(nx-1)*ny*nz*nt);\npy = w((n*(nx-1)*ny*nt*nz+1):(n*(nx-1)*ny*nz*nt+n*nx*(ny-1)*nz*nt));\npz = w((n*(nx-1)*ny*nz*nt+n*nx*(ny-1)*nz*nt)+1:(n*(nx-1)*ny*nz*nt+n*nx*(ny-1)*nz*nt+n*nx*ny*(nz-1)*nt));\nrho = w((n*(nx-1)*ny*nz*nt+n*nx*(ny-1)*nz*nt+n*nx*ny*(nz-1)*nt)+1:...\n (n*(nx-1)*ny*nz*nt+n*nx*(ny-1)*nz*nt+n*nx*ny*(nz-1)*nt+n*nx*ny*nz*(nt-1)));\nu = w((end-m*nx*ny*nz*nt+1):end);\nc = costgradf(px,py,pz,rho,u,param)/hx/hy/hz/ht;\nc = c + mu*sum(abs(D*w-b(:)));\nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/heterogenity_metrics/optimalMassTransport/phi1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6852185948788296}} {"text": "function pattern = elementaryCellularAutomata(rule, n, width, randfrac)\n%elementaryCellularAutomata Elementary 1D cellular automaton patterns\n%\n% PATTERN = elementaryCellularAutomata(RULE, NITER), where NITER is a\n% scalar, returns an NITER x 2*NITER+1 matrix whose entries are all 0 or\n% 1. The I'th row of the matrix contains the state of the elementary 1D\n% cellular automaton at iteration I-1, counting the initial state as\n% iteration 0. The integer RULE specifies the rule to use as set out at\n% http://mathworld.wolfram.com/ElementaryCellularAutomaton.html.\n%\n% The initial state is all zeros except for a 1 at element NITER+1 (the\n% central element) of the CA.\n%\n% PATTERN = elementaryCellularAutomata(RULE, NITER, WID), where WID is a\n% scalar, returns an NITER x WID matrix. The array of cells is taken to\n% be circular, so that PATTERN(I+1,I) depends on PATTERN{(I,WID), (I,1)\n% and (I,2)}. Similarly, PATTERN(I+1,WID) depends on PATTERN{(I,WID-1),\n% (I,WID) and (I,1)}. This only matters if WID < 2*NITER+1 and RULE is\n% such that the pattern propagates outwards, so reaching the boundaries\n% of the array.\n%\n% This wraparound allows long, thin patterns to be generated if an\n% appropriate rule is chosen. All patterns with a fixed width will be\n% periodic, unless some random noise is added.\n%\n% The state on the first iteration is all zeros except for a 1 at element\n% floor((WID+1)/2) of the CA.\n%\n% PATTERN = elementaryCellularAutomata(RULE, NITER, START) where START is\n% a 1 x WID row vector containing only the values 0 and 1, is as above\n% except that the initial state is given by the entries in START. Thus on\n% exit, PATTERN(1,:) is equal to START.\n%\n% PATTERN = elementaryCellularAutomata(RULE, NITER, WIDSTART, FNOISE) is\n% as above except that noise is added to the process. WIDSTART can be\n% either a scalar giving the width or a vector giving the start state; an\n% empty matrix is equivalent to 2*NITER+1. FNOISE is a number from 0 to 1\n% giving the probability that any given cell will be set to the wrong\n% state (the complement of the state given by the rule) on any one\n% iteration.\n%\n% Example\n% -------\n% % show 50 rows of each pattern\n% for rule = 0:255\n% pattern = elementaryCellularAutomata(rule, 50);\n% imshow(pattern); pause;\n% end\n\n% Copyright 2010 David Young\n\n% check arguments and supply defaults\nerror(nargchk(2, 4, nargin));\nvalidateattributes(rule, {'numeric'}, {'scalar' 'integer' 'nonnegative' '<=' 255}, ...\n 'elementaryCellularAutomata', 'RULE');\nvalidateattributes(n, {'numeric'}, {'scalar' 'integer' 'positive'}, ...\n 'elementaryCellularAutomata', 'N');\nif nargin < 3 || isempty(width)\n width = 2*n-1;\nelseif isscalar(width)\n validateattributes(width, {'numeric'}, {'integer' 'positive'}, ...\n 'elementaryCellularAutomata', 'WIDTH');\nelse\n validateattributes(width, {'numeric' 'logical'}, {'binary' 'row'}, ...\n 'elementaryCellularAutomata', 'START');\nend\nif nargin < 4 || isempty(randfrac)\n dorand = false;\nelse\n validateattributes(randfrac, {'double' 'single'}, {'scalar' 'nonnegative' '<=' 1}, ...\n 'elementaryCellularAutomata', 'FNOISE');\n dorand = true;\nend\n\n% set up machine\nif isscalar(width)\n patt = ones(1, width);\n patt(floor((width+1)/2)) = 2;\nelse\n patt = width + 1; % change 0,1 to 1,2 so can use sub2ind\n width = length(patt);\nend\n\n% unpack rule\nrulearr = (bitget(rule, 1:8) + 1);\n\n% initialise output array\npattern = zeros(n, width);\n\n% iterate to generate rest of pattern\nfor i = 1:n\n pattern(i, :) = patt; % record current state in output array\n \n % core step: apply CA rules to propagate to next 1D pattern\n ind = sub2ind([2 2 2], ...\n [patt(2:end) patt(1)], patt, [patt(end) patt(1:end-1)]);\n patt = rulearr(ind);\n \n %optional randomisation\n if dorand\n flip = rand(1, width) < randfrac;\n patt(flip) = 3 - patt(flip);\n end\nend\n\n% change symbols from 1 and 2 to 0 and 1\npattern = pattern-1;\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/26929-elementary-cellular-automata/elementaryCellularAutomata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.6852149580732809}} {"text": "function [varargout] = kruskal_mst(A,varargin)\n% KRUSKAL_MST Compute a minimum spanning with Kruskal's algorithm.\n%\n% The Kruskal MST algorithm computes a minimum spanning tree for a graph.\n%\n% This method works on weighted symmetric graphs.\n% The runtime is O(E log (E)).\n%\n% See the mst function for calling information. This function just calls\n% mst(...,struct('algname','kruskal'));\n%\n% Example:\n% load graphs/clr-24-1.mat\n% kruskal_mst(A)\n%\n% See also MST, PRIM_MST.\n\n% David Gleich\n% Copyright, Stanford University, 2006-2008\n\n%% History\n% 2006-04-23: Initial version\n% 2008-09-24: Code cleanup\n%%\n\nalgname = 'kruskal';\nif ~isempty(varargin), \n options = merge_options(struct(),varargin{:}); \n options.algname= algname;\nelse options = struct('algname',algname); \nend\n\nvarargout = cell(1,max(nargout,1));\n\n[varargout{:}] = mst(A,options);\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/matlab_bgl/kruskal_mst.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.6852149378157641}} {"text": "function cvx_optval = sum_smallest( x, varargin )\n\n%SUM_SMALLEST Sum of the smallest k elements of a vector.\n% For a real vector X and an integer k between 1 and length(X) inclusive,\n% y = SUM_SMALLEST(X,k) is the sum of the k smallest elements of X; e.g.,\n% temp = sort( x )\n% y = sum( temp( 1 : k ) )\n% If k=1, then SUM_SMALLEST(X,k) is equivalent to MIN(X); if k=length(X),\n% then SUM_SMALLEST(X,k) is equivalent to SUM(X).\n%\n% Both X and k must be real, and k must be a scalar. But k is not, in\n% fact, constrained to be an integer between 1 and length(X); the\n% function is extended continuously and logically to all real k. For\n% example, if k <= 0, then SUM_SMALLEST(X,k)=0. If k > length(X), then\n% SUM_SMALLEST(X,k)=SUM(X). Non-integer values of k interpolate linearly\n% between their integral neighbors.\n%\n% For matrices, SUM_SMALLEST(X,k) is a row vector containing the\n% application of SUM_SMALLEST to each column. For N-D arrays, the\n% SUM_SMALLEST operation is applied to the first non-singleton dimension\n% of X.\n%\n% SUM_SMALLEST(X,k,DIM) performs the operation along dimension DIM of X.\n%\n% Disciplined convex programming information:\n% SUM_SMALLEST(X,...) is concave and nondecreasing in X. Thus, when\n% used in CVX expressions, X must be concave (or affine). k and DIM\n% must both be constant.\n\nerror( nargchk( 2, 3, nargin ) );\ncvx_optval = -sum_largest( -x, varargin{:} );\n\n% Copyright 2010 Michael C. Grant and Stephen P. Boyd.\n% See the file COPYING.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/functions/sum_smallest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677468516188, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6852149324212731}} {"text": "%E2H Euclidean to homogeneous\n%\n% H = E2H(E) is the homogeneous version (K+1xN) of the Euclidean \n% points E (KxN) where each column represents one point in R^K.\n%\n% Reference::\n% - Robotics, Vision & Control: Second Edition, P. Corke, Springer 2016; p604.\n%\n% See also H2E.\n\n% Copyright (C) 1993-2019 Peter I. Corke\n%\n% This file is part of The Spatial Math Toolbox for MATLAB (SMTB).\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, including without limitation the rights\n% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n% of the Software, and to permit persons to whom the Software is furnished to do\n% so, subject to the following conditions:\n%\n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n% FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n% COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n% IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n%\n% https://github.com/petercorke/spatial-math\n\nfunction h = e2h(e)\n h = [e; ones(1,numcols(e))];\n", "meta": {"author": "petercorke", "repo": "spatialmath-matlab", "sha": "6eeff4a79f14286705560b84f1fe72e0b7e0e7f7", "save_path": "github-repos/MATLAB/petercorke-spatialmath-matlab", "path": "github-repos/MATLAB/petercorke-spatialmath-matlab/spatialmath-matlab-6eeff4a79f14286705560b84f1fe72e0b7e0e7f7/e2h.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.6852149312763524}} {"text": "function prob_test054 ( )\n\n%*****************************************************************************80\n%\n%% TEST054 tests EMPIRICAL_DISCRETE_CDF, EMPIRICAL_DISCRETE_CDF_INV, EMPIRICAL_DISCRETE_PDF;\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n a = 6;\n\n b(1:a) = [ 1.0, 1.0, 3.0, 2.0, 1.0, 2.0 ];\n c(1:a) = [ 0.0, 1.0, 2.0, 4.5, 6.0, 10.0 ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST054\\n' );\n fprintf ( 1, ' For the Empirical Discrete PDF:\\n' );\n fprintf ( 1, ' EMPIRICAL_DISCRETE_CDF evaluates the CDF;\\n' );\n fprintf ( 1, ' EMPIRICAL_DISCRETE_CDF_INV inverts the CDF.\\n' );\n fprintf ( 1, ' EMPIRICAL_DISCRETE_PDF evaluates the PDF;\\n' );\n\n check = empirical_discrete_check ( a, b, c );\n\n if ( ~check );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST054 - Fatal error!\\n' );\n fprintf ( 1, ' The parameters are not legal.\\n' );\n return\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' PDF parameter A = %6d\\n', a );\n r8vec_print ( a, b, ' PDF parameter B:' );\n r8vec_print ( a, c, ' PDF parameter C:' );\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X PDF CDF CDF_INV\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : 10\n\n [ x, seed ] = empirical_discrete_sample ( a, b, c, seed );\n\n pdf = empirical_discrete_pdf ( x, a, b, c );\n\n cdf = empirical_discrete_cdf ( x, a, b, c );\n\n x2 = empirical_discrete_cdf_inv ( cdf, a, b, c );\n\n fprintf ( 1, ' %14f %14f %14f %14f\\n', x, pdf, cdf, x2 );\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/prob_test054.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.6852149253971642}} {"text": "function [Ka, Kb] = getKernels(ops, nup, sig)\n% this function makes upsampling kernels for the temporal components.\n% those are used for interpolating the biggest negative peak,\n% and aligning the template to that peak with sub-sample resolution\n% needs nup, the interpolation factor (default = 10)\n% also needs sig, the interpolation smoothness (default = 1)\n\nnt0min = getOr(ops, 'nt0min', 20);\nnt0 = getOr(ops, 'nt0', 61);\n\nxs = 1:nt0;\nys = linspace(.5, nt0+.5, nt0*nup+1);\nys(end) = [];\n\n% these kernels are just standard kriging interpolators\n\n% first compute distances between the sample coordinates\n% for some reason, this seems to be circular, although the waveforms are not circular\n% I think the reason had to do with some constant offsets in some channels?\nd = rem(xs(:) - xs(:)' + nt0, nt0);\nd = min(d, nt0-d);\nKxx = exp(-d.^2 / (sig^2)); % the kernel covariance uses a squared exponential of spatial scale sig\n\n% do the same for the kernel similarities between upsampled \"test\" timepoints and the original coordinates\nd = rem(ys(:) - xs(:)' + nt0, nt0);\nd = min(d, nt0-d);\nKyx = exp(-d.^2 / (sig^2));\n\n% the upsampling matrix is given by the following formula,\n% with some light diagonal regularization of the matrix inversion\nB = Kyx/(Kxx + .01 * eye(nt0));\nB = reshape(B, nup, nt0, nt0);\n\n% A is just a slice through this upsampling matrix corresponding to the most negative point\n% this is used to compute the biggest negative deflection (after upsampling)\nA = squeeze(B(:, nt0min, :));\nB = permute(B, [2 3 1]);\n\n% move to the GPU and make it a double\nKa = gpuArray(double(A));\nKb = gpuArray(double(B));\n", "meta": {"author": "MouseLand", "repo": "Kilosort", "sha": "d55179f4bed45d4f17e5481283bc3f260212c1c7", "save_path": "github-repos/MATLAB/MouseLand-Kilosort", "path": "github-repos/MATLAB/MouseLand-Kilosort/Kilosort-d55179f4bed45d4f17e5481283bc3f260212c1c7/mainLoop/getKernels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.7371581684030621, "lm_q1q2_score": 0.6851445857143775}} {"text": "% ASTROTIK by Francesco Santilli\n% R2BP (Restricted Two Bodies Problem)\n% H2f converts hyperbolic anomaly to true anomaly for an hyperbolic orbit.\n%\n% Usage: f = H2f(H,e)\n%\n% where: H(k) = hyperbolic anomaly [rad]\n% e = eccentricity [-] (e>1)\n% f(k) = true anomaly [rad]\n\nfunction f = H2f(H,e)\n\n if ~(nargin == 2)\n error('Wrong number of input arguments.')\n end\n \n check(H,1)\n check(e,0)\n \n if e <= 1\n error('e must be strictly major than 1.')\n end\n \n ee = sqrt((e+1)/(e-1));\n f = 2*atan( ee*tanh(H/2) );\n \n kk = H/(2*pi);\n k = round(kk) - ((kk-fix(kk)) == 0.5);\n f = f + k*(2*pi);\n \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/27308-astrotik-1-0/orbits/H2f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6851428204826557}} {"text": "%THIS FUMCTION ILLUSTRATES HOW TO USE THE USER-DEFINED ALGORITHM\nfunction [AH,XH] = user_alg4(Y,r,X)\n%\n% The example of implementing the user-defined algorithm (this is the Lee-Seung algorithm based on the KL divergence)\n%\n% INPUTS:\n% Y - mixed signals (matrix of size [m by T])\n% r - number of estimated signals\n% X - true source signals\n%\n% OUTPUTS\n% AH - estimated mixing matrix (matrix of size [m by r])\n% XH - estimated source signals (matrix of size [r by T])\n%\n% #########################################################################\n% Initialization\n[m,T]=size(Y);\nY(Y <=0) = eps; % this enforces the positive value in the data \nAH=rand(m,r);\nXH=rand(r,T);\n\nIterNo = 1000; % number of alternating steps\n\n% Iterations\nfor k = 1:IterNo \n XH = XH.*(AH'*(Y./(AH*XH + eps)));\n AH = AH.*((Y./(AH*XH + eps))*XH')./repmat(sum(XH,2)',m,1);\n AH = AH*diag(1./(sum(AH,1) + eps));\nend\n \n \n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/NMFLABSP_ver1.2/user_alg4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6851428077285268}} {"text": "function varargout = CannyEdgeDetector(varargin)\n% CannyEdgeDetector Detects edges in the intensity image.\n% imo = CannyEdgeDetector(imi) takes the intensity image imi as input\n% and returns a binary image imo with the same size as imi, where 1's\n% are the edge pixels detected by Canny's method (default). The default\n% value for the thresholds are specified as\n% 0.3*max(GradientMagnitudeImage), 0.1*max(GradientMagnitudeImage) and\n% 1 for high and low thresholds and sigma for Gaussian kernel,\n% respectively. There are also some additional features listed as\n% below:\n% \n% imo = CannyEdgeDetector(imi,method) takes an additional string \n% 'method' as input which specifies the function to detect the edges \n% whether using Canny's method, or Laplacian of Gaussian. The possible \n% valid entries for method input are 'canny' and 'log'. The default \n% threshold value for log method is automatically chosen by 'edge' \n% function, which is present in \"Image Processing Toolbox\".\n% \n% imo = CannyEdgeDetector(imi,sigma) returns the same output as \n% described at the top, only with the specified sigma value for\n% Gaussian kernel in stead of the default value. The default value for\n% method is 'canny'.\n% \n% imo = CannyEdgeDetector(imi,sigma,method) returns the edge detected \n% binary image imo, with the specified sigma value and the specified \n% method, in stead of the defaults.\n% \n% imo = CannyEdgeDetector(...,Th) returns the same output as described\n% above, with an additional input to specify the threshold for 'log'\n% method, or the high threshold for 'canny'. In the second case, the\n% low threshold is 1/3 of Th by default.\n% \n% imo = CannyEdgeDetector(...,Th,Tl) takes an additional input Tl,\n% which specifies the low threshold in case of Canny's method. When the\n% method input is 'log', this usage is invalid and the function will\n% return an error message.\n% \n% imo = CannyEdgeDetector(...,Th,Tl,feature) In the case of Canny's\n% method, there are two distinct ways to apply hysteresis thresholding\n% defined. The first one is a recursive search (namely, depth first\n% search), and the second one is to use some morphological operations.\n% Obviously, the recursive method takes longer to operate. The string\n% input 'feature' specifies which one to use. Valid options for this\n% input are 'dfs' and 'morph'. It is defined as 'dfs' by default. In\n% the case of log method, this usage is invalid and will return an\n% error message.\n% \n% CannyEdgeDetector(...) usage (without the output arguments) plots the\n% binary image using imshow, in stead of making any assignments.\n% \n% Author: Halim Can ALBASAN\n% \n% Written for the term project of the course \"Robot Vision\" (EE701)\n% given in Middle East Technical University, Ankara, Turkey; by the \n% lecturer A. Aydin Alatan.\n% \n% Date: 15/06/2008 \n\n\n[imi,sigma,method,Th,Tl,feature] = parse_inputs (varargin{:});\n\nswitch method\n case 'canny'\n \n%% Detection of Gaussian kernel size ( 3 <= N <= 15 )\n\nG = gaussmf (-10:10,[sigma 0]);\nind = find (G<=.1);\nif length(ind)<=6\n N = 15; % Upper boundary\n warning('MATLAB:LargeSigma','Sigma too large!')\n \nelseif length(ind)>=18\n N = 3; % Lower boundary\n warning('MATLAB:SmallSigma','Sigma too small!')\nelse\n G(ind) = [];\n N = length (G);\nend\n\n%% Gaussian kernel and its first derivatives ( horizontal (Gh) and vertical\n%% (Gv) )\n\nG = fspecial ('gaussian', [N N], sigma);\n[Gh,Gv] = gradient(G);\n\n%% Applying the operators to the image and obtaining the gradient\n%% magnitudes and directions\n\nimx = conv2(double(imi),Gh);\nimx = imx ((N-1)/2+1:size(imx,1)-(N-1)/2,(N-1)/2+1:size(imx,2)-(N-1)/2);\nimy = conv2(double(imi),Gv);\nimy = imy ((N-1)/2+1:size(imy,1)-(N-1)/2,(N-1)/2+1:size(imy,2)-(N-1)/2);\n\ngra_mag = sqrt(imx.^2+imy.^2);\ngra_dir = atan2(imy,imx);\n\n%% Gradient direction discretization\n\n[r c] = size (gra_dir);\n\nfor i=1:r\n for j=1:c\n if ( gra_dir(i,j)=0 ) ...\n || ( gra_dir(i,j)<=2*pi && gra_dir(i,j)>=15*pi/8 ) ...\n || ( gra_dir(i,j)<9*pi/8 && gra_dir(i,j)>=7*pi/8 )\n gra_dir(i,j) = 0;\n elseif ( gra_dir(i,j)>=pi/8 && gra_dir(i,j)<3*pi/8 ) ...\n || ( gra_dir(i,j)>=9*pi/8 && gra_dir(i,j)<11*pi/8 )\n gra_dir(i,j) = 45;\n elseif ( gra_dir(i,j)>=3*pi/8 && gra_dir(i,j)<5*pi/8 ) ...\n || ( gra_dir(i,j)>=11*pi/8 && gra_dir(i,j)<13*pi/8)\n gra_dir(i,j) = 90;\n else\n gra_dir(i,j) = 135;\n end\n end\nend\n\n%% Nonmaxima suppression\n\ngra_mag_s = gra_mag;\ngra_mag_s(1,:) = zeros (1,c);\ngra_mag_s(r,:) = zeros (1,c);\ngra_mag_s(:,1) = zeros (r,1);\ngra_mag_s(:,c) = zeros (r,1); % Suppress boundaries first\n\nfor i=2:r-1\n for j=2:c-1\n if gra_dir(i,j)==0\n if ( gra_mag(i,j)<=gra_mag(i,j+1) ) ...\n || ( gra_mag(i,j)<=gra_mag(i,j-1) )\n gra_mag_s(i,j) = 0;\n end\n elseif gra_dir(i,j)==45\n if ( gra_mag(i,j)<=gra_mag(i-1,j+1) ) ...\n || ( gra_mag(i,j)<=gra_mag(i+1,j-1) )\n gra_mag_s(i,j) = 0;\n end\n elseif gra_dir(i,j)==90\n if ( gra_mag(i,j)<=gra_mag(i+1,j) ) ...\n || ( gra_mag(i,j)<=gra_mag(i-1,j) )\n gra_mag_s(i,j) = 0;\n end\n else\n if ( gra_mag(i,j)<=gra_mag(i+1,j+1) ) ...\n || ( gra_mag(i,j)<=gra_mag(i-1,j-1) )\n gra_mag_s(i,j) = 0;\n end\n end\n end\nend\n\n%% Hysteresis thresholding and forming the output image\n\nif isempty(Th)\n Tl = .10*max(max(gra_mag_s));\n Th = .30*max(max(gra_mag_s));\nend\n\nh_thr_im = gra_mag_s;\nh_thr_im(gra_mag_s0\n h_thr_im = edge_follow(h_thr_im,l_thr_im,i,j);\n end\n end\nend\n\nimo = logical(h_thr_im);\n\n end\n \n case 'log'\n \nimo = edge(imi,method,Th,sigma);\n\nend\n\nif nargout<1\n imshow(imo)\nelse\n varargout{1} = imo;\nend\n\n\nfunction thr_h = edge_follow(thr_h,thr_l,i,j)\n \n x = [-1 0 1 -1 1 -1 0 1]; % Relative coordinates of 8 neighbors\n y = [-1 -1 -1 0 0 1 1 1];\n \n \n for k=1:8\n if thr_h(i+x(k),j+y(k))==0 && thr_l(i+x(k),j+y(k))~=0\n thr_h(i+x(k),j+y(k)) = -thr_l(i+x(k),j+y(k));\n thr_h = edge_follow(thr_h,thr_l,i+x(k),j+y(k));\n end\n end\n\nend\n\nfunction [imi,sigma,method,Th,Tl,feature] = parse_inputs(varargin)\n \n imi = varargin{1};\n sigma = 1; % defaults\n method = 'canny';\n Th = []; % the defaults for the thresholds will be \n Tl = []; % specified after the gradient magnitude is \n feature = 'dfs'; % calculated.\n \n methods = {'canny','log'};\n features = {'dfs','morph'};\n sigma_default = false;\n \n if nargin<1\n error('Not enough input arguments.')\n end\n \n if nargin>=2\n \n if ischar(varargin{2})\n if length(strmatch(varargin{2},methods))~=1\n error('Wrong input for edge detection method')\n else\n method=varargin{2};\n sigma_default = true;\n end\n \n else\n sigma=varargin{2};\n end\n end\n \n if nargin>=3\n \n if sigma_default\n Th = varargin{3};\n Tl = Th/3;\n else\n if length(strmatch(varargin{3},methods))~=1\n error('Wrong input for edge detection method')\n else\n method=varargin{3};\n end\n end\n end\n \n if nargin>=4\n \n if sigma_default\n if strcmp(method,'canny')\n Tl = varargin{4};\n else\n error('Wrong sequence or number of inputs for \"log\" method')\n end\n else\n Th = varargin{4};\n end\n end\n \n if nargin>=5\n if strcmp(method,'log')\n error('Too many input arguments!')\n else\n if sigma_default\n if ischar(varargin{5})\n if length(strmatch(varargin{5},features))~=1\n error('Wrong input for hysteresis thresholding method')\n else\n feature = varargin{5};\n end\n else\n error('Wrong usage of input argument \"feature\"!')\n end\n else\n Tl = varargin{5};\n end\n end\n end\n \n if nargin>=6\n if sigma_default\n error('Too many input arguments!')\n else\n if ischar(varargin{6})\n if length(strmatch(varargin{6},features))~=1\n error('Wrong input for hysteresis thresholding method')\n else\n feature = varargin{5};\n end\n else\n error('Wrong usage of input argument \"feature\"!')\n end\n end\n end\n \n if nargin>6\n error('Too many input arguments')\n end\nend\n\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/22714-canny-edge-detector/CannyEdgeDetector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6850618848913181}} {"text": "function DataSet = prtDataGenNoisySinc(varargin)\n% prtDataGenNoisySinc Generates noisy sinc example data\n%\n% DATASET = prtDataGenNoisySinc returns a prtDataSetRegress with 100\n% samples of sinc wave with zero-mean additive Gaussian noise. The noise\n% variance is .1.\n%\n% DATASET = prtDataGenNoisySinc(param,value) enables specification of\n% various parameter/value pairs:\n% nSamples - 100 - the number of random locations to sample\n% tLims - [-10 10] - 1x2 vector specifying x sampling range\n% x - [] - nx1 vector of locations to sample at; if empty, use random\n% sampling, which uses nSamples and t to randomly pick x.\n% noiseVar - 0.1 - the variance of the noise to add\n% \n%\n% Example:\n%\n% ds1 = prtDataGenNoisySinc;\n% ds2 = prtDataGenNoisySinc('tLims',[-5 5],'nSamples',1000);\n% ds3 = prtDataGenNoisySinc('x',linspace(-10,10,30));\n% subplot(3,1,1); \n% plot(ds1); \n% V = axis;\n% subplot(3,1,2);\n% plot(ds2); \n% axis(V);\n% subplot(3,1,3);\n% plot(ds3); \n% axis(V);\n%\n% See also: prtDataSetClass, prtDataGenBiModal, prtDataGenIris,\n% prtDataGenMary, prtDataGenNoisySinc, prtDataGenOldFaithful,\n% prtDataGenSpiral, prtDataGenUnimodal, prtDataGenUnimodal, prtDataGenXor\n\n\n\n\n\n\n\nif nargin == 1\n nSamples = varargin{1};\n noiseVar = 0.1;\n tLims = [-10 10];\n x = prtUtilRandSample(tLims,nSamples);\nelse\n p = inputParser;\n p.addParameter('noiseVar',.1);\n p.addParameter('nSamples',100);\n p.addParameter('tLims',[-10 10]);\n p.addParameter('x',[]);\n p.parse(varargin{:});\n inputs = p.Results;\n noiseVar = inputs.noiseVar;\n nSamples = inputs.nSamples;\n tLims = inputs.tLims;\n x = inputs.x;\n x = x(:);\n if isempty(x);\n x = prtUtilRandSample(tLims,nSamples);\n end\nend\n\nt = sinc(x/pi);\ny = t + noiseVar*randn(size(x));\n\nDataSet = prtDataSetRegress(x,y,'name','Noisy Sinc');\n\nfunction y = sinc(x)\n\ny = sin(pi*x)./(pi*x);\ny(x == 0) = 1;\n\nfunction x = prtUtilRandSample(tLims,nSamples)\n\nx = rand(nSamples,1)*(tLims(2)-tLims(1)) + tLims(1);\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/dataGen/prtDataGenNoisySinc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.8723473730188542, "lm_q1q2_score": 0.6850618775466002}} {"text": "function x = r8blt_sl ( n, ml, a, b, job )\n\n%*****************************************************************************80\n%\n%% R8BLT_SL solves a R8BLT system.\n%\n% Discussion:\n%\n% The R8BLT storage format is appropriate for a banded lower triangular matrix.\n% The matrix is assumed to be zero below the ML-th subdiagonal.\n% The matrix is stored in an ML+1 by N array, in which the diagonal\n% appears in the first row, followed by successive subdiagonals.\n% Columns are preserved.\n%\n% No factorization of the lower triangular matrix is required.\n%\n% Example:\n%\n% N = 5, ML = 2\n%\n% A11 0 0 0 0\n% A21 A22 0 0 0\n% A31 A32 A33 0 0\n% 0 A42 A43 A44 0\n% 0 0 A53 A54 A55\n% --- ---\n% ---\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, integer ML, the lower bandwidth.\n%\n% Input, real A(ML+1,N), the R8BLT matrix.\n%\n% Input, real B(N), the right hand side.\n%\n% Input, integer JOB, is 0 to solve the untransposed system,\n% nonzero to solve the transposed system.\n%\n% Output, real X(N), the solution vector.\n%\n x(1:n) = b(1:n);\n\n if ( job == 0 )\n\n for j = 1 : n\n x(j) = x(j) / a(1,j);\n ihi = min ( j + ml, n );\n for i = j+1 : ihi\n x(i) = x(i) - a(i-j+1,j) * x(j);\n end\n end\n\n else\n\n for j = n : -1 : 1\n x(j) = x(j) / a(1,j);\n ilo = max ( j - ml, 1 );\n for i = ilo : j-1\n x(i) = x(i) - a(j-i+1,i) * x(j);\n end\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/linplus/r8blt_sl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782092, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.6850618700832389}} {"text": "function r8lib_test122 ( )\n\n%*****************************************************************************80\n%\n%% R8LIB_TEST122 tests R8VEC_HISTOGRAM.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n histo_num = 20;\n n = 1000;\n\n seed = 123456789;\n test_num = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8LIB_TEST122\\n' );\n fprintf ( 1, ' R8VEC_HISTOGRAM histograms an integer vector.\\n' );\n\n for test = 1 : test_num\n\n if ( test == 1 )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Uniform data:\\n' );\n\n a_lo = 0.0;\n a_hi = +1.0;\n [ a, seed ] = r8vec_uniform_01 ( n, seed );\n\n elseif ( test == 2 )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Normal data:\\n' );\n a_lo = -3.0;\n a_hi = +3.0;\n [ a, seed ] = r8vec_normal_01 ( n, seed );\n\n end\n\n histo_gram = r8vec_histogram ( n, a, a_lo, a_hi, histo_num );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Histogram of data:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 0 : histo_num+1\n\n if ( i == 0 )\n\n fprintf ( 1, ' %10f %6d\\n', a_lo, histo_gram(i+1) );\n\n elseif ( i <= histo_num )\n\n bin_lo = ( ( histo_num - i + 1 ) * a_lo ...\n + ( i - 1 ) * a_hi ) ...\n / ( histo_num );\n\n bin_hi = ( ( histo_num - i ) * a_lo ...\n + ( i ) * a_hi ) ...\n / ( histo_num );\n\n fprintf ( 1, ' %10f %10f %6d\\n', bin_lo, bin_hi, histo_gram(i+1) );\n\n elseif ( i == histo_num+1 )\n\n fprintf ( 1, ' %10f %6d\\n', a_hi, histo_gram(i+1) );\n\n end\n\n end\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_histogram_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.6850073950488367}} {"text": "% Multichannel version of im2col. Rearranges image blocks into columns.\n% The vectorized blocks of each channel are staked vertically in the output.\n%\n% USAGE: patches = im2col_ch(im, [ph pw], mode)\n%\n% -> im : input image\n% -> ph,pw : patch size (ph x pw)\n% -> mode : either 'distinct' of 'sliding'\n%\n% <- patches : output patches (ph pw ch x n)\nfunction patches = im2col_ch(im, psz, mode)\n\n\tif nargin < 3,\n\t\tmode = 'sliding';\n\tend\n\n\tpdim = prod(psz);\n\tch = size(im,3);\n\n\t% extract patches from first channel\n\tpatches = im2col(im(:,:,1),psz,mode);\n\n\t% number of patches\n\tn = size(patches,2);\n\n\t% allocate room for the other channels\n\tpatches = [patches ; zeros((ch-1)*size(patches,1), size(patches,2))];\n\tfor c = 2:ch,\n\t\tpatches((c-1)*pdim + [1:pdim],:) = im2col(im(:,:,c), psz, mode);\n\tend\n\nend\n\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u53bb\u566a\u7b97\u6cd5/nlbayes.m-master/im2col_ch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.6850073940940231}} {"text": "load sstest2_results.mat % TM T1 TU f\nwhos\n\nindex = UFget ;\n\ntmax = max (max (TM))\ntmin = min (TM (find (TM > 0)))\n\nnmat = length (f) ;\nk = nmat ;\n\n for kind = 1:4\n\n\tsubplot (2,4,kind) ;\n\tr = TM (1:k,kind) ./ T1 (1:k,kind) ;\n\trmin = min (r) ;\n\trmax = max (r) ;\n\tloglog (TM (1:k,kind), r, 'o', ...\n\t [tmin tmax], [1 1], 'r-', ...\n\t [tmin tmax], [1.1 1.1], 'r-', ...\n\t [tmin tmax], [1/1.1 1/1.1], 'r-', ...\n\t [tmin tmax], [2 2], 'g-', ...\n\t [tmin tmax], [1.5 1.5], 'g-', ...\n\t [tmin tmax], [1/1.5 1/1.5], 'g-', ...\n\t [tmin tmax], [.5 .5], 'g-' );\n\tif (k > 2)\n\t axis ([tmin tmax rmin rmax]) ;\n\t set (gca, 'XTick', [1e-5 1e-4 1e-3 1e-2 1e-1 1 10]) ;\n\t set (gca, 'YTick', [.5 1/1.5 1/1.1 1 1.1 1.5 2]) ;\n\tend\n\txlabel ('MATLAB time') ; \n\tylabel ('MATLAB/SM time') ; \n\tif (kind == 1)\n\t title ('real*real') ;\n\telseif (kind == 2)\n\t title ('complex*real') ;\n\telseif (kind == 3)\n\t title ('real*complex') ;\n\telseif (kind == 4)\n\t title ('complex*complex') ;\n\tend\n\n end\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/SuiteSparse/SSMULT/Results/s2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.6850073892153005}} {"text": "function [phiNorm] = normalize_angle(phi)\n%Normalize phi to be between -pi and pi\n\nwhile(phi>pi)\n\tphi = phi - 2*pi;\nendwhile\n\nwhile(phi<-pi)\n\tphi = phi + 2*pi;\nendwhile\nphiNorm = phi;\n\nend\n", "meta": {"author": "kiran-mohan", "repo": "SLAM-Algorithms-Octave", "sha": "e0254ad38cfca2170b2af68c96c183df77c76252", "save_path": "github-repos/MATLAB/kiran-mohan-SLAM-Algorithms-Octave", "path": "github-repos/MATLAB/kiran-mohan-SLAM-Algorithms-Octave/SLAM-Algorithms-Octave-e0254ad38cfca2170b2af68c96c183df77c76252/1_EKF_SLAM/octave/tools/normalize_angle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.6850073861749991}} {"text": "% Lorenz Attractor equations solved by ODE Solve\n%% x' = sigma*(y-x)\n%% y' = x*(rho - z) - y\n%% z' = x*y - beta*z\nfunction dx = lorenzatt(X)\n rho = 28; sigma = 10; beta = 8/3;\n dx = zeros(3,1);\n dx(1) = sigma*(X(2) - X(1));\n dx(2) = X(1)*(rho - X(3)) - X(2);\n dx(3) = X(1)*X(2) - beta*X(3);\n return\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/NumericalMethods/lorenzatt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947055100817, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6849985731687301}} {"text": "clear, clc;\n\n% This is an example for running the function sparseInverseCovariance\n% \n% max log( det( Theta ) ) - < S, Theta> - lambda * ||Theta||_1\n%\n% For detailed description of the function, please refer to the Manual.\n%\n%% Related papers\n%\n% The implementation is based on the following paper:\n%\n% [1] Jerome Friedman, Trevor Hastie, and Robert Tibshirani,\n% Sparse inverse covariance estimation with the graphical lasso, 2007\n%\n% This function has been used in the following paper:\n%\n% [2] Shuai Huang, Jing Li, Liang Sun, Jun Liu, Teresa Wu,\n% Kewei Chen, Adam Fleisher, Eric Reiman, and Jieping Ye,\n% Learning Brain Connectivity of Alzheimer's Disease \n% from Neuroimaging Data, NIPS, 2009\n%\n%% ------------ History --------------------\n%\n% First version on September 18, 2008.\n%\n% For any problem, please contact Jun Liu (j.liu@asu.edu)\n\ncd ..\ncd ..\n\nroot=cd;\naddpath(genpath([root '/SLEP']));\n % add the functions in the folder SLEP to the path\n \n% change to the original folder\ncd Examples/invCov;\n\nn=100;\n% problem size\n\n% generate the data\nrandn('state',1);\nA=randn(n,n);\n\nmean_1=mean(A,1);\nA=A-repmat(mean_1,n,1);\nnorm_2=sqrt( sum(A.^2,1) );\nA=A./repmat(norm_2,n,1);\n\n% S is the empirical covariance matrix\nS=A'*A;\n\n% set the maximal number of iterations\nopts.maxIter=100;\n\nlambda=0.2;\n\ntic;\nTheta=sparseInverseCovariance(S, lambda, opts);\ntoc;", "meta": {"author": "zzstefan", "repo": "BrainNetClass", "sha": "556cda9516429a964100e1ac0bace4258194b4a1", "save_path": "github-repos/MATLAB/zzstefan-BrainNetClass", "path": "github-repos/MATLAB/zzstefan-BrainNetClass/BrainNetClass-556cda9516429a964100e1ac0bace4258194b4a1/Toolbox/SLEP_package_4.1/Examples/invCov/example_sparseInverseCovariance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6849885744520515}} {"text": "function [fc,cc,kc,alpha_c,Rc,Tc,omc,nx,ny,x_dist,xd] = willson_convert(Ncx,Nfx,dx,dy,dpx,dpy,Cx,Cy,sx,f,kappa1,Tx,Ty,Tz,Rx,Ry,Rz,p1,p2);\n\n%Conversion from Reg Willson's calibration format to my format\n\n% Conversion:\n\n% Focal length:\nfc = [sx/dpx ; 1/dpy]*f;\n\n% Principal point;\ncc = [Cx;Cy];\n\n% Skew:\nalpha_c = 0;\n\n% Extrinsic parameters:\nRx = rodrigues([Rx;0;0]);\nRy = rodrigues([0;Ry;0]);\nRz = rodrigues([0;0;Rz]);\n\nRc = Rz * Ry * Rx;\n\nomc = rodrigues(Rc);\n\nTc = [Tx;Ty;Tz];\n\n\n% More tricky: Take care of the distorsion:\n\nNfy = round(Nfx * 3/4);\n\nnx = Nfx;\nny = Nfy;\n\n% Select a set of DISTORTED coordinates uniformely distributed across the image:\n\n[xp_dist,yp_dist] = meshgrid(0:Nfx-1,0:Nfy);\n\nxp_dist = xp_dist(:)';\nyp_dist = yp_dist(:)';\n\n\n% Apply UNDISTORTION according to Willson:\n\nxp_sensor_dist = dpx*(xp_dist - Cx)/sx;\nyp_sensor_dist = dpy*(yp_dist - Cy);\n\ndist_fact = 1 + kappa1*(xp_sensor_dist.^2 + yp_sensor_dist.^2);\n\nxp_sensor = xp_sensor_dist .* dist_fact;\nyp_sensor = yp_sensor_dist .* dist_fact;\n\nxp = xp_sensor * sx / dpx + Cx;\nyp = yp_sensor / dpy + Cy;\n\nind= find((xp > 0) & (xp < Nfx-1) & (yp > 0) & (yp < Nfy-1));\n\nxp = xp(ind);\nyp = yp(ind);\nxp_dist = xp_dist(ind);\nyp_dist = yp_dist(ind);\n\n\n% Now, find my own set of parameters:\n\nx_dist = [(xp_dist - cc(1))/fc(1);(yp_dist - cc(2))/fc(2)];\nx_dist(1,:) = x_dist(1,:) - alpha_c * x_dist(2,:);\n\nx = [(xp - cc(1))/fc(1);(yp - cc(2))/fc(2)];\nx(1,:) = x(1,:) - alpha_c * x(2,:);\n\nk = [0;0;0;0;0];\n\nfor kk = 1:5,\n\t\n\t[xd,dxddk] = apply_distortion(x,k);\n\n\terr = x_dist - xd;\n\n\t%norm(err)\n \n k_step = inv(dxddk'*dxddk)*(dxddk')*err(:);\n \n k = k + k_step; %inv(dxddk'*dxddk)*(dxddk')*err(:);\n \n %norm(k_step)/norm(k)\n \n if norm(k_step)/norm(k) < 10e-10,\n break;\n end;\n \nend;\n\n\nkc = k;\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/EKF_monoSLAM_1pRANSAC/matlab_code/matlabcalibration2ourcalibration/TOOLBOX_calib/willson_convert.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6849885695659141}} {"text": "function sMap = rsom_lininit(Distances, msize, varargin)\n\n%RSOM_LININIT computes linear initialization for the RSOM. \n%\n% sM = rsom_lininit(D, msize, [argID, value, ...])\n%\n% sM = rsom_lininit(D, msize, 'lattice', 'hexa');\n%\n% Input and output arguments: \n% D (matrix) dissimilarity data for training, size nData x nData\n% msize (vector) map size\n% [argID, (string) See below.\n% value] (varies) \n%\n% sM (struct) RSOM map struct, the initialized map \n%\n% Here are the valid argument IDs and corresponding values.\n% 'lattice' (string) map lattice: 'hexa' or 'rect'\n% 'shape' (string) map shape: 'sheet', 'cyl' or 'toroid'\n% 'name' (string) name of the RSOM struct\n%\n% For more help, try 'type rsom_lininit' or check out online documentation.\n% See also RSOM_RANDINIT, RSOM_BATCHTRAIN.\n\n%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% rsom_lininit\n%\n% PURPOSE\n%\n% Initializes the RSOM in the input space linearly.\n%\n% SYNTAX\n%\n% sM = rsom_lininit(D, msize);\n% sM = rsom_lininit(...,'argID',value,...);\n%\n% DESCRIPTION\n%\n% The grid in the input space is initialized along the eigenvectors \n% corresponding to the largest eigenvalues. These are calculated by \n% classical MDS from the dissimilarity matrix D. If D is generated from\n% euclidean data, squared distances should be provided i.e.\n% (D)_ij = ||x_i - x_j||^2. \n% \n% REFERENCES\n%\n% Barbara Hammer, Alexander Hasenfuss: Topographic Mapping of Large\n% Dissimilarity Data Sets. Neural Computation 22(9): 2229-2284 (2010)\n%\n% REQUIRED INPUT ARGUMENTS\n%\n% D (matrix) dissimilarity data for training, size nData x nData\n% msize (vector) map size\n%\n% OPTIONAL INPUT ARGUMENTS \n%\n% argID (string) Argument identifier string (see below).\n% value (varies) Value for the argument (see below).\n%\n% The optional arguments can be given as 'argID',value -pairs.\n% The valid IDs and corresponding values are listed below. \n%\n% Below is the list of valid arguments: \n% 'lattice' (string) map lattice: 'hexa' or 'rect'\n% 'shape' (string) map shape: 'sheet', 'cyl' or 'toroid'\n% 'name' (string) name of the RSOM struct\n%\n% EXAMPLES\n%\n% sM = rsom_lininit(D, [10 10]);\n% sM = rsom_lininit(D, [10 10], 'lattice', 'hexa');\n%\n% SEE ALSO\n%\n% rsom_randinit Initialize a RSOM randomly\n% rsom_batchtrain Train a RSOM\n\n% Contributed to SOM Toolbox vs2, December 7th, 2012 by Alexander Schulz\n% Copyright (c) Alexander Schulz\n% http://www.cis.hut.fi/projects/somtoolbox/\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%% Prase input\np = inputParser;\np.addRequired('Distances', @isnumeric);\np.addRequired('msize', @isnumeric);\n\np.addParamValue('lattice', 'rect', @ischar);\np.addParamValue('shape', 'sheet', @ischar);\np.addParamValue('name', '', @ischar);\n\np.parse(Distances, msize, varargin{:});\n\nlattice = p.Results.lattice;\nshape = p.Results.shape;\nname = p.Results.name;\nclear p;\nmdim = length(msize);\nnData = size(Distances,1);\n\n%% Init and normalize\n% create the topology struct\nsTopol = som_topol_struct('msize', msize, ...\n 'lattice', lattice, ...\n 'shape', shape);\n\n\nCoords = som_unit_coords(msize,'rect','sheet');\n% normalize the neuron positions to mean 0\nCoords = bsxfun(@minus, Coords, mean(Coords,1));\n\n% compute mds embedding of the distance matrix\n[V, e]=cmdscale(Distances.^(1/2));\n% keep only the first mdim dimensions\nV = V(:, 1:mdim);\ne = e(1:mdim);\nscale = std(V);\n\n% scale Coords to the scale of the data\n%Coords = bsxfun(@rdivide, Coords, std(Coords));\n%Coords = bsxfun(@times, Coords, scale);\nCoords = bsxfun(@rdivide, Coords, std(Coords)+1e-10);\n\n% project neurons onto the data\n% e is n * variance\nstandardDev = sqrt(e/nData);\nV = bsxfun(@rdivide, V, nData*standardDev'+1e-10);\n%V = bsxfun(@rdivide, V, sqrt(sum(V.^2, 2))+1e-10);\n\ncCodebook = Coords * V';\ncCodebook = cCodebook + 1/nData;\n\n%% create the resulting struct\nsTrain = som_train_struct('algorithm','lininit');\n \nsMap = struct('type', 'rsom_map', ...\n 'cCodebook', cCodebook, ...\n 'topol', sTopol, ...\n 'labels', cell(1), ...\n 'neigh', 'gaussian', ...\n 'trainhist', cell(1), ...\n 'name', name);\n\nsTrain = som_set(sTrain,'time',datestr(now,0));\nsMap.trainhist = sTrain;\n\n", "meta": {"author": "ilarinieminen", "repo": "SOM-Toolbox", "sha": "f2597abc1ae33c2060e0443d49e854011ff21831", "save_path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox", "path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox/SOM-Toolbox-f2597abc1ae33c2060e0443d49e854011ff21831/contrib/rsom/rsom_lininit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7606506472514405, "lm_q1q2_score": 0.6849885687409961}} {"text": "%SFLAG4 Shape function driver (fourth order P4/Q4 Lagrange polynomials).\n%\n% [ VBASE, NLDOF, XLDOF, SFUN ] = SFLAG4( I_EVAL, N_SDIM, N_VERT, I_DOF, XI, AINVJAC, VBASE )\n% Evaluates conforming quartic Lagrange shape functions with values\n% defined in the nodes, and edges, (and also faces, and cell centers for\n% quadrilaterals, tetrahedra, and hexahedrals).\n%\n% Input Value/[Size] Description\n% -----------------------------------------------------------------------------------\n% i_eval scalar: 1 Evaluate function values\n% >1 Evaluate values of derivatives\n% n_sdim scalar: 1-3 Number of space dimensions\n% n_vert scalar: 2-8 Number of vertices per cell\n% i_dof scalar: 1-n_ldof Local basis function to evaluate\n% xi [n_sdim(+1)] Local coordinates of evaluation point\n% aInvJac [n,n_sdim(+1)*n_sdim] Inverse of transformation Jacobian\n% vBase [n] Preallocated output vector\n% .\n% Output Value/[Size] Description\n% -----------------------------------------------------------------------------------\n% vBase [n] Evaluated function values\n% nLDof [4] Number of local degrees of freedom on\n% vertices, edges, faces, and cell interiors\n% xLDof [n_sdim,n_ldof] Local coordinates of local dofs\n% sfun string Function name of called shape function\n%\n% See also SF_LINE_P4, SF_TRI_P4, SF_TET_P4, SF_QUAD_Q4, SF_HEX_Q4\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/ellib/sflag4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6849885577630292}} {"text": "function [ y ] = tapas_huge_logit( x )\n% Numerical stable calculation of logit function.\n% \n% INPUTS:\n% x - Array of double.\n% \n% OUTPUTS:\n% y - logit of x.\n% \n\n% Author: Yu Yao (yao@biomed.ee.ethz.ch)\n% Copyright (C) 2019 Translational Neuromodeling Unit\n% Institute for Biomedical Engineering,\n% University of Zurich and ETH Zurich.\n% \n% This file is part of TAPAS, which is released under the terms of the GNU\n% General Public Licence (GPL), version 3. For further details, see\n% .\n% \n% This software is provided \"as is\", without warranty of any kind, express\n% or implied, including, but not limited to the warranties of\n% merchantability, fitness for a particular purpose and non-infringement.\n% \n% This software is intended for research only. Do not use for clinical\n% purpose. Please note that this toolbox is under active development.\n% Considerable changes may occur in future releases. For support please\n% refer to:\n% https://github.com/translationalneuromodeling/tapas/issues\n% \n\ny = log(x./(1-x));\ny(y == Inf) = realmax;\ny(y == -Inf) = -realmin;\n\n\nend\n\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/huge/tapas_huge_logit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.684988556557337}} {"text": "% MAIN -- Polar Point Mass\n%\n% This script runs a simulation of the polar point mass, with a controller\n% that is working to hold the mass at a fixed distance from the origin\n%\n\nP.m = 1;\nP.g = 9.81;\nP.l = 1;\nP.freq = 3*sqrt(P.g/P.l); %Response frequence in controller\nP.damp = 1.0; %Damping ratio in controller\nP.eNom = 2.5*P.m*P.g*P.l;\n\n% z = [r; th; dr; dth];\n\nz0min = [0.5*P.l; -pi; -0.2; -0.2];\nz0max = [1.5*P.l; pi; 0.2; 0.2];\n\n\nz0 = z0min + (z0max-z0min).*rand(4,1);\n\nuserFunc = @(t,z)dynamics(t,z,controller(z,P),P);\n\ntSpan = [0;3];\n\nsol = ode45(userFunc,tSpan,z0);\n\nt = linspace(tSpan(1),tSpan(2),500);\nz = deval(sol,t);\nu = controller(z,P);\n\nfigure(234); clf;\n\nsubplot(3,2,1);\nplot(t,z(1,:))\nylabel('r')\n\nsubplot(3,2,3);\nplot(t,z(3,:))\nylabel('dr')\n\nsubplot(3,2,5);\nplot(t,u)\nylabel('u')\n\nsubplot(3,2,2);\nplot(t,z(2,:))\nylabel('th')\n\nsubplot(3,2,4);\nplot(t,z(4,:))\nylabel('dth')\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/polarPointMass/MAIN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6849435924544501}} {"text": "function price = PROJ_ForwardStarting(N, alph, r, q, T1, T2, S_0, call, rnCHF1, rnCHF2)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% About: Pricing Function for Forward Starting Options using PROJ method (uses cubic B-splines)\n% Models Supported: Levy Processes, including jump diffusions and Black-Scholes model\n% Returns: price of contract\n% Author: Justin Lars Kirkby\n%\n% ----------------------\n% Contract/Model Params \n% ----------------------\n% S_0 = initial stock price (e.g. 100)\n% W = strike (e.g. 100)\n% r = interest rate (e.g. 0.05)\n% q = dividend yield (e.g. 0.05)\n% T1 = time to maturity (in years), e.g. T1=1\n% T2 = T - T1, how much time remains in contract after the forward start date (choose 0 < T2 < T1)\n% call = 1 for call (else put)\n% rnCHF1 = risk netural characteristic function of process up to T1 (function handle with single argument)\n% rnCHF2 = risk netural characteristic function of process with T2 = T - T1 remaining time to maturity after forward start date\n% ----------------------\n% Numerical (PROJ) Params \n% ----------------------\n% alph = grid with is 2*alph\n% N = budget: resolution = 2*alph/(N-1), where support is of length 2*alph\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nT = T1 + T2;\n\ndx = 2*alph/(N-1); a = 1/dx;\ndw = 2*pi/(N*dx);\n\nomega = dw*(1:N-1); %We calcuate coefficient of w=0 explicitly\nnbar = N/2;\nxmin = (1 - N/2)*dx;\n\n%%%% Cubic Spline\nb0 = 1208/2520; b1 = 1191/2520; b2 = 120/2520; b3 = 1/2520;\ngrand = @(w)rnCHF2(w).*(sin(w/(2*a))./w).^4./(b0 + b1*cos(w/a) +b2*cos(2*w/a) +b3*cos(3*w/a));\nbeta = real(fft([1/(32*a^4) exp(-1i*xmin*omega).*feval(grand,omega)]));\n\n%FIND Value of E[(1 - exp(X_tau))^+]\nG = zeros(1,N); \n\nG(nbar +1) = 1*(1/24 - 1/20*exp(dx)*(exp(-7/4*dx)/54 + exp(-1.5*dx)/18 + exp(-1.25*dx)/2 + 7*exp(-dx)/27));\n\nG(nbar ) = 1*(.5 -.05*(28/27 + exp(-7/4*dx)/54 + exp(-1.5*dx)/18 + exp(-1.25*dx)/2 + 14*exp(-dx)/27 ...\n + 121/54*exp(-.75*dx) + 23/18*exp(-.5*dx) + 235/54*exp(-.25*dx)));\n\nG(nbar -1) = 1*( 23/24 - exp(-dx)/90*( (28 + 7*exp(-dx))/3 ...\n + ( 14*exp(dx) + exp(-7/4*dx) + 242*cosh(.75*dx) + 470*cosh(.25*dx))/12 ...\n +.25*(exp(-1.5*dx) + 9*exp(-1.25*dx) + 46*cosh(.5*dx))) );\n\nvartheta_star = 1/90*( 14/3*(2+cosh(dx)) ...\n + .5*(cosh(1.5*dx) + 9*cosh(1.25*dx) +23*cosh(.5*dx))...\n + 1/6*(cosh(7/4*dx) + 121*cosh(.75*dx) +235*cosh(.25*dx))); \n\nG(1: nbar -2) = 1 - 1*exp(xmin +dx*(0:nbar-3))*vartheta_star;\nCons = 32*a^4;\n\nVbar2 = Cons/N*G(1,1:(nbar +1))*(beta(1,1:(nbar +1))');\n\n%%% Find Second Expansion\ngrand = @(w)rnCHF1(w).*(sin(w/(2*a))./w).^4./(b0 + b1*cos(w/a) +b2*cos(2*w/a) +b3*cos(3*w/a));\nbeta = real(fft([1/(32*a^4) exp(-1i*xmin*omega).*feval(grand,omega)]));\n\nG(1:N) = exp(xmin + (0:(N-1))*dx);\nVbar1 = Cons/N*G*beta';\nVal_put = exp(-r*T)*Vbar2*Vbar1*S_0*vartheta_star;\n\n\n%%%% PUT CALL PARITY/PRICING FORMULA\nif call ==1\n Val_Proj = S_0*(exp(-q*T)-exp(-r*T2)*exp(-q*T1)) + Val_put; %check this formula\nelse\n Val_Proj = Val_put;\nend\n\nprice = Val_Proj;\n\nend\n\n", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/PROJ/LEVY/Forward_Starting_Options/PROJ_ForwardStarting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6848745904912897}} {"text": "function Lbw = Lbw(angle_of_attack, angle_of_sideslip)\n% Rotation matrix from Wind-axis to Aircraft's body axis\nsa = sind(angle_of_attack);\nca = cosd(angle_of_attack);\nsb = sind(angle_of_sideslip);\ncb = cosd(angle_of_sideslip);\nLbw = [...\n ca*cb -ca*sb -sa\n sb cb 0\n sa*cb -sa*sb ca];\nend", "meta": {"author": "Ro3code", "repo": "aircraft_3d_animation", "sha": "fa0cdebd6988e11761eadd1b6f73a48b8c6a552e", "save_path": "github-repos/MATLAB/Ro3code-aircraft_3d_animation", "path": "github-repos/MATLAB/Ro3code-aircraft_3d_animation/aircraft_3d_animation-fa0cdebd6988e11761eadd1b6f73a48b8c6a552e/live_scripts/Lbw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6848718369075771}} {"text": "function lm = energy_awgn_normapx(en0, epsil)\n% Compute normapx on log m^*(E/N_0, \\epsilon)\n\nloge = log2(exp(1));\nlm = en0 * loge + loge * sqrt(2*en0) * norminv(epsil) + log2(en0)/2;\n%lm = en0 * loge + loge * sqrt(2*en0) * norminv(epsil) + log2(2*en0)/2;\n", "meta": {"author": "yp-mit", "repo": "spectre", "sha": "57af76799e4eb43aa707cc13c4c5220d281e0b78", "save_path": "github-repos/MATLAB/yp-mit-spectre", "path": "github-repos/MATLAB/yp-mit-spectre/spectre-57af76799e4eb43aa707cc13c4c5220d281e0b78/energy-per-bit/energy_awgn_normapx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6848718356990502}} {"text": "function [ball] = pwrbal1(pp,pw,ee)\n%PWRBAL1 compute the ortho-balls associated with a 1-simplex\n%triangulation embedded in R^2 or R^3.\n% [BB] = PWRBAL1(PP,PW,TT) returns the set of power balls\n% associated with the edges in [PP,PW,EE], such that BB =\n% [XC,YC,RC.^2]. PW is a vector of vertex weights.\n\n% Darren Engwirda : 2017 --\n% Email : de2363@columbia.edu\n% Last updated : 02/05/2018\n\n%---------------------------------------------- basic checks\n if ( ~isnumeric(pp) || ...\n ~isnumeric(pw) || ...\n ~isnumeric(ee) )\n error('pwrbal1:incorrectInputClass' , ...\n 'Incorrect input class.');\n end\n\n%---------------------------------------------- basic checks\n if (ndims(pp) ~= +2 || ...\n ndims(pw) ~= +2 || ...\n ndims(ee) ~= +2 )\n error('pwrbal1:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n\n if (size(pp,2) < +2 || ...\n size(pp,1)~= size(pw,1) || ...\n size(ee,2) < +2 )\n error('pwrbal1:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n\n switch (size(pp,2))\n case +2\n %-------------------------------------------- lin offset\n pp12 = pp(ee(:,1),:) - ...\n pp(ee(:,2),:) ;\n\n ww12 = pw(ee(:,1),1) - ...\n pw(ee(:,2),1) ;\n\n dp12 = sum(pp12.*pp12,2) ;\n\n tpwr = +.5 * (ww12+dp12)./dp12 ;\n\n ball = zeros(size(ee,1),3) ;\n ball(:,1:2) = ...\n pp(ee(:,1),:) - tpwr.*pp12 ;\n\n vsq1 = ...\n pp(ee(:,1),:) - ball(:,1:2);\n vsq2 = ...\n pp(ee(:,2),:) - ball(:,1:2);\n\n %-------------------------------------------- mean radii\n rsq1 = sum(vsq1 .^ 2,2) ;\n rsq2 = sum(vsq2 .^ 2,2) ;\n\n rsq1 = rsq1-pw(ee(:,1)) ;\n rsq2 = rsq2-pw(ee(:,2)) ;\n\n ball(:,3) = (rsq1 + rsq2) / 2. ;\n\n case +3\n %-------------------------------------------- lin offset\n pp12 = pp(ee(:,1),:) - ...\n pp(ee(:,2),:) ;\n\n ww12 = pw(ee(:,1),1) - ...\n pw(ee(:,2),1) ;\n\n dp12 = sum(pp12.*pp12,2) ;\n\n tpwr = +.5 * (ww12+dp12)./dp12 ;\n\n ball = zeros(size(ee,1),4) ;\n ball(:,1:3) = ...\n pp(ee(:,1),:) - tpwr.*pp12 ;\n\n vsq1 = ...\n pp(ee(:,1),:) - ball(:,1:3);\n vsq2 = ...\n pp(ee(:,2),:) - ball(:,1:3);\n\n %-------------------------------------------- mean radii\n rsq1 = sum(vsq1 .^ 2,2) ;\n rsq2 = sum(vsq2 .^ 2,2) ;\n\n rsq1 = rsq1-pw(ee(:,1)) ;\n rsq2 = rsq2-pw(ee(:,2)) ;\n\n ball(:,4) = (rsq1 + rsq2) / 2. ;\n\n otherwise\n\n error('pwrbal2:unsupportedDimension' , ...\n 'Dimension not supported.');\n\n end\n\nend\n\n\n\n", "meta": {"author": "dengwirda", "repo": "mesh2d", "sha": "749a81073facc8b5db02e4f7bb0b10c9783cebd3", "save_path": "github-repos/MATLAB/dengwirda-mesh2d", "path": "github-repos/MATLAB/dengwirda-mesh2d/mesh2d-749a81073facc8b5db02e4f7bb0b10c9783cebd3/mesh-ball/pwrbal1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299529686199, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6848314901779373}} {"text": "function res=NODDI_erfi(x)\n% %erfi(x). The Imaginary error function, as it is defined in Mathematica\n% %erfi(z)==erf(iz)/i (z could be complex) using \n% %the incomplete gamma function in matlab: gammainc\n% %Using \"@\": erfi = @(x) real(-sqrt(-1).*sign(x).*gammainc(-x.^2,1/2))\n% %Note: limit(x->0) erfi(x)/x -> 2/sqrt(pi)\n%\n% %Example 1: \n% x=linspace(0.001,6,100);\n% y=exp(-x.^2).*erfi(x)./2./x;\n% figure(1), clf;plot(x,y*sqrt(pi))\n%\n% %Example 2: \n% [x,y]=meshgrid(linspace(-3,3,180),linspace(-3,3,180));\n% z=x+i*y;\n% figure(1), clf;contourf(x,y,log(erfi(z)))\n% axis equal;axis off\n\n% MATLAB only:\n% xc=5.7;%cut for asymptotic approximation (when x is real)\n% res=~isreal(x).*(-(sqrt(-x.^2)./(x+isreal(x))).*gammainc(-x.^2,1/2))+...\n% isreal(x).*real(-sqrt(-1).*sign(x).*((x=xc).*exp(x.^2)./x/sqrt(pi));\n\ntry % FASTER AND COMPATIBLE WITH BOTH MATLAB AND OCTAVE:\n res = Faddeeva_erfi(x);\ncatch\n if ~moxunit_util_platform_is_octave\n xc=5.7;%cut for asymptotic approximation (when x is real)\n res=~isreal(x).*(-(sqrt(-x.^2)./(x+isreal(x))).*gammainc(-x.^2,1/2))+...\n isreal(x).*real(-sqrt(-1).*sign(x).*((x=xc).*exp(x.^2)./x/sqrt(pi));\n else\n error('Faddeeva_erfi was not build correctly. run Faddeeva_build.m')\n end\nend\n \n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NODDI_toolbox_v1.0/models/watson/NODDI_erfi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6848314864010324}} {"text": "function auc = aucroc(p_predicted, p_target, freq)\n\n % Count observations by class\n nTarget = sum(freq .* p_target);\n nBackground = sum(freq .* (1-p_target));\n\n % Rank data\n R = tiedrank(p_predicted); % 'tiedrank' from Statistics Toolbox\n [R_uniq, I, J] = unique(R);\n [R_mean,R_num] = grpstats(freq,R,{'mean','numel'});\n R_freq = R_mean .* R_num;\n\n % adjust for counts\n rank_start_freq = cumsum(R_freq);\n rank_start_freq = [0; rank_start_freq(1:(end-1))] + 1;\n rank_mean_freq = (2*rank_start_freq+R_freq-1)/2;\n \n rank_orig = rank_mean_freq(J);\n\n % Calculate AUC\n %Error = (sum(R(Actual == 1)) - (nTarget^2 + nTarget)/2) / (nTarget * nBackground);\n auc = (sum(rank_orig .* p_target .* freq) - (nTarget^2 + nTarget)/2) / (nTarget * nBackground);\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/19468-auroc-area-under-receiver-operating-characteristic/aucroc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.684831485676176}} {"text": "function wavelet_test09 ( )\n\n%*****************************************************************************80\n%\n%% WAVELET_TEST09 tests DAUB18_TRANSFORM and DAUB18_TRANSFORM_INVERSE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 July 2011\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'WAVELET_TEST09\\n' );\n fprintf ( 1, ' DAUB18_TRANSFORM computes the DAUB18 transform of a vector.\\n' );\n fprintf ( 1, ' DAUB18_TRANSFORM_INVERSE inverts it.\\n' );\n%\n% Random data.\n%\n n = 16;\n seed = 123456789;\n [ u, seed ] = r8vec_uniform_01 ( n, seed );\n\n v = daub18_transform ( n, u );\n\n w = daub18_transform_inverse ( n, v );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' i U(i) D18(U)(i) D18inv(D18(U))(i)\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %2d %10.4f %10.4f %10.4f\\n', i, u(i), v(i), w(i) );\n end\n%\n% Constant signal.\n%\n n = 8;\n u(1:n) = 1.0;\n\n v = daub18_transform ( n, u );\n\n w = daub18_transform_inverse ( n, v );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' i U(i) D18(U)(i) D18inv(D18(U))(i)\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %2d %10.4f %10.4f %10.4f\\n', i, u(i), v(i), w(i) );\n end\n%\n% Linear signal.\n%\n n = 16;\n a_first = 1.0;\n a_last = n;\n u = linspace ( a_first, a_last, n );\n\n v = daub18_transform ( n, u );\n\n w = daub18_transform_inverse ( n, v );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' i U(i) D18(U)(i) D18inv(D18(U))(i)\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %2d %10.4f %10.4f %10.4f\\n', i, u(i), v(i), w(i) );\n end\n%\n% Quadratic data.\n%\n n = 8;\n u(1) = 25.0;\n u(2) = 16.0;\n u(3) = 9.0;\n u(4) = 4.0;\n u(5) = 1.0;\n u(6) = 0.0;\n u(7) = 1.0;\n u(8) = 4.0;\n\n v = daub18_transform ( n, u );\n\n w = daub18_transform_inverse ( n, v );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' i U(i) D18(U)(i) D18inv(D18(U))(i)\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %2d %10.4f %10.4f %10.4f\\n', i, u(i), v(i), w(i) );\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/wavelet/wavelet_test09.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.6848167216124111}} {"text": "% sgwt_randmat : Compute random (Erdos-Renyi model) graph\n%\n% function A=sgwt_randmat(N,thresh)\n%\n% Inputs : \n% N - number of vertices\n% thresh - probability of connection of each edge\n%\n% Outputs :\n% A - adjacency matrix\n\n% This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox)\n% Copyright (C) 2010, David K. Hammond. \n%\n% The SGWT toolbox 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% The SGWT toolbox 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 the SGWT toolbox. If not, see .\n\nfunction [A]=sgwt_randmat(N,thresh)\n assert(thresh<=1 && thresh>=0);\n A=rand(N)>1-thresh;\n B=triu(A);\n A=B+B';\n for i=1:size(A,1)\n A(i,i)=0;\n end\n A=sparse(A);\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/test_gsptoolbox/old/sgwt_toolbox/sgwt_randmat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6847831062260002}} {"text": "function [ row, col, a, seed ] = wathen_st ( nx, ny, nz_num, seed )\n\n%*****************************************************************************80\n%\n%% WATHEN_ST: Wathen matrix stored in sparse triplet format.\n%\n% Discussion:\n%\n% When dealing with sparse matrices in MATLAB, it can be much more efficient\n% to work first with a triple of I, J, and X vectors, and only once\n% they are complete, convert to MATLAB's sparse format.\n%\n% The Wathen matrix is a finite element matrix which is sparse.\n%\n% The entries of the matrix depend in part on a physical quantity\n% related to density. That density is here assigned random values between\n% 0 and 100.\n%\n% The matrix order N is determined by the input quantities NX and NY,\n% which would usually be the number of elements in the X and Y directions.\n%\n% The value of N is\n%\n% N = 3*NX*NY + 2*NX + 2*NY + 1,\n%\n% The matrix is the consistent mass matrix for a regular NX by NY grid\n% of 8 node serendipity elements.\n%\n% The local element numbering is\n%\n% 3--2--1\n% | |\n% 4 8\n% | |\n% 5--6--7\n%\n% Here is an illustration for NX = 3, NY = 2:\n%\n% 23-24-25-26-27-28-29\n% | | | |\n% 19 20 21 22\n% | | | |\n% 12-13-14-15-16-17-18\n% | | | |\n% 8 9 10 11\n% | | | |\n% 1--2--3--4--5--6--7\n%\n% For this example, the total number of nodes is, as expected,\n%\n% N = 3 * 3 * 2 + 2 * 2 + 2 * 3 + 1 = 29\n%\n% The matrix is symmetric positive definite for any positive values of the\n% density RHO(X,Y).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 July 2014\n%\n% Author:\n%\n% Original MATLAB version by Nicholas Higham.\n% Modifications by Tim Davis.\n% Modifications by John Burkardt.\n%\n% Reference:\n%\n% Nicholas Higham,\n% Algorithm 694: A Collection of Test Matrices in MATLAB,\n% ACM Transactions on Mathematical Software,\n% Volume 17, Number 3, September 1991, pages 289-305.\n%\n% Andrew Wathen,\n% Realistic eigenvalue bounds for the Galerkin mass matrix,\n% IMA Journal of Numerical Analysis,\n% Volume 7, Number 4, October 1987, pages 449-457.\n%\n% Parameters:\n%\n% Input, integer NX, NY, values which determine the size of the matrix.\n%\n% Input, integer NZ_NUM, the number of values used to describe the matrix.\n%\n% Input/output, integer SEED, the random number seed.\n%\n% Output, integer ROW(NZ_NUM), COL(NZ_NUM), the row and column indices \n% of the nonzero entries.\n%\n% Output, real A(NZ_NUM), the nonzero values.\n%\n if ( nargin < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'WATHEN_ST - Fatal error!\\n' );\n fprintf ( 1, ' Not enough input.\\n' );\n error ( 'WATHEN_ST - Fatal error!' );\n end\n\n if ( nargin < 2 )\n ny = nx;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' NY was not supplied. Setting NY = NX = %d.\\n', ny );\n end\n\n if ( nargin < 3 )\n nz_num = wathen_st_size ( nx, ny );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' NZ_NUM was not supplied. NZ_NUM = %d\\n', nz_num );\n end\n\n if ( nargin < 4 )\n seed = 123456789;\n end\n\n em = [\n 6.0, -6.0, 2.0, -8.0, 3.0, -8.0, 2.0, -6.0;\n -6.0, 32.0, -6.0, 20.0, -8.0, 16.0, -8.0, 20.0;\n 2.0, -6.0, 6.0, -6.0, 2.0, -8.0, 3.0, -8.0;\n -8.0, 20.0, -6.0, 32.0, -6.0, 20.0, -8.0, 16.0;\n 3.0, -8.0, 2.0, -6.0, 6.0, -6.0, 2.0, -8.0;\n -8.0, 16.0, -8.0, 20.0, -6.0, 32.0, -6.0, 20.0;\n 2.0, -8.0, 3.0, -8.0, 2.0, -6.0, 6.0, -6.0;\n -6.0, 20.0, -8.0, 16.0, -8.0, 20.0, -6.0, 32.0 ]';\n\n row = zeros(nz_num,1);\n col = zeros(nz_num,1);\n a = zeros(nz_num,1);\n\n node = zeros(8,1);\n\n k = 0;\n\n for j = 1 : ny\n for i = 1 : nx\n\n node(1) = 3 * j * nx + 2 * i + 2 * j + 1;\n node(2) = node(1) - 1;\n node(3) = node(2) - 1;\n node(4) = ( 3 * j - 1 ) * nx + 2 * j + i - 1;\n node(5) = 3 * ( j - 1 ) * nx + 2 * i + 2 * j - 3;\n node(6) = node(5) + 1;\n node(7) = node(6) + 1;\n node(8) = node(4) + 1;\n\n [ rho, seed ] = r8_uniform_01 ( seed );\n rho = 100.0 * rho;\n\n for krow = 1 : 8\n for kcol = 1 : 8\n k = k + 1;\n row(k) = node(krow);\n col(k) = node(kcol);\n a(k) = rho * em(krow,kcol);\n end\n end\n\n end\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/wathen/wathen_st.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6847830992154498}} {"text": "classdef MW11 < PROBLEM\n% \n% Constrained benchmark MOP proposed by Ma and Wang\n\n%------------------------------- Reference --------------------------------\n% Z. Ma and Y. Wang, Evolutionary constrained multiobjective optimization:\n% Test suite construction and performance comparisons. IEEE Transactions on\n% Evolutionary Computation, 2019, 23(6): 972-986.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n methods\n %% Default settings of the problem\n function Setting(obj)\n obj.M = 2;\n if isempty(obj.D); obj.D = 15; end\n obj.lower = zeros(1,obj.D);\n obj.upper = ones(1,obj.D);\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values and constraint violations\n function Population = Evaluation(obj,varargin)\n X = varargin{1};\n X = max(min(X,repmat(obj.upper,size(X,1),1)),repmat(obj.lower,size(X,1),1));\n g = 1 + sum(2*(X(:,obj.M:end) + (X(:,obj.M-1:end-1) - 0.5).^2 - 1).^2,2);\n PopObj(:,1) = g.*X(:,1)*sqrt(1.9999);\n PopObj(:,2) = g.*sqrt(2 - (PopObj(:,1)./g).^2);\n PopCon(:,1) = -(3 - PopObj(:,1).^2 - PopObj(:,2)).*(3 - 2*PopObj(:,1).^2 - PopObj(:,2));\n PopCon(:,2) = (3 - 0.625*PopObj(:,1).^2 - PopObj(:,2)).*(3 - 7*PopObj(:,1).^2 - PopObj(:,2));\n PopCon(:,3) = -(1.62 - 0.18*PopObj(:,1).^2 - PopObj(:,2)).*(1.125 - 0.125*PopObj(:,1).^2 - PopObj(:,2));\n PopCon(:,4) = (2.07 - 0.23*PopObj(:,1).^2 - PopObj(:,2)).*(0.63 - 0.07*PopObj(:,1).^2 - PopObj(:,2));\n Population = SOLUTION(X,PopObj,PopCon,varargin{2:end});\n obj.FE = obj.FE + length(Population);\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n R(:,1) = (0:1/(N-1):1)';\n R(:,2) = 1 - R(:,1);\n R = R./repmat(sqrt(sum(R.^2,2)/2),1,2);\n c1 = (3 - R(:,1).^2 - R(:,2)).*(3 - 2*R(:,1).^2 - R(:,2));\n c2 = (3 - 0.625*R(:,1).^2 - R(:,2)).*(3 - 7*R(:,1).^2 - R(:,2));\n c3 = (1.62 - 0.18*R(:,1).^2 - R(:,2)).*(1.125 - 0.125*R(:,1).^2 - R(:,2));\n c4 = (2.07 - 0.23*R(:,1).^2 - R(:,2)).*(0.63 - 0.07*R(:,1).^2 - R(:,2));\n invalid = c1<0 | c2>0 | c3<0 | c4>0;\n while any(invalid)\n R(invalid,:) = R(invalid,:).*1.001;\n R(any(R>2.2,2),:) = [];\n c1 = (3 - R(:,1).^2 - R(:,2)).*(3 - 2*R(:,1).^2 - R(:,2));\n c2 = (3 - 0.625*R(:,1).^2 - R(:,2)).*(3 - 7*R(:,1).^2 - R(:,2));\n c3 = (1.62 - 0.18*R(:,1).^2 - R(:,2)).*(1.125 - 0.125*R(:,1).^2 - R(:,2));\n c4 = (2.07 - 0.23*R(:,1).^2 - R(:,2)).*(0.63 - 0.07*R(:,1).^2 - R(:,2));\n invalid = c1<0 | c2>0 | c3<0 | c4>0;\n end\n R = [R;1,1];\n R = R(NDSort(R,1)==1,:);\n end\n %% Generate the feasible region\n function R = GetPF(obj)\n [x,y] = meshgrid(linspace(0,2.1,400));\n z = nan(size(x));\n fes1 = -(3-x.^2-y).*(3-2*x.^2-y) <= 0;\n fes2 = (3-0.625*x.^2-y).*(3-7*x.^2-y) <= 0;\n fes3 = -(1.62-0.18*x.^2-y).*(1.125-0.125*x.^2-y) <= 0;\n fes4 = (2.07-0.23*x.^2-y).*(0.63-0.07*x.^2-y) <= 0;\n z(fes1 & fes2 & fes3 & fes4 & x.^2+y.^2>=2) = 0;\n R = {x,y,z};\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/MW/MW11.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6847830900076777}} {"text": "% op_makePhaseDrift.m\n% Jamie Near, McGill University 2014.\n% \n% USAGE:\n% [out,phDrift]=op_makePhaseDrift(in,totalDrift,noise);\n% \n% DESCRIPTION:\n% Add phase drift to a dataset containing multiple averages. This is generally \n% used to generate simulated datasets with phase drift. \n% \n% INPUTS:\n% in = input data in matlab structure format.\n% totalDrift = total amount of phase drift (in degrees) to add over the whole scan.\n% If totalDrift is a scalar, then a constant slope of drift\n% will be added. If totalDrift is a vector or matrix with dimensions\n% equal to the dimensions of the input data, then this\n% vector specifies the drift applied to each average.\n% noise = the standard deviation of noise to add to the phase drift\n% function.\n%\n% OUTPUTS:\n% out = Output dataset with phase drift added.\n% phDrift = Vector of phase drift values that were added (in degrees).\n\n\nfunction [out,phDrift]=op_makePhaseDrift(in,totalDrift,noise);\n%out=op_makedrift(in,totalDrift);\n\n%First make the matrices needed for multiplication\nif any(totalDrift)\n if isequal(size(totalDrift),[in.averages/in.subspecs,in.subspecs])\n ph=totalDrift;\n else\n ph=linspace(0,totalDrift,in.averages*in.subspecs);\n ph=reshape(ph,in.subspecs,in.averages);\n ph=ph';\n end\nelse\n ph=zeros(in.averages,in.subspecs);\nend\nphnoise=noise*randn(size(ph));\nphDrift=ph+phnoise;\n%PH=repmat(phDrift',in.sz(1),1);\nphDrift_shft=shiftdim(phDrift,-1);\nPH=repmat(phDrift_shft,in.sz(1),1,1);\n\n%Now apply the drift to the fids;\nfids=in.fids.*exp(-1i*PH*pi/180);\n\n%Now re-calculate specs using ifft\nspecs=fftshift(ifft(fids,[],in.dims.t),in.dims.t);\n\n%FILLING IN DATA STRUCTURES\nout=in;\nout.fids=fids;\nout.specs=specs;\n\n%FILLING IN THE FLAGS\nout.flags=in.flags;\n", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/processingTools/op_makePhaseDrift.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7718434925908524, "lm_q1q2_score": 0.6847830876533739}} {"text": "function [reg_c,rho_c,eta_c] = l_corner(rho,eta,reg_param,U,s,b,method,M)\n%L_CORNER Locate the \"corner\" of the L-curve.\n%\n% [reg_c,rho_c,eta_c] =\n% l_corner(rho,eta,reg_param)\n% l_corner(rho,eta,reg_param,U,s,b,method,M)\n% l_corner(rho,eta,reg_param,U,sm,b,method,M) , sm = [sigma,mu]\n%\n% Locates the \"corner\" of the L-curve in log-log scale.\n%\n% It is assumed that corresponding values of || A x - b ||, || L x ||,\n% and the regularization parameter are stored in the arrays rho, eta,\n% and reg_param, respectively (such as the output from routine l_curve).\n%\n% If nargin = 3, then no particular method is assumed, and if\n% nargin = 2 then it is issumed that reg_param = 1:length(rho).\n%\n% If nargin >= 6, then the following methods are allowed:\n% method = 'Tikh' : Tikhonov regularization\n% method = 'tsvd' : truncated SVD or GSVD\n% method = 'dsvd' : damped SVD or GSVD\n% method = 'mtsvd' : modified TSVD,\n% and if no method is specified, 'Tikh' is default. If the Spline Toolbox\n% is not available, then only 'Tikh' and 'dsvd' can be used.\n%\n% An eighth argument M specifies an upper bound for eta, below which\n% the corner should be found.\n\n% Per Christian Hansen, IMM, July 26, 2007.\n% \n%\n% This file is part of regtools [1] and covered by the BSD License\n%\n% Copyright (c) 2008, Per Christian Hansen\n% All rights reserved.\n% \n% Redistribution and use in source and binary forms, with or without \n% modification, are permitted provided that the following conditions are \n% met:\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% \n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE \n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n% POSSIBILITY OF SUCH DAMAGE.\n%\n% References: \n% [1] http://www.mathworks.com/matlabcentral/fileexchange/file_infos/52-regtools\n\n\n% Set default regularization method.\nif (nargin <= 3)\n method = 'none';\n if (nargin==2), reg_param = (1:length(rho))'; end\nelse\n if (nargin==6), method = 'Tikh'; end\nend\n\n% Set this logical variable to 1 (true) if the corner algorithm\n% should always be used, even if the Spline Toolbox is available.\nalwayscorner = 0;\n\n% Set threshold for skipping very small singular values in the\n% analysis of a discrete L-curve.\ns_thr = eps; % Neglect singular values less than s_thr.\n\n% Set default parameters for treatment of discrete L-curve.\ndeg = 2; % Degree of local smooting polynomial.\nq = 2; % Half-width of local smoothing interval.\norder = 4; % Order of fitting 2-D spline curve.\n\n% Initialization.\nif (length(rho) < order)\n error('Too few data points for L-curve analysis')\nend\nif (nargin > 3)\n [p,ps] = size(s); [m,n] = size(U);\n beta = U'*b;\n if (m>n), b0 = b - U*beta; end\n if (ps==2)\n s = s(p:-1:1,1)./s(p:-1:1,2);\n beta = beta(p:-1:1);\n end\n xi = beta./s;\nend\n\n% Restrict the analysis of the L-curve according to M (if specified).\nif (nargin==8)\n index = find(eta < M);\n rho = rho(index); eta = eta(index); reg_param = reg_param(index);\nend\n\nif (strncmp(method,'Tikh',4) | strncmp(method,'tikh',4))\n\n % The L-curve is differentiable; computation of curvature in\n % log-log scale is easy.\n\n % Compute g = - curvature of L-curve.\n g = lcfun(reg_param,s,beta,xi);\n\n % Locate the corner. If the curvature is negative everywhere,\n % then define the leftmost point of the L-curve as the corner.\n [gmin,gi] = min(g);\n reg_c = fminbnd('lcfun',...\n reg_param(min(gi+1,length(g))),reg_param(max(gi-1,1)),...\n optimset('Display','off'),s,beta,xi); % Minimizer.\n kappa_max = - lcfun(reg_c,s,beta,xi); % Maximum curvature.\n\n if (kappa_max < 0)\n lr = length(rho);\n reg_c = reg_param(lr); rho_c = rho(lr); eta_c = eta(lr);\n else\n f = (s.^2)./(s.^2 + reg_c^2);\n eta_c = norm(f.*xi);\n rho_c = norm((1-f).*beta);\n if (m>n), rho_c = sqrt(rho_c^2 + norm(b0)^2); end\n end\n\nelseif (strncmp(method,'tsvd',4) | strncmp(method,'tgsv',4) | ...\n strncmp(method,'mtsv',4) | strncmp(method,'none',4))\n\n % Use the adaptive pruning algorithm to find the corner, if the\n % Spline Toolbox is not available.\n if ~exist('splines','dir') | alwayscorner\n %error('The Spline Toolbox in not available so l_corner cannot be used')\n reg_c = corner(rho,eta);\n rho_c = rho(reg_c);\n eta_c = eta(reg_c);\n return\n end\n\n % Othersise use local smoothing followed by fitting a 2-D spline curve\n % to the smoothed discrete L-curve. Restrict the analysis of the L-curve\n % according to s_thr.\n if (nargin > 3)\n if (nargin==8) % In case the bound M is in action.\n s = s(index,:);\n end\n index = find(s > s_thr);\n rho = rho(index); eta = eta(index); reg_param = reg_param(index);\n end\n\n % Convert to logarithms.\n lr = length(rho);\n lrho = log(rho); leta = log(eta); slrho = lrho; sleta = leta;\n\n % For all interior points k = q+1:length(rho)-q-1 on the discrete\n % L-curve, perform local smoothing with a polynomial of degree deg\n % to the points k-q:k+q.\n v = (-q:q)'; A = zeros(2*q+1,deg+1); A(:,1) = ones(length(v),1);\n for j = 2:deg+1, A(:,j) = A(:,j-1).*v; end\n for k = q+1:lr-q-1\n cr = A\\lrho(k+v); slrho(k) = cr(1);\n ce = A\\leta(k+v); sleta(k) = ce(1);\n end\n\n % Fit a 2-D spline curve to the smoothed discrete L-curve.\n sp = spmak((1:lr+order),[slrho';sleta']);\n pp = ppbrk(sp2pp(sp),[4,lr+1]);\n\n % Extract abscissa and ordinate splines and differentiate them.\n % Compute as many function values as default in spleval.\n P = spleval(pp); dpp = fnder(pp);\n D = spleval(dpp); ddpp = fnder(pp,2);\n DD = spleval(ddpp);\n ppx = P(1,:); ppy = P(2,:);\n dppx = D(1,:); dppy = D(2,:);\n ddppx = DD(1,:); ddppy = DD(2,:);\n\n % Compute the corner of the discretized .spline curve via max. curvature.\n % No need to refine this corner, since the final regularization\n % parameter is discrete anyway.\n % Define curvature = 0 where both dppx and dppy are zero.\n k1 = dppx.*ddppy - ddppx.*dppy;\n k2 = (dppx.^2 + dppy.^2).^(1.5);\n I_nz = find(k2 ~= 0);\n kappa = zeros(1,length(dppx));\n kappa(I_nz) = -k1(I_nz)./k2(I_nz);\n [kmax,ikmax] = max(kappa);\n x_corner = ppx(ikmax); y_corner = ppy(ikmax);\n\n % Locate the point on the discrete L-curve which is closest to the\n % corner of the spline curve. Prefer a point below and to the\n % left of the corner. If the curvature is negative everywhere,\n % then define the leftmost point of the L-curve as the corner.\n if (kmax < 0)\n reg_c = reg_param(lr); rho_c = rho(lr); eta_c = eta(lr);\n else\n index = find(lrho < x_corner & leta < y_corner);\n if ~isempty(index)\n [dummy,rpi] = min((lrho(index)-x_corner).^2 + (leta(index)-y_corner).^2);\n rpi = index(rpi);\n else\n [dummy,rpi] = min((lrho-x_corner).^2 + (leta-y_corner).^2);\n end\n reg_c = reg_param(rpi); rho_c = rho(rpi); eta_c = eta(rpi);\n end\n\nelseif (strncmp(method,'dsvd',4) | strncmp(method,'dgsv',4))\n\n % The L-curve is differentiable; computation of curvature in\n % log-log scale is easy.\n\n % Compute g = - curvature of L-curve.\n g = lcfun(reg_param,s,beta,xi,1);\n\n % Locate the corner. If the curvature is negative everywhere,\n % then define the leftmost point of the L-curve as the corner.\n [gmin,gi] = min(g);\n reg_c = fminbnd('lcfun',...\n reg_param(min(gi+1,length(g))),reg_param(max(gi-1,1)),...\n optimset('Display','off'),s,beta,xi,1); % Minimizer.\n kappa_max = - lcfun(reg_c,s,beta,xi,1); % Maximum curvature.\n\n if (kappa_max < 0)\n lr = length(rho);\n reg_c = reg_param(lr); rho_c = rho(lr); eta_c = eta(lr);\n else\n f = s./(s + reg_c);\n eta_c = norm(f.*xi);\n rho_c = norm((1-f).*beta);\n if (m>n), rho_c = sqrt(rho_c^2 + norm(b0)^2); end\n end\n\nelse\n error('Illegal method')\nend", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/utils/l_corner.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579722, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.6847641458442786}} {"text": "%H2E Homogeneous to Euclidean \n%\n% E = H2E(H) is the Euclidean version (K-1xN) of the homogeneous \n% points H (KxN) where each column represents one point in P^K.\n%\n% Reference::\n% - Robotics, Vision & Control: Second Edition, P. Corke, Springer 2016; p604.\n%\n% See also E2H.\n\n% Copyright (C) 1993-2019 Peter I. Corke\n%\n% This file is part of The Spatial Math Toolbox for MATLAB (SMTB).\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, including without limitation the rights\n% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n% of the Software, and to permit persons to whom the Software is furnished to do\n% so, subject to the following conditions:\n%\n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n% FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n% COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n% IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n%\n% https://github.com/petercorke/spatial-math\n\nfunction e = h2e(h)\n\n if isvector(h)\n h = h(:);\n end\n e = h(1:end-1,:) ./ repmat(h(end,:), numrows(h)-1, 1);\n\n", "meta": {"author": "petercorke", "repo": "spatialmath-matlab", "sha": "6eeff4a79f14286705560b84f1fe72e0b7e0e7f7", "save_path": "github-repos/MATLAB/petercorke-spatialmath-matlab", "path": "github-repos/MATLAB/petercorke-spatialmath-matlab/spatialmath-matlab-6eeff4a79f14286705560b84f1fe72e0b7e0e7f7/h2e.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.6847641447658428}} {"text": "function r8poly_lagrange_0_test ( )\n\n%*****************************************************************************80\n%\n%% R8POLY_LAGRANGE_0_TEST tests R8POLY_LAGRANGE_0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n npol = 5;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8POLY_LAGRANGE_0_TEST\\n' );\n fprintf ( 1, ' R8POLY_LAGRANGE_0 evaluates the Lagrange\\n' );\n fprintf ( 1, ' factor W(X) at a point.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The number of data points is %d\\n', npol );\n%\n% Set the abscissas of the polynomials.\n%\n xlo = 0.0;\n xhi = npol - 1;\n\n xpol = r8vec_even ( npol, xlo, xhi );\n\n r8vec_print ( npol, xpol, ' Abscissas:' );\n%\n% Evaluate W(X).\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X W(X)\\n' );\n fprintf ( 1, '\\n' );\n\n nx = 4 * npol - 1;\n\n for ival = 1 : nx\n\n xval = r8vec_even_select ( nx, xlo, xhi, ival );\n\n w = r8poly_lagrange_0 ( npol, xpol, xval );\n\n fprintf ( 1, '%12f %12e\\n', xval, w );\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/r8lib/r8poly_lagrange_0_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.684764140625684}} {"text": "function res = calc_pot_values(w)\n%\n%calculate potential values for non obstacle and foal locations in given world\n%\nr = size(w,1);\nc = size(w,2);\nfor t = size(w,3):-1:1\n for x = 1:r\n for y = 1:c\n if w(x,y,t) == -1\n n = w(x,y,t+1);\n if x ~= 1\n n = n + w(x-1,y,t+1);\n else\n n = n + 1;% boundary condition\n end\n if x ~= r\n n = n + w(x+1,y,t+1);\n else\n n = n + 1;\n end\n if y ~= 1\n n = n + w(x,y-1,t+1);\n else\n n = n + 1;\n end\n if y ~= c\n n = n + w(x,y+1,t+1);\n else\n n = n + 1;\n end\n w(x,y,t) = n / 5;% take average of neighbors\n end\n end\n end\nend\nres = w;\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/22346-temporal-potential-function-based-path-planner-for-dynamic-environments/TempPP/calc_pot_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6847621339893804}} {"text": "function r = randp(lambda)\n% randp(lambda) returns Poisson distributed Vector with mean lambda\n\ntry\n r = poissrnd(lambda);\n return\nend\n\nlambda = reshape(lambda,1,[]);\naktiv = find(lambda > 1e-10);\nll = log(lambda(aktiv));\nr(aktiv) = rand(1,length(aktiv));\nr(find(lambda < 1e-10)) = 0;\n\ni = 0;\nwhile length(aktiv) > 0\n\t\tr(aktiv) = r(aktiv) - exp(i*ll - lambda(aktiv) - gammaln(i+1));\n\t\tind = find(r(aktiv)<=0);\n\t\tr(aktiv(ind)) = i;\n\t\taktiv(ind) = [];\n\t\tll(ind) = [];\n\t\ti = i + 1;\nend\n\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/tools/statistic_tools/randp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6847621338566332}} {"text": "function phi = correct_azimuth(phi)\n%CORRECT_AZIMUTH ensures azimuth angle between -pi and +pi-eps \n%\n% Usage: phi = correct_azimuth(phi)\n%\n% Input parameters:\n% phi - azimuth / rad. Can be a single value or a matrix.\n%\n% Output paramteres:\n% phi - angle between -pi and +pi-eps / rad\n%\n% See also: correct_elevation, get_ir\n\n%*****************************************************************************\n% The MIT License (MIT) *\n% *\n% Copyright (c) 2010-2019 SFS Toolbox Developers *\n% *\n% Permission is hereby granted, free of charge, to any person obtaining a *\n% copy of this software and associated documentation files (the \"Software\"), *\n% to deal in the Software without restriction, including without limitation *\n% the rights to use, copy, modify, merge, publish, distribute, sublicense, *\n% and/or sell copies of the Software, and to permit persons to whom the *\n% Software is furnished to do so, subject to the following conditions: *\n% *\n% The above copyright notice and this permission notice shall be included in *\n% all copies or substantial portions of the Software. *\n% *\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *\n% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *\n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *\n% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\n% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *\n% DEALINGS IN THE SOFTWARE. *\n% *\n% The SFS Toolbox allows to simulate and investigate sound field synthesis *\n% methods like wave field synthesis or higher order ambisonics. *\n% *\n% https://sfs.readthedocs.io sfstoolbox@gmail.com *\n%*****************************************************************************\n\n\n%% ===== Checking of input parameters ==================================\nnargmin = 1;\nnargmax = 1;\nnarginchk(nargmin,nargmax);\n\n\n%% ===== Computation ====================================================\n% Ensure -2pi <= phi <= 2pi\nphi = rem(phi,2*pi);\n% Ensure -pi <= phi < pi\nphi(phi<-pi) = phi(phi<-pi) + 2*pi;\nphi(phi>=pi) = phi(phi>=pi) - 2*pi;\n", "meta": {"author": "sfstoolbox", "repo": "sfs-matlab", "sha": "02194f0243d1ead26572f760032c40527718919d", "save_path": "github-repos/MATLAB/sfstoolbox-sfs-matlab", "path": "github-repos/MATLAB/sfstoolbox-sfs-matlab/sfs-matlab-02194f0243d1ead26572f760032c40527718919d/SFS_general/correct_azimuth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6847621314901644}} {"text": "function plotConfMat(varargin)\n%PLOTCONFMAT plots the confusion matrix with colorscale, absolute numbers\n% and precision normalized percentages\n%\n% usage: \n% PLOTCONFMAT(confmat) plots the confmat with integers 1 to n as class labels\n% PLOTCONFMAT(confmat, labels) plots the confmat with the specified labels\n%\n% Vahe Tshitoyan\n% 20/08/2017\n%\n% Arguments\n% confmat: a square confusion matrix\n% labels (optional): vector of class labels\n\n% number of arguments\nswitch (nargin)\n case 0\n confmat = 1;\n labels = {'1'};\n case 1\n confmat = varargin{1};\n labels = 1:size(confmat, 1);\n otherwise\n confmat = varargin{1};\n labels = varargin{2};\nend\n\nconfmat(isnan(confmat))=0; % in case there are NaN elements\nnumlabels = size(confmat, 1); % number of labels\n\n% calculate the percentage accuracies\nconfpercent = 100*confmat./repmat(sum(confmat, 1),numlabels,1);\n\n% plotting the colors\nimagesc(confpercent);\ntitle(sprintf('Accuracy: %.2f%%', 100*trace(confmat)/sum(confmat(:))));\n%ylabel('Predicted Class'); xlabel('Target Class');\nylabel('Predicted Class'); xlabel('Target Class');\n\n% set the colormap\ncolormap(flipud(gray));\n\n% Create strings from the matrix values and remove spaces\ntextStrings = num2str([confpercent(:), confmat(:)], '%.1f%%\\n%d\\n');\ntextStrings = strtrim(cellstr(textStrings));\n\n% Create x and y coordinates for the strings and plot them\n[x,y] = meshgrid(1:numlabels);\nhStrings = text(x(:),y(:),textStrings(:), ...\n 'HorizontalAlignment','center');\n\n% Get the middle value of the color range\nmidValue = mean(get(gca,'CLim'));\n\n% Choose white or black for the text color of the strings so\n% they can be easily seen over the background color\ntextColors = repmat(confpercent(:) > midValue,1,3);\nset(hStrings,{'Color'},num2cell(textColors,2));\n\n% Setting the axis labels\nset(gca,'XTick',1:numlabels,...\n 'XTickLabel',labels,...\n 'YTick',1:numlabels,...\n 'YTickLabel',labels,...\n 'TickLength',[0 0]);\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/analysis/plotConfMat/plotConfMat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6847610310017785}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n%\n% problem 11 - graph of r[n] and of r[n+1]\n\n\n% r[n]\n n=-3:6;\n u=(n>=0);\n r=n.*u;\n \n stem(n,r)\n title('Unit ramp sequence r[n]')\n ylim([-.1 6.1])\n\n \n\n% r[n+1]\n figure\n n=-3:6;\n u1=(n>=-1);\n r=(n+1).*u1;\n \n stem(n,r)\n title('Unit ramp sequence r[n+1]')\n ylim([-.1 7.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/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/2/c2711.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.863391617003942, "lm_q1q2_score": 0.684761021203932}} {"text": "\nfunction [ NRI , pval ] = NetReclassificationImprovement( pred_old , pred_new , outcome )\n% Net Reclassification Index (NRI) \n% Compare classification of an old vs new classification technique\n% Usage:\n% [ NRI , pval ] = NetReclassificationImprovement( pred_old , pred_new , outcome )\n% \n% http://www.epibiostat.ucsf.edu/courses/RoadmapK12/SIGS/Pencina.pdf\n% Statist. Med. (in press) (www.interscience.wiley.com) DOI: 10.1002/sim.2929\n% Evaluating the added predictive ability of a new marker: From area under the ROC curve to reclassi\ufffdcation and beyond\n% Michael J. Pencina Ralph B. D'agostino Sr Ralph B. D'Agostino Jr and Ramachandran S. Vasan\n% \n% (c) Louis Mayaud, 2011 (louis.mayaud@gmail.com) \n% Please reference :\n% Mayaud, Louis, et al. \"Dynamic Data During Hypotensive Episode Improves\n% Mortality Predictions Among Patients With Sepsis and Hypotension*.\"\n% Critical care medicine 41.4 (2013): 954-962.\n\n\n% Remove NaNs\nIdx = (isnan(pred_old) & isnan(pred_new));\npred_old(Idx) = [];\npred_new(Idx) = [];\n\n% Need to define the following probabilities\nPEventUp = sum(outcome==1 & pred_old==0 & pred_new==1)/sum(outcome==1); \nPEventDown = sum(outcome==1 & pred_old==1 & pred_new==0)/sum(outcome==1); \nPNoneventUp= sum(outcome==0 & pred_old==0 & pred_new==1)/sum(outcome==0); \nPNoneventDown= sum(outcome==0 & pred_old==1 & pred_new==0)/sum(outcome==0); \n\nNRI = (PEventUp - PEventDown) - (PNoneventUp - PNoneventDown) ;\nz = abs(NRI)/sqrt( (PEventUp + PEventDown)/sum(outcome==1) + (PNoneventUp + PNoneventDown)/sum(outcome==0) );\n[~,pval] = ztest(z,0,1);\n\n% Implemented from Mc Nemar 1947, as detailed in\n% Biometrics, 66, 1185-1191, 2010 Dec.\n% Westfall et al.\n% N01 = sum(pred_old==0 & pred_new==1);\n% N10 = sum(pred_old==1 & pred_new==0);\n% Nd = N01 + N10 ;\n% \n% pval = binocdf(N01,Nd,0.5);\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/43200-net-reclassification-improvement/NetReclassificationImprovement.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.684761016385882}} {"text": "function [f, label] = gsp_jtv_fa(G,shift)\n%GSP_JTV_FA Frequency axis for the joint time vertex framework\n% Usage: f = gsp_jtv_fa(G);\n%\n% Input parameters:\n% G : Time-vertex graph structure\n% shift : Boolean value: 1 to apply fftshift on the frequency vector, 0 otherwise\n% Ouput parameters:\n% f : Frequency axis (row vector)\n%\n\n% Author: Nathanael Perraudin, Francesco Grassi\n% Date : September 2016\n\nif nargin<2\n shift = 0;\nend\n\nif ~gsp_check_jtv(G)\n error('GSP_JTV_FA needs the time dimension. Use GSP_JTV_GRAPH');\nend\n\nif isempty(G.jtv.NFFT)\n NFFT = G.jtv.T;\nelse\n NFFT = G.jtv.NFFT;\nend\n\nif shift\n f = fftshift(gsp_cfa( NFFT,G.jtv.fs )');\nelse\n f = gsp_cfa( NFFT,G.jtv.fs )';\nend\n\n\n\n\nlabel = '\\omega';\n\nend", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/utils/gsp_jtv_fa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.684761006588035}} {"text": "function pitchwatch(x,Ts)\n% Plot the pitch keys.\n% pitchwatch(x,[Ts])\n% \n% :: Syntax\n% The array x is the input signal and Ts is the (optional) sampling period.\n% Example on use: [x,Fs] = wavread('Hum.wav');\n% pitchwatch(x,1/Fs);\n% \n% :: Information\n% Make your own wav-files with the Windows Sound Recorder. Choose the attributes\n% PCM 8000Hz, 16bit, Mono when saving the wav-file. For more information on pitch\n% keys, go to http://www.bookrags.com/wiki/Piano_key_frequencies.\n\n% Set parameters.\nif nargin < 2, Ts = 1/8000; end\n\n% Set constants.\nxlen = length(x);\nwlen = 512;\nwlag = 128;\n\n% Zero-pad signal.\nxpad = wlag-rem(xlen-wlen-1,wlag)-1;\nx = [x(:); zeros(xpad,1)];\nL = (xlen+xpad-wlen)/wlag+1;\nL = L-wlen/wlag/2;\n\n% Calculate the AMDF and AMDF-fractional pitch periods.\nfor k1 = 1:L\n k2 = (k1-1)*wlag;\n for k3 = 1:wlen/2-1, c(k3) = sum(abs(x(k2+(1:wlen))-x(k2+k3+(1:wlen)))); end\n \n n = findpeaks(-c);\n if ~isempty(n), n(find(c(n) > mean(c(n))-sqrt(var(c(n))))) = []; end\n if ~isempty(n), t0 = n(1);\n else, t0 = []; end\n \n if ~isempty(t0)\n u1 = x(k2+t0+(1:wlen))-x(k2+(1:wlen));\n u2 = x(k2+t0+(1:wlen))-x(k2+t0+1+(1:wlen));\n t1 = sum(u1.*u2)/sum(u2.*u2);\n y(k1) = 1/Ts/(t0+t1);\n else\n y(k1) = NaN;\n end\nend\n\n% Plot pitch keys.\nkeys = {'C','C#','D','D#','E','F','F#','G','G#','A','A#','B'};\nkey0 = 12*log2(y/440)+57;\nu1 = max(0,min(floor(key0)));\nu2 = min(96,max(ceil(key0)));\nkey1 = mod([u1:u2],12)+1;\nkey2 = floor([u1:u2]/12);\nfor k = [1:u2-u1+1], tick(k) = strcat(keys(key1(k)),num2str(key2(k))); end\nfigure, plot((0.5+[0:L-1])*wlag*Ts,key0,'b.');\nset(gca,'FontSize',8,'XLim',[0,L*wlag]*Ts,'YLim',[u1,u2],'YTick',[u1:u2],'YTickLabel',tick);\nxlabel('Time'); ylabel('Key');\n\n% FUNCTIONS\n\nfunction n = findpeaks(x)\n\nn = find(diff(diff(x) > 0) < 0);\nu = find(x(n+1) > x(n));\nn(u) = n(u)+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/11002-speech-snipper/pitchwatch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6847076808219382}} {"text": "function c = r8mat_add ( m, n, alpha, a, beta, b )\n\n%*****************************************************************************80\n%\n%% R8MAT_ADD computes C = alpha * A + beta * B for R8MAT's.\n%\n% Discussion:\n%\n% An R8MAT is an array of R8 values.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 December 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, real ALPHA, the multiplier for A.\n%\n% Input, real A(M,N), the first matrix.\n%\n% Input, real BETA, the multiplier for A.\n%\n% Input, real B(M,N), the second matrix.\n%\n% Output, real C(M,N), the sum of alpha*A+beta*B.\n%\n c(1:m,1:n) = alpha * a(1:m,1:n) + beta * b(1:m,1:n);\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/r8lib/r8mat_add.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.6846591659466984}} {"text": "function [Q, V, policy, mean_discrepancy] = mdp_MK_learning(P, R, discount, N)\n\n% mdp_Q_learning Evaluation of the matrix Q, using the Q learning algorithm \n%\n% Arguments\n% -------------------------------------------------------------------------\n% Let S = number of states, A = number of actions\n% P(SxSxA) = transition matrix \n% P could be an array with 3 dimensions or \n% a cell array (1xA), each cell containing a sparse matrix (SxS)\n% R(SxSxA) or (SxA) = reward matrix\n% R could be an array with 3 dimensions (SxSxA) or \n% a cell array (1xA), each cell containing a sparse matrix (SxS) or\n% a 2D array(SxA) possibly sparse \n% discount = discount rate in ]0; 1[\n% N(optional) = number of iterations to execute, default value: 10000.\n% It is an integer greater than the default value. \n% Evaluation --------------------------------------------------------------\n% Q(SxA) = learned Q matrix \n% V(S) = learned value function.\n% policy(S) = learned optimal policy.\n% mean_discrepancy(N/100) = vector of V discrepancy mean over 100 iterations\n% Then the length of this vector for the default value of N is 100.\n\n% MDPtoolbox: Markov Decision Processes Toolbox\n% Copyright (C) 2009 INRA\n% Redistribution and use in source and binary forms, with or without modification, \n% are permitted provided that the following conditions are met:\n% * Redistributions of source code must retain the above copyright notice, \n% this list of conditions and the following disclaimer.\n% * Redistributions in binary form must reproduce the above copyright notice, \n% this list of conditions and the following disclaimer in the documentation \n% and/or other materials provided with the distribution.\n% * Neither the name of the nor the names of its contributors \n% may be used to endorse or promote products derived from this software \n% without specific prior written permission.\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND \n% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \n% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n% IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n% INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, \n% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \n% DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF \n% LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE \n% OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n% OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n% check of arguments\nif (discount <= 0 || discount >= 1)\n disp('--------------------------------------------------------')\n disp('MDP Toolbox ERROR: Discount rate must be in ]0,1[')\n disp('--------------------------------------------------------') \nelseif (nargin >= 4) && (N < 10000)\n disp('--------------------------------------------------------')\n disp('MDP Toolbox ERROR: N must be upper than 10000')\n disp('--------------------------------------------------------') \nelse\n\n % initialization of optional arguments\n if (nargin < 4); N=10000; end; \n \n % Find number of states and actions\n if iscell(P)\n S = size(P{1},1);\n A = length(P);\n else\n S = size(P,1);\n A = size(R,2); \n end;\n \n % Initialisations\n Q = zeros(S,A);\n dQ = zeros(S,A);\n mean_discrepancy = [];\n discrepancy = [];\n\n % Initial state choice\n s = randi([1,S]);\n prob=[NaN NaN];\n while nansum(prob)==0\n s = randi([1,S]); \n [s1, act, prob]=find(P(:,s,:)); %which actions are possible in that state?\n end\n \n h = waitbar(0,'Initializing waitbar...');\n \n for n=1:N\n\n \n \n % Reinitialisation of trajectories every 100 transitions\n if (mod(n,100)==0); \n prob=[NaN NaN];\n while nansum(prob)==0\n s = randi([1,S]); \n [s1, act, prob]=find(P(:,s,:)); %which actions are possible in that state?\n end\n waitbar(n/N,h,n/N*100);\n end;\n \n % Action choice : greedy with increasing probability\n % probability 1-(1/log(n+2)) can be changed\n \n \n \n pn = rand(1);\n% if (pn < (1-(1/log(n+2))))\n% [~,a] = max(Q(s,:));\n% else\n a = act(randi([1,numel(act)]));\n% end;\n \n % Simulating next state s_new and reward associated to \n p_s_new = rand(1);\n p = 0; \n s_new = 0;\n while ((p < p_s_new) && (s_new < S)) \n s_new = s_new+1;\n if iscell(P)\n p = p + P{a}(s,s_new);\n else \n p = p + P(s,s_new,a);\n end;\n end; \n if iscell(R)\n r = R{a}(s,s_new); \n elseif ndims(R) == 3\n r = R(s,s_new,a); \n else\n r = R(s,a); \n end;\n\n % Updating the value of Q \n % Decaying update coefficient (1/sqrt(n+2)) can be changed\n delta = r + discount*max(Q(s_new,:)) - Q(s,a);\n dQ = (1/sqrt(n+2))*delta;\n Q(s,a) = Q(s,a) + dQ;\n \n % Current state is updated\n s = s_new;\n \n % Computing and saving maximal values of the Q variation \n discrepancy(mod(n,100)+1) = abs(dQ); \n \n % Computing means all over maximal Q variations values \n if (length(discrepancy) == 100) \n mean_discrepancy = [ mean_discrepancy mean(discrepancy)];\n discrepancy = [];\n end; \n \n end;\n\n %compute the value function and the policy\n [V, policy] = max(Q,[],2); \nclose(h);\nend;\n", "meta": {"author": "matthieukomorowski", "repo": "AI_Clinician", "sha": "0669f8907e65503641857ca76aa46938641e513f", "save_path": "github-repos/MATLAB/matthieukomorowski-AI_Clinician", "path": "github-repos/MATLAB/matthieukomorowski-AI_Clinician/AI_Clinician-0669f8907e65503641857ca76aa46938641e513f/MDPtoolbox/mdp_MK_learning.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6846434582758838}} {"text": "% See how well partial Kalman filter updates work\n\nseed = 0;\nrand('state', seed);\nrandn('state', seed);\nnlandmarks = 6;\nT = 12;\n\n[A,B,C,Q,R,Qbig,Rbig,init_x,init_V,robot_block,landmark_block,...\n\t true_landmark_pos, true_robot_pos, true_data_assoc, ...\n\t obs_rel_pos, ctrl_signal] = mk_linear_slam(...\n\t 'nlandmarks', nlandmarks, 'T', T, 'ctrl', 'leftright', 'data-assoc', 'cycle');\n\n% exact\n[xe, Ve] = kalman_filter(obs_rel_pos, A, C, Qbig, Rbig, init_x, init_V, ...\n\t\t\t\t 'model', true_data_assoc, 'u', ctrl_signal, 'B', B);\n\n\n% approx\n%k = nlandmarks-1; % exact\nk = 3;\nndx = {};\nfor t=1:T\n landmarks = unique(true_data_assoc(t:-1:max(t-k,1)));\n tmp = [landmark_block(:, landmarks) robot_block'];\n ndx{t} = tmp(:);\nend\n\n[xa, Va] = kalman_filter(obs_rel_pos, A, C, Qbig, Rbig, init_x, init_V, ...\n\t\t\t 'model', true_data_assoc, 'u', ctrl_signal, 'B', B, ...\n\t\t 'ndx', ndx);\n\n\n\nnrows = 10;\nstepsize = T/(2*nrows);\nts = 1:stepsize:T;\n\nif 1 % plot\n \nclim = [0 max(max(Va(:,:,end)))];\n\nfigure(2)\nif 0\n imagesc(Ve(1:2:end,1:2:end, T))\n clim = get(gca,'clim');\nelse\n i = 1;\n for t=ts(:)'\n subplot(nrows,2,i)\n i = i + 1;\n imagesc(Ve(1:2:end,1:2:end, t))\n set(gca, 'clim', clim)\n colorbar\n end\nend\nsuptitle('exact')\n\n\nfigure(3)\nif 0\n imagesc(Va(1:2:end,1:2:end, T))\n set(gca,'clim', clim)\nelse\n i = 1;\n for t=ts(:)'\n subplot(nrows,2,i)\n i = i+1;\n imagesc(Va(1:2:end,1:2:end, t))\n set(gca, 'clim', clim)\n colorbar\n end\nend\nsuptitle('approx')\n\n\nfigure(4)\ni = 1;\nfor t=ts(:)'\n subplot(nrows,2,i)\n i = i+1;\n Vd = Va(1:2:end,1:2:end, t) - Ve(1:2:end,1:2:end,t);\n imagesc(Vd)\n set(gca, 'clim', clim)\n colorbar\nend\nsuptitle('diff')\n\nend % all plot\n\n\nfor t=1:T\n %err(t)=rms(xa(:,t), xe(:,t));\n err(t)=rms(xa(1:end-2,t), xe(1:end-2,t)); % exclude robot\nend\nfigure(5);plot(err)\ntitle('rms mean pos')\n\n\nfor t=1:T\n i = 1:2*nlandmarks;\n denom = Ve(i,i,t) + (Ve(i,i,t)==0);\n Vd =(Va(i,i,t)-Ve(i,i,t)) ./ denom;\n Verr(t) = max(Vd(:));\nend\nfigure(6); plot(Verr)\ntitle('max relative Verr')\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/examples/dynamic/SLAM/slam_partial_kf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797081106935, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6846434579554251}} {"text": "% Small technical example. \n% Shows how to retrieve the details on a rectangular grid, after a multi- \n% resolution decomposition has been performed.\n%\ndisp('Small technical example.');\ndisp('Shows how to retrieve the details on a rectangular grid, after a multi-');\ndisp('resolution decomposition has been performed.');\ndisp('FOR MORE INFORMATION: help retrieveR');\ndisp(' ');\ndisp('See also the report http://repository.cwi.nl:8888/cwi_repository/docs/IV/04/04178D.pdf');\ndisp('Dr. Paul M. de Zeeuw ');\ndisp(' (C) 1998-2006 Stichting CWI, Amsterdam, The Netherlands');\ndisp(' ');\n%---PARAMETERS-----------------------------------------------------------------\n% How to execute, set parameters\nN = 6; % maximum level (even number) in lifting scheme\nfiltername = 'Neville4';\n%\n%---INSERT YOUR IMAGE HERE-----------------------------------------------------\nif exist('imread','file') == 2\n Orig = double(imread('zenithgray.TIF','tiff'));\nelse\n load zenithgray; Orig = zenithgray; clear zenithgray;\nend\n%\ndisp([' Dimensions of original ' int2str( size(Orig) )]);\n%---DECOMPOSITION--------------------------------------------------------------\ndisp([' Filter type is ' filtername]);\n[C,S] = QLiftDec2(Orig,N,filtername);\n%\n%---RETRIEVE APPROXIMATION-----------------------------------------------------\nA = retrieveR(N, 'a', C, S);\nsizeA = size(A);\n%\n%---RETRIEVE DETAIL AT EVEN LEVEL----------------------------------------------\nlevel = N-2;\ndisp([' Level ' int2str(level)]);\nD = retrieveR(level, 'd', C, S);\n%\ndisp(['The dimensions of the detail function read as follows ' int2str(size(D))]);\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/13507-lisq-a-toolbox-for-the-lifting-scheme-on-2d-quincunx-grids/LISQ/example07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6846434506587884}} {"text": "%% BVAR tutorial: Bayesian Dynamic Factor model \n% Author: Filippo Ferroni and Fabio Canova\n% Date: 09/14/2021\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Estimation of a static and dynamic factor model\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nclear; close all; clc;\n\naddpath ../../cmintools/\naddpath ../../bvartools/\n\nrng('default');\nrng(999);\n\n% generate factors/observables\n\n% Setting the parameters\n% AR1 factors\nPhi = [0.75 0.0;0.1 0.8];\n% Cov factors innovation\nSigma = [1 -0.2; -0.2 2];\nQ = chol(Sigma,'lower');\n% factor loadings\nLambda = [1 0;\n 0.3 1;\n 0.5 -1.5;\n -1.1 -0.5;\n 1.5 1.5; \n 5*randn(45,size(Phi,1))]; \n% persistence of idisyncratic errors\nrho = 0; \n% standard deviation of idisyncratic errors\nsig = 1;\n\n% preallocating memory\n% sample length\nT = 301;\nf = zeros(T,size(Phi,1));\ny = zeros(T,size(Lambda,1));\ne = zeros(T,size(Lambda,1));\ni = zeros(T,size(Phi,1));\n\nfor t = 1 : T-1\n i(t+1,:) = randn(size(f,2),1)';\n f(t+1,:) = (Phi*f(t,:)' + Q*i(t+1,:)')'; \n e(t+1,:) = (rho*e(t,:)' + sig*randn(size(Lambda,1),1))';\n y(t+1,:) = (Lambda*f(t+1,:)' + e(t+1,:)')';\nend\nf(1,:) = [];\ny(1,:) = [];\n\nsubplot(2,1,1)\nplot(y)\nsubplot(2,1,2)\nplot(f)\n\n% true IRFs\nhor = 24;\nir_true=zeros(size(y,2), hor,size(f,2));\ntrue = iresponse(Phi,eye(size(f,2)),hor,Q);\nLam_ = repmat(Lambda,1,1,size(f,2));\nif exist('pagemtimes','builtin') == 5\n ir_true = pagemtimes(Lam_,true);\nelse\n for ff = 1 : size(f,2)\n ir_true(:,:,ff) = Lambda * true(:,:,ff);\n end\nend\npause;\n\n%% principal components\n\nnfac = 2;\ntransf = 0;\n\n[~,pc,~,egv,~] = pc_T(y,nfac,transf);\n\n% scree plot\nfigure,\nplot(egv(1:10),'b','Linewidth',2);\ngrid on\ntitle('Eigenvalues')\n% STR_RECAP = [ dirname '/screeplot'];\n% saveas(gcf,STR_RECAP,'fig');\n% savefigure_pdf([STR_RECAP '.pdf']);\n\n\n\n%% static factor model\n\n% 2 static factors\nnfac = size(f,2);\nlags = 0; \n% priors\noptions.priors.F.Lambda.mean = 0;\noptions.priors.F.Lambda.cov = 6;\n% estimation command\n[BSFM] = bdfm_(y,lags,nfac,options);\n% consider a subset of draws\n%index = 5000:20:size(BSFM.Phi_draws,3);\nindex = 1:1:size(BSFM.Phi_draws,3);\n% plot estimated and true factors\nfigure,\nfor gg=1:nfac\n subplot(nfac,1,gg)\n % draws of factors\n plot(squeeze(BSFM.f_draws(:,gg,index)),'Color',[0.7 0.7 0.7])\n hold on\n % true factor\n f_mean = mean(BSFM.f_draws(:,gg,index),3);\n sign_ = sign(corr(f_mean,f(:,gg)));\n plot(sign_ * f(:,gg),'b','Linewidth',2)\n hold on\n plot(f_mean,'k','Linewidth',2)\nend\n% save plot\ndirname = 'factor_plt';\nmkdir(dirname)\nSTR_RECAP = [ dirname '/sfm'];\nsaveas(gcf,STR_RECAP,'fig');\nif strcmp(version('-release'),'2022b') == 0\n\tsavefigure_pdf([STR_RECAP '.pdf']);\nend\npause;\n\n\n \n\n%% dynamic factor model\nclear options\nnfac = size(f,2);\nlags = round(size(Phi,2)/nfac);\n\n% Priors options\n% factors priors\noptions.priors.F.Phi.mean = Phi;\noptions.priors.F.Phi.cov = 10 * eye(size(Phi,1));\noptions.priors.F.Sigma.scale = Sigma;\noptions.priors.F.Sigma.df = 4;\noptions.priors.F.Lambda.mean = 0;\noptions.priors.F.Lambda.cov = 6;\n% else Jeffrey prior on PhiSigma: options.priors.name = 'Jeffrey';\n% idyosincratic error priors\noptions.priors.G.Sigma.scale = sig;\noptions.priors.G.Sigma.df = 4;\n% IRF options\n% IV identification\noptions.proxy = i(lags+2:end,1);\n% Sign identification\noptions.signs{1} = 'y(4,1:3,1)<0'; %\noptions.signs{2} = 'y(5,1:3,1)>0'; %\n% estimation command\n[BDFM] = bdfm_(y,lags,nfac,options);\n% consider a subset of draws\n% index = 5000:20:size(BDFM.Phi_draws,3);\nindex = 1:1:size(BDFM.Phi_draws,3);\n% plot estimated and true factors\nfigure,\nfor gg=1:nfac\n subplot(nfac,1,gg)\n plot(squeeze(BDFM.f_draws(:,gg,index)),'Color',[0.7 0.7 0.7])\n hold on\n f_mean = mean(BDFM.f_draws(:,gg,index),3);\n sign_ = sign(corr(f_mean,f(:,gg)));\n % true factor\n plot(sign_ * f(:,gg),'b','Linewidth',2)\n hold on\n plot(f_mean,'k','Linewidth',2)\nend\nSTR_RECAP = [ dirname '/dfm'];\nsaveas(gcf,STR_RECAP,'fig');\nif strcmp(version('-release'),'2022b') == 0\n\tsavefigure_pdf([STR_RECAP '.pdf']);\nend\n\n%%\n\nPhi_m = mean(BDFM.Phi_draws(:,:,index),3);\nSig_m = mean(BDFM.Sigma_draws(:,:,index),3);\nPtt = lyapunov_symm(Phi_m, Sig_m);\nf_m = mean(BDFM.f_draws(:,:,index),3);\nfigure,\nfor gg=1:nfac\n subplot(nfac,1,gg)\n plot([f_m(:,gg)-2*Ptt(gg,gg) f_m(:,gg)+2*Ptt(gg,gg)],'Color',[0.7 0.7 0.7],'Linewidth',2)\n hold on\n plot(f(:,gg),'b','Linewidth',2)\n hold on\n plot(f_m(:,gg),'k','Linewidth',2)\nend\n\nPhi0 = Phi';\njj = 0;\nfigure('Name','Phi')\nfor gg=1: nfac\n for hh =1 : nfac\n jj = jj+1;\n subplot(nfac,nfac,jj)\n histogram(squeeze(BDFM.Phi_draws(gg,hh,index)),40)\n hold on\n plot([Phi0(gg,hh) Phi0(gg,hh)],[0 50],'r','Linewidth',2)\n xlim([-1 1])\n end\nend\n%\n\nfigure('Name','Sigma')\nSigma0 = Q*Q';\njj = 0;\nfor gg=1:2\n for hh =1 :2\n jj = jj+1;\n subplot(nfac,nfac,jj)\n histogram(squeeze(BDFM.Sigma_draws(gg,hh,index)),40)\n hold on\n plot([Sigma0(gg,hh) Sigma0(gg,hh)],[0 50],'r','Linewidth',2)\n end\nend\n% \n% figure('Name','Lambda')\n% Lambda0 = Lambda;\n% jj = 0;\n% for gg=1:10\n% for hh =1 :2\n% jj = jj+1;\n% subplot(5,4,jj)\n% histogram(squeeze(BDFM.lambda_draws(gg,hh,index)),40)\n% hold on\n% plot([Lambda0(gg,hh) Lambda0(gg,hh)],[0 30],'r','Linewidth',2)\n% end\n% end\n% \n% figure('Name','sigma_g')\n% sig0 = sig*ones(size(Lambda,1),1);\n% for jj=1:10\n% subplot(3,4,jj)\n% histogram(squeeze(BDFM.sigma_draws(jj,index)),40)\n% hold on\n% plot([sig0(jj) sig0(jj)],[0 30],'r','Linewidth',2)\n% end\n\n%% Plot IRFs\n\nindex_var = [1 2 4 5 15 20];\nindex_sho = 1;\n\n% some options:\n% add the true IRF\noptions.add_irfs = ir_true(index_var,:,index_sho);\n% additional 90% HPD set\noptions.conf_sig_2 = 0.9; \n% additional 90% HPD set\noptions.nplots = [2 3]; \n% variables names for the plots\noptions.varnames = {'Var1','Var2','Var4','Var5','Var15','Var20'}; \n% name of the directory where the figure is saved\noptions.saveas_dir = './factor_plt';\n% name of the figure to save\noptions.saveas_strng = 'sign';\n% sign restricted IRF\nirfs_to_plot = BDFM.irsign_draws(index_var,:,index_sho,:);\nplot_irfs_(irfs_to_plot,options)\n\n% IV IRF\nirfs_to_plot_iv = BDFM.irproxy_draws(index_var,:,index_sho,:);\n% name of the figure to save\noptions.saveas_strng = 'iv';\nplot_irfs_(irfs_to_plot_iv,options)\n\n\n\n\n\n\n", "meta": {"author": "naffe15", "repo": "BVAR_", "sha": "4c935f440a2e98475ead4f873ebdfd03378a0eee", "save_path": "github-repos/MATLAB/naffe15-BVAR_", "path": "github-repos/MATLAB/naffe15-BVAR_/BVAR_-4c935f440a2e98475ead4f873ebdfd03378a0eee/examples/BVAR tutorial/example_12_bdfm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6846434464352816}} {"text": "function [warp,L,LnInv,bendE] = tpsGetWarp( lambda, xsS, ysS, xsD, ysD )\n% Given two sets of corresponding points, calculates warp between them.\n%\n% Uses booksteins PAMI89 method. Can then apply warp to a new set of\n% points (tpsInterpolate), or even an image (tpsInterpolateIm).\n% \"Principal Warps: Thin-Plate Splines and the Decomposition of\n% Deformations\". Bookstein. PAMI 1989.\n%\n% USAGE\n% [warp,L,LnInv,bendE] = tpsGetWarp( lambda, xsS, ysS, xsD, ysD )\n%\n% INPUTS\n% lambda - rigidity of warp (inf means warp becomes affine)\n% xsS, ysS - [1xn] correspondence points from source image\n% xsD, ysD - [1xn] correspondence points from destination image\n%\n% OUTPUTS\n% warp - bookstein warping parameters\n% L, LnInv - see bookstein\n% bendE - bending energy\n%\n% EXAMPLE - 1\n% xsS=[0 -1 0 1]; ysS=[1 0 -1 0]; xsD=xsS; ysD=[3/4 1/4 -5/4 1/4];\n% warp = tpsGetWarp( 0, xsS, ysS, xsD, ysD );\n% [gxs, gys] = meshgrid(-1.25:.25:1.25,-1.25:.25:1.25);\n% tpsInterpolate( warp, gxs, gys, 1 );\n%\n% EXAMPLE - 2\n% xsS = [3.6929 6.5827 6.7756 4.8189 5.6969];\n% ysS = [10.3819 8.8386 12.0866 11.2047 10.0748];\n% xsD = [3.9724 6.6969 6.5394 5.4016 5.7756];\n% ysD = [6.5354 4.1181 7.2362 6.4528 5.1142];\n% warp = tpsGetWarp( 0, xsS, ysS, xsD, ysD );\n% [gxs, gys] = meshgrid(3.5:.25:7, 8.5:.25: 12.5);\n% tpsInterpolate( warp, gxs, gys, 1 );\n%\n% See also TPSINTERPOLATE, TPSINTERPOLATEIM, TPSRANDOM\n%\n% Piotr's Computer Vision Matlab Toolbox Version 2.0\n% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n% Licensed under the Simplified BSD License [see external/bsd.txt]\n\ndim = size( xsS );\nif( all(size(xsS)~=dim) || all(size(ysS)~=dim) || all(size(xsD)~=dim))\n error( 'argument sizes do not match' );\nend\n\n% get L\nn = size(xsS,2);\ndeltaXs = xsS'*ones(1,n) - ones(n,1) * xsS;\ndeltaYs = ysS'*ones(1,n) - ones(n,1) * ysS;\nRsq = (deltaXs .* deltaXs + deltaYs .* deltaYs);\nRsq = Rsq+eye(n); K = Rsq .* log( Rsq ); K( isnan(K) )=0;\nK = K + lambda * eye( n );\nP = [ ones(n,1), xsS', ysS' ];\nL = [ K, P; P', zeros(3,3) ];\nLInv = L^(-1);\nLnInv = LInv(1:n,1:n);\n\n% recover W's\nwx = LInv * [xsD 0 0 0]';\naffinex = wx(n+1:n+3);\nwx = wx(1:n);\nwy = LInv * [ysD 0 0 0]';\naffiney = wy(n+1:n+3);\nwy = wy(1:n);\n\n% record warp\nwarp.wx = wx; warp.affinex = affinex;\nwarp.wy = wy; warp.affiney = affiney;\nwarp.xsS = xsS; warp.ysS = ysS;\nwarp.xsD = xsD; warp.ysD = ysD;\n\n% get bending energy (without regularization)\nw = [wx'; wy'];\nK = K - lambda * eye( n );\nbendE = trace(w*K*w')/2;\n", "meta": {"author": "pdollar", "repo": "toolbox", "sha": "e87332637bbe8e8b92dd487c87567d9628404523", "save_path": "github-repos/MATLAB/pdollar-toolbox", "path": "github-repos/MATLAB/pdollar-toolbox/toolbox-e87332637bbe8e8b92dd487c87567d9628404523/matlab/tpsGetWarp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6846434349151377}} {"text": "seed = 1;\nrand('state', seed);\nrandn('state', seed);\n\nN = 4; \ndag = zeros(N,N);\nC = 1; S = 2; R = 3; W = 4;\ndag(C,[R S]) = 1;\ndag(R,W) = 1;\ndag(S,W)=1;\n\nfalse = 1; true = 2;\nns = 2*ones(1,N); % binary nodes\n\nbnet = mk_bnet(dag, ns);\nif 0\n bnet.CPD{C} = tabular_CPD(bnet, C, [0.5 0.5]);\n bnet.CPD{R} = tabular_CPD(bnet, R, [0.8 0.2 0.2 0.8]);\n bnet.CPD{S} = tabular_CPD(bnet, S, [0.5 0.9 0.5 0.1]);\n bnet.CPD{W} = tabular_CPD(bnet, W, [1 0.1 0.1 0.01 0 0.9 0.9 0.99]);\nelse\n for i=1:N, bnet.CPD{i} = tabular_CPD(bnet, i); end\nend\n\n\n\nevidence = cell(1,N);\nonodes = [1 3];\ndata = sample_bnet(bnet);\nevidence(onodes) = data(onodes);\n\nclear engine;\nengine{1} = belprop_inf_engine(bnet);\nengine{2} = jtree_inf_engine(bnet);\nengine{3} = global_joint_inf_engine(bnet);\nengine{4} = var_elim_inf_engine(bnet);\nE = length(engine);\n\nclear mpe;\nfor e=1:E\n mpe{e} = find_mpe(engine{e}, evidence);\nend\nfor e=2:E\n assert(isequal(mpe{1}, mpe{e}))\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/examples/static/mpe1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.684575718957487}} {"text": "% Copyright (C) Daphne Koller, Stanford University, 2012\n\nfunction [MEU OptimalDecisionRule] = OptimizeMEU( I )\n\n % Inputs: An influence diagram I with a single decision node and a single utility node.\n % I.RandomFactors = list of factors for each random variable. These are CPDs, with\n % the child variable = D.var(1)\n % I.DecisionFactors = factor for the decision node.\n % I.UtilityFactors = list of factors representing conditional utilities.\n % Return value: the maximum expected utility of I and an optimal decision rule \n % (represented again as a factor) that yields that expected utility.\n \n % We assume I has a single decision node.\n % You may assume that there is a unique optimal decision.\n D = I.DecisionFactors(1);\n DF = CalculateExpectedUtilityFactor(I);\n MEU = 0;\n D.val = D.val*0;\n ca=D.card(1);\n l = length(D.val)/ca;\n for i = 1:l\n\t start = i*ca-ca+1;\n endd = i*ca;\n [x,y] = max(DF.val(start:endd));\n\tMEU+=x;\n\tD.val(start+y-1) = 1;\nend\nOptimalDecisionRule = D;\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n % YOUR CODE HERE...\n % \n % Some other information that might be useful for some implementations\n % (note that there are multiple ways to implement this):\n % 1. It is probably easiest to think of two cases - D has parents and D \n % has no parents.\n % 2. You may find the Matlab/Octave function setdiff useful.\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n \n\nend\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/6.Decision Making/OptimizeMEU.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.6845757119546815}} {"text": "function l = gammaPriorLogProb(prior, x)\n\n% GAMMAPRIORLOGPROB Log probability of Gamma prior.\n\n% PRIOR\n\n% Compute log prior\nD = length(x);\nl = D*prior.a*log(prior.b)-D*gammaln(prior.a)+(prior.a-1)*sum(log(x))-prior.b*sum(x);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/prior/gammaPriorLogProb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6845321792010931}} {"text": "function b = r8po_inverse ( n, r )\n\n%*****************************************************************************80\n%\n%% R8PO_INVERSE computes the inverse of a matrix factored by R8PO_FA.\n%\n% Discussion:\n%\n% The R8PO storage format is appropriate for a symmetric positive definite \n% matrix and its inverse. (The Cholesky factor of a R8PO matrix is an\n% upper triangular matrix, so it will be in R8GE storage format.)\n%\n% Only the diagonal and upper triangle of the square array are used.\n% This same storage scheme is used when the matrix is factored by\n% R8PO_FA, or inverted by R8PO_INVERSE. For clarity, the lower triangle\n% is set to zero.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 February 2004\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real R(N,N), the Cholesky factor, in R8GE storage, returned by R8PO_FA.\n%\n% Output, real B(N,N), the inverse matrix, in R8PO storage.\n%\n b(1:n,1:n) = r(1:n,1:n);\n%\n% Compute Inverse ( R ).\n%\n for k = 1 : n\n\n b(k,k) = 1.0E+00 / b(k,k);\n b(1:k-1,k) = -b(1:k-1,k) * b(k,k);\n\n for j = k + 1 : n\n t = b(k,j);\n b(k,j) = 0.0E+00;\n b(1:k,j) = b(1:k,j) + t * b(1:k,k);\n end\n\n end\n%\n% Compute Inverse ( R ) * ( Inverse ( R ) )'.\n%\n for j = 1 : n\n\n for k = 1 : j - 1\n t = b(k,j);\n b(1:k,k) = b(1:k,k) + t * b(1:k,j);\n end\n\n b(1:j,j) = b(1:j,j) * b(j,j);\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/linplus/r8po_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6845112763045934}} {"text": "% Tow Thomas Bandpass Filter - Worst-Case Analysis (RSS, EVA, FMCA)\n% File: c:\\M_files\\short_updates\\TowThomaswca.m\n% updated 11/16/06\nclear;clc;\nK=1e3;uF=1e-6; % Unit suffixes\n% Component values\nR1=200*K;R2=10*K;R3=20*K;R4=10*K;R5=20*K;R6=20*K;\nC1=0.0159*uF;C2=C1;\n%\nNom=[R1 R2 R3 R4 R5 R6 C1 C2]; % Place components in vector X\n%\nTr=0.02;Tc=0.1; % 2% resistors, 10% capacitors\n%\n% Tolerance array T; minus in row 1, plus in row 2\n% Column order follows component vector X\n%\nT=[-Tr -Tr -Tr -Tr -Tr -Tr -Tc -Tc;\n Tr Tr Tr Tr Tr Tr Tc Tc];\n% \n% Linear frequency; in Hz\n%\nBF=700;LF=1300;NP=301; % Number of points\nF=linspace(BF,LF,NP);\n%\nNc=length(Nom); % Nc = number of components\n%\n% Nominal output\n%\nMr=1+(T(2,:)+T(1,:))/2; % For asymmetric tolerances if any\nNav=Nom.*Mr; % Average value of components; = Nom if symmetric tolerances\nTv=(T(2,:)-T(1,:))./(2*Mr); % Tv used for RSS\n%\n[A,B,D,E,I]=ttbpf(Nav); % call nominal arrays\n%\n% Arrays are constant and real, and they are calculated only once,\n% not at each frequency as in admittance matrix analyses. \n% This reduces run times considerably.\n%\nfor i=1:NP;s=2*pi*F(i)*j;Vn(i)=abs(D*((s*I-A)\\B)+E);end; % Nominal output\n%\nNf=2^Nc;Vm1=zeros(Nf,NP); % Used in FMCA\nk=1:Nf;RB=dec2bin(k-1); % Used in FMCA\n%\n% Sensitivities\n%\ndpf=0.0001; % derivative perturbation factor\nQ=1+dpf;R=1-dpf;\nfor i=1:NP\n Qx=ones(1,Nc);Rx=Qx; % reset Q & R\n s=2*pi*F(i)*j;\n for p=1:Nc % start sensitivity loop; p = component counter\n Qx(p)=Q;Rx(p)=R;\n if p > 1;Qx(p-1)=1;Rx(p-1)=1;end % reset previous\n %\n [A,B,D,E,I]=ttbpf(Nom.*Qx); % arrays perturbated forward\n Vr=abs(D*inv(s*I-A)*B+E); % output perturbated forward\n %\n [A,B,D,E,I]=ttbpf(Nom.*Rx); % arrays perturbated backward\n Vb=abs(D*inv(s*I-A)*B+E); % output perturbated backward\n %\n Sens(i,p)=(Vr-Vb)/(2*Vn(i)*dpf); % centered difference approximation\n % Ref: Numerical Methods for Engineers, 3rd ed.\n % S.C. Chapra & R.P. Canale, McGraw-Hill, 1998, p.93\n %\n % EVA (Extreme Value Analysis)\n %\n if Sens(i,p) > 0\n Hi(p)=1+T(2,p);Lo(p)=1+T(1,p); % component tolerance for WC High\n else\n Hi(p)=1+T(1,p);Lo(p)=1+T(2,p); % component tolerance for WC Low\n end\n end % close p sensitivity loop\n%\n% Get extreme value low (EVL) and extreme value high (EVH)\n%\n\t[A,B,D,E,I]=ttbpf(Nav.*Lo);\n VL(i)=abs(D*((s*I-A)\\B)+E);\n %\n\t[A,B,D,E,I]=ttbpf(Nav.*Hi);\n VH(i)=abs(D*((s*I-A)\\B)+E);\n% \n% RSS (Root-Sum-Square)\n%\n STn=norm(Sens(i,:).*Tv);\n Vrss1(i)=Vn(i)*(1-STn);Vrss2(i)=Vn(i)*(1+STn);\n%\n% FMCA\n%\n% Binary array RB contains binary numbers Nc bits wide from 0 to Nf.\n% Used for all possible tolerance combinations.\n%\n for k=1:Nf % start FMCA loop\n for p=1:Nc\n if RB(k,p)=='0'\n Tf(p)=1+T(1,p); % low tolerance if a logic '0'\n else\n Tf(p)=1+T(2,p); % high tolerance if a logic '1'\n end\n end % close FMCA tolerance loop\n [A,B,D,E,I]=ttbpf(Nav.*Tf);\n Vm1(k,i)=abs(D*((s*I-A)\\B)+E); \n end % close FMCA loop\nend % close major i loop\nVmax1=max(Vm1);Vmin1=min(Vm1);\n%\n% Plot sensitivities\n% Number of sensitivities to be plotted = Nc\n% Adjust 'g=plot(...' statements accordingly.\n% All should be plotted to observe any bipolarity (non-monotonicity).\nh=plot(F,Sens(:,1),'k',F,Sens(:,2),'r',F,Sens(:,3),'g',F,Sens(:,4),'b');\nset(h,'LineWidth',2);grid on\naxis auto\nylabel('%/%');xlabel('Freq (Hz)');\ntitle('Sensitivities')\nhold off\nlegend('R1','R2','R3','R4',0);\nfigure\n%\nh=plot(F,Sens(:,5),'k',F,Sens(:,6),'r',F,Sens(:,7),'g',F,Sens(:,8),'b');\nset(h,'LineWidth',2);\naxis auto;grid on\nylabel('%/%');xlabel('Freq (Hz)');\ntitle('Sensitivities')\nlegend('R5','R6','C1','C2',0);\nfigure\n%\n% RSS\nh=plot(F,Vn,'k--',F,Vrss1,'b',F,Vrss2,'r');\nset(h,'LineWidth',2);grid on\naxis auto\nylabel('Volts');xlabel('Freq (Hz)');\ntitle('RSS')\nlegend('Nom','RSS Lo','RSS Hi',0);\nfigure\n%\n% EVA\nh=plot(F,Vn,'k--',F,VH,'r',F,VL,'b');\nset(h,'LineWidth',2);grid on\naxis auto\nxlabel('Freq(Hz)');ylabel('Volts');\ntitle('EVA')\nlegend('Nom','EVA Hi','EVA Lo',0);\nfigure\n%\n% FMCA\nh=plot(F,Vn,'k--',F,Vmax1,'r',F,Vmin1,'b');\nset(h,'LineWidth',2);grid on\naxis auto\nxlabel('Freq(Hz)');ylabel('Volts');\ntitle('FMCA');\nlegend('Nom','FMCA Hi','FMCA Lo',0);\n%\n% See comments concerning RSS, EVA, & FMCA at end of mfbpfwca.m\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/2435-shortcut-state-space-circuit-analysis/Matlab_Files/TowThomaswca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6845112713635925}} {"text": "function x = gaussRnd(mu, Sigma, n)\n% Generate samples from a Gaussian distribution.\n% Input:\n% mu: d x 1 mean vector\n% Sigma: d x d covariance matrix\n% n: number of samples\n% Outpet:\n% x: d x n generated sample x~Gauss(mu,Sigma)\n% Written by Mo Chen (sth4nth@gmail.com).\nif nargin == 2\n n = 1;\nend\n[V,err] = chol(Sigma);\nif err ~= 0\n error('ERROR: sigma must be a symmetric positive definite matrix.');\nend\nx = V'*randn(size(V,1),n)+repmat(mu,1,n);", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter11/gaussRnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6845112605041896}} {"text": "function f=ref_iedgtii(c,g,a,M)\n%REF_IEDGTII Inverse Reference Even DGT type II\n% Usage f=ref_edgt(c,g,a,M);\n%\n% If a is even, then the input window must be odd-centered of length 2L.\n% \n% If a is odd, then the input window must be even-centered of length 2L.\n%\n\nL2=size(g,1);\nW=size(c,2);\nL=L2/2;\n\nb=L/M;\nN=L/a;\n\nF=zeros(L,M*N);\n\nl=(0:L-1).';\n\nlsecond=(2*L-1:-1:L).';\n\ngnew=circshift(g,floor(a/2));\nfor n=0:N-1\t \n for m=0:M-1\n gshift=circshift(gnew,n*a);\n\n F(:,M*n+m+1)=exp(2*pi*i*m*(l+.5)/M).*gshift(l+1) + ...\n\texp(-2*pi*i*m*(l+.5)/M).*gshift(lsecond+1);\n\n end;\nend;\n\nf=F*c;\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/reference/ref_iedgtii.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6844352792363636}} {"text": "function loglik = computeEMLoglik(xInit,PInit,xSmooth,y,F,H,Q,R,B,u)\n% COMPUTEEMLOGLIK Compute EM loglikelihood p(y_{1:t},x_{1:t} | theta), where\n% theta = {F,H,Q,R,B}.\n%\n% INPUTS: xInit The (xDim x 1) initial state mean for time 1\n% PInit The (xDim x xDim) initial state covariance for time 1\n% xSmooth The (xDim x N) matrix of smoothed estimates for time 1:N\n% y The (yDim x N) matrix of measurements for time 1:N\n% F The (xDim x xDim) state transition matrix\n% H The (yDim x xDim) measurement matrix\n% Q The (xDim x xDim) process noise covariance\n% R The (yDim x yDim) measurement noise covariance\n% B The (xDim x uDim) control input gain matrix\n% u The (uDim x N) control input matrix for time 1:N\n% \n% OUTPUTS: loglik A boolean stating if EM has converged\n%\n% [1] A. W. Blocker, An EM algorithm for the estimation of affine state-space systems with or without known inputs, (2008)\n%\n% January 2018 Lyudmil Vladimirov, University of Liverpool.\n\n [xDim, N] = size(xSmooth);\n yDim = size(y,1);\n \n loglik = -sum((y-H*xSmooth).^2)/(2*R) - N/2*log(abs(R))...\n -1/2*sum((xSmooth(2:N)-F*xSmooth(1:N-1)-B*u(2:N)).^2)/(Q) - (N-1)/2*log(abs(Q))...\n -sum((xSmooth(1)-xInit).^2)/(2*PInit) - 0.5*log(abs(PInit)) - N*log(2*pi);\n \n% loglik = -.5*(y-H*xSmooth)/R*(y-H*xSmooth)' - N/2*log(abs(R))...\n% -1/2*(xSmooth(:,2:N)-F*xSmooth(1:N-1)-B*u(2:N))/Q - (N-1)/2*log(abs(Q))...\n% -sum((xSmooth(1)-xInit).^2)/(2*PInit) - 0.5*log(abs(PInit)) - N*log(2*pi);\n \n% loglik = cell(1,3);\n% loglik{1} = -.5*(xSmooth(:,1) - xInit)/PInit*(xSmooth(:,1) - xInit)' ...\n% -.5*log(abs(PInit)) - .5*(N-1)*log(abs(Q)) - .5*N*log(abs(R)) ...\n% -.5*N*(xDim+yDim)*log(2*pi);\n% loglik{2} = 0;\n% loglik{3} = 0;\n% for k = 1:N\n% if(k>1)\n% loglik{2} = loglik{2} + .5*(xSmooth(:,k) ...\n% - F*xSmooth(:,k-1) - B*u(:,k))/Q*(xSmooth(:,k) - F*xSmooth(:,k-1) - B*u(:,k))';\n% end\n% loglik{3} = loglik{3} + .5*(y(:,k) - H*xSmooth(:,k))/R*(y(:,k) - H*xSmooth(:,k))';\n% end\n% loglik = loglik{1} - loglik{2} - loglik{3};\nend", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/Filters/Kalman/KalmanFilterX/Functions/Learning/+ExpectationMaximisation/computeEMLoglik.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6844352708021605}} {"text": "function [interp1_fs, interp2_fs] = get_interp_fourier(sz, params)\n\n% Compute the Fourier series of the interpolation function (b_d in the\n% paper). The interpolation method is set using params.interpolation_method:\n% - 'ideal' performs ideal reconstruction, which corresponds to a periodic\n% summation of a sinc function b_d in the spatial domain.\n% - 'bicubic' uses a bicubic kernel b_d in the spatial domain.\n\nswitch lower(params.interpolation_method)\n case 'none'\n % Do nothing\n interp1_fs = ones(sz(1),1);\n interp2_fs = ones(1,sz(2));\n case 'ideal'\n % Ideal reconstruction (flat in the frequency domain)\n interp1_fs = ones(sz(1),1) / sz(1);\n interp2_fs = ones(1,sz(2)) / sz(2);\n case 'bicubic'\n % Take the truncated fourier series from the cubic spline\n a = params.interpolation_bicubic_a;\n interp1_fs = real(1/sz(1) * cubic_spline_fourier((-(sz(1)-1)/2:(sz(1)-1)/2)'/sz(1), a));\n interp2_fs = real(1/sz(2) * cubic_spline_fourier((-(sz(2)-1)/2:(sz(2)-1)/2)/sz(2), a));\n otherwise\n error('Unknown dft interpolation method');\nend\n\nif params.interpolation_centering\n % Center the feature grids by shifting the interpolated features\n % Multiply Fourier coeff with e^(-i*pi*k/N)\n interp1_fs = interp1_fs .* exp(-1i*pi / sz(1) * (-(sz(1)-1)/2:(sz(1)-1)/2)');\n interp2_fs = interp2_fs .* exp(-1i*pi / sz(2) * (-(sz(2)-1)/2:(sz(2)-1)/2));\nend\nif params.interpolation_windowing\n % Window the Fourier series of the interpolation basis function\n win1 = hann(sz(1)+2);\n win2 = hann(sz(2)+2);\n interp1_fs = interp1_fs .* win1(2:end-1);\n interp2_fs = interp2_fs .* win2(2:end-1)';\nend\n\ninterp1_fs = single(interp1_fs);\ninterp2_fs = single(interp2_fs);", "meta": {"author": "martin-danelljan", "repo": "Continuous-ConvOp", "sha": "a79708be1f6f8bd8ec5489281cb37b164bebea83", "save_path": "github-repos/MATLAB/martin-danelljan-Continuous-ConvOp", "path": "github-repos/MATLAB/martin-danelljan-Continuous-ConvOp/Continuous-ConvOp-a79708be1f6f8bd8ec5489281cb37b164bebea83/implementation/get_interp_fourier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6844352708021604}} {"text": "classdef diskfun < separableApprox\n%DISKFUN DISKFUN class for representing functions on the unit disk.\n% \n% Class for approximating smooth functions defined on the unit disk. The \n% functions should be smooth. Diskfun objects can be constructed in a \n% variety of ways: \n%\n% 1. Y = diskfun(F), where F is a function handle in Cartesian \n% coordinates (x,y), e.g., @(x,y) x.*y + cos(x).\n% 2. Y = diskfun(F, 'polar'), where F is a function handle in polar \n% coordinates (theta,r). Here, theta is the angular variable satisfying\n% -pi <= theta <= pi, and r is the radial variable satisfying 0 <= r < 1,\n% e.g., @(theta,r) cos(r.*sin(theta))\n% 3. Y = diskfun(F), where F is a matrix of numbers.\n%\n% If F is a function handle then it should allow for vectorized evaluations.\n%\n% If F is a matrix, F = (f_ij), the numbers fij are used as function values\n% at the tensor Fourier-Chebyshev points on the rectangle [-pi,pi]x[0,1].\n%\n% DISKFUN(F, k) returns a rank k approximation to F.\n%\n% DISKFUN(F, [m n]) returns a representation of F using a degree m\n% Chebyshev approximation of F in the radial direction and a degree n\n% trigonometric approximation in the angular direction. The result is\n% compressed in low rank form and the rank k is still determined adaptively\n% (satisfying k<=min(m,n)+1).\n% \n% The DISKFUN software system is based on: \n%\n% H. Wilber, A. Townsend, and G. Wright, Computing with functions in\n% spherical and polar geometries II: The disk, SIAM. J. Sci. Comput., 39-4\n% (2017), C238-C262.\n%\n% See also CHEBFUN2, SPHEREFUN, DISKFUNV.\n\n% Copyright 2017 by The University of Oxford and The CHEBFUN Developers.\n% See http://www.chebfun.org/ for CHEBFUN information.\n\n% TODO: Include documentation of fixed eps construction\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% CLASS CONSTRUCTOR:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods ( Access = public, Static = false )\n \n function f = diskfun(varargin)\n % The main diskfun constructor!\n \n % Return an empty DISKFUN:\n if ( (nargin == 0) || isempty(varargin{1}) )\n f.domain = [-pi pi 0 1];\n return\n end\n % Call the constructor, all the work is done here:\n f = constructor(f, varargin{:}); \n end\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% CLASS METHODS:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods\n \n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% HIDDEN METHODS:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods ( Access = public, Static = false, Hidden = true )\n % Make f have BMC-II symmetry.\n f = projectOntoBMCII(f);\n \n end\n \n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% PUBLIC METHODS:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods ( Access = public, Static = false )\n \n % The main bulk of the DISKFUN constructor:\n g = constructor(g, op, dom, varargin);\n \n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% STATIC METHODS:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods ( Access = public, Static = true )\n \n % Fast Poisson & Helmholtz solvers: \n u = poisson( f, bc, m, n );\n u = helmholtz( f, k, bc, m, n); \n \n % Converts a function in polar coordinates to one in Cartesian\n % coordinates on the disk\n fdf = pol2cartf(f, r, th);\n \n % Disk harmonics\n Y = harmonic(l,m,type);\n \n % Convert coeffs to a diskfun\n f = coeffs2diskfun(CFS); \n \n \n varargout = coeffs2vals(U, varargin); \n varargout = vals2coeffs(U, varargin);\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% Private Static methods implemented by DISKFUN class.\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods ( Access = private, Static = true )\n \n\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% CLASS PROPERTIES\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n properties (Access = public)\n % DOMAIN: default is [-pi,pi] x [0,1] which corresponds to using \n % polar coordinates. \n % Doubled-up disk will have a domain of [-pi,pi] x [-1,1].\n idxPlus\n idxMinus\n nonZeroPoles = 0;\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% Private constant properties\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n properties ( Constant )\n % TODO: Add support for this constant here.\n %alpha = 50; % Growth factor control.\n end\n \n \nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@diskfun/diskfun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6844256738595348}} {"text": "function [uxref, xref] = xsection(qmethod,xy,x_gal,yref,fig)\n%xsection plots/explores solution on horizontal cross-section \n% [uxref, xref] = xsection(qmethod,xy,x_gal,yref,fig);\n% input\n% qmethod mixed method \n% xy velocity nodal coordinate vector \n% x_gal solution vector\n% yref y-location of grid line \n% fig figure number\n%\n% IFISS function: DJS; 19 September 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \nnvtx=length(xy(:,1));\nkk=find(xy(:,2)==yref);\nif isempty(kk), error('location yref is not a grid-line!'), end\nuxref=x_gal(kk); xref=xy(kk,1);\nfigure(fig)\nplot(xref,uxref,'-k'), axis('square'), title('x-section of flow')\n%%\n%% compute volume of flow using appropriate quadrature\nnny=length(xref); hy=xref(2)-xref(1);\nif qmethod >1,\n%% Simpson's rule\nww=ones(nny,1); ww(2:2:nny-1)=4; ww(3:2:nny-1)=2;\ntotal=(hy/3)*sum(ww.*uxref);\nelse \n%% Trapezium rule\nww=ones(nny,1); ww(2:2:nny-1)=2; ww(3:2:nny-1)=2;\ntotal=(hy/2)*sum(ww.*uxref);\nend\nfprintf('\\narea of x-section is %10.6e \\n',total)\nreturn\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/toms866/graphs/xsection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6844256663620426}} {"text": "%DEMO_MODELASSESMENT1 Demonstration for model assessment with WAIC,\n% DIC, number of effective parameters and ten-fold cross validation\n% \n% Description\n% We will consider the regression problem in demo_regression1. \n% The analysis is conducted with full Gaussian process, and FIC\n% and PIC sparse approximations. The performance of these models\n% are compared by evaluating ten-fold cross validation,\n% leave-one-out cross-validation, WAIC, DIC and the effective\n% number of parameters. The inference will be conducted using\n% maximum a posterior (MAP) estimate for the parameters, via\n% full Markov chain Monte Carlo (MCMC) and with an integration\n% approximation (IA) for the parameters.\n%\n% This demo is organised in three parts:\n% 1) data analysis with full GP model\n% 2) data analysis with FIC approximation\n% 3) data analysis with PIC approximation\n%\n% See also DEMO_REGRESSION1, DEMO_REGRESSION_SPARSE1\n%\n% Copyright (c) 2009-2010 Jarno Vanhatalo\n% Copyright (c) 2010-2012 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\n\n%========================================================\n% PART 1 data analysis with full GP model\n%========================================================\ndisp('Full GP model with Gaussian noise model')\n\n% Load the data\nS = which('demo_regression1');\nL = strrep(S,'demo_regression1.m','demodata/dat.1');\ndata=load(L);\nx = [data(:,1) data(:,2)];\ny = data(:,3);\n[n, nin] = size(x);\n\nDIC=repmat(NaN,1,9);DIC2=repmat(NaN,1,9);DIC_latent=repmat(NaN,1,9);\np_eff=repmat(NaN,1,9);p_eff2=repmat(NaN,1,9);p_eff_latent=repmat(NaN,1,9);p_eff_latent2=repmat(NaN,1,9);\n\n% ---------------------------\n% --- Construct the model ---\ngpcf = gpcf_sexp('lengthScale', [1 1], 'magnSigma2', 0.2^2);\nlik = lik_gaussian('sigma2', 0.2^2);\ngp = gp_set('lik', lik, 'cf', gpcf, 'jitterSigma2', 1e-9);\n\n% -----------------------------\n% --- Conduct the inference ---\n%\n% We will make the inference first by finding a maximum a posterior estimate \n% for the parameters via gradient based optimization. After this we will\n% perform an extensive Markov chain Monte Carlo sampling for the parameters.\n% \ndisp('MAP estimate for the parameters')\n\n% --- MAP estimate ---\n% (see gp_optim for more details)\n\n% Set the options for the optimization\nopt=optimset('TolFun',1e-3,'TolX',1e-3);\n% Optimize with the BFGS quasi-Newton method\ngp=gp_optim(gp,x,y,'opt',opt,'optimf',@fminlbfgs);\n\n% Evaluate the effective number of parameters, DIC and WAIC with focus on\n% latent variables. \nmodels{1} = 'full_MAP';\np_eff_latent = gp_peff(gp, x, y);\n% For easier comparison to other methods, compute mean log\n% predictive density (mlpd) instead of deviance (-2n*mlpd)\n[DIC_latent, p_eff_latent2] = gp_dic(gp, x, y);\nWAICV(1) = gp_waic(gp,x,y);\nWAICG(1) = gp_waic(gp,x,y, 'method', 'G');\n\n\n% Evaluate the 10-fold cross-validation results.\ndisp('MAP estimate for the parameters - k-fold-CV')\ncvres = gp_kfcv(gp, x, y, 'display', 'fold');\nmlpd_cv(1) = cvres.mlpd_cv;\nrmse_cv(1) = cvres.mrmse_cv;\n\ndisp('MAP estimate for the parameters - LOO-CV')\n[Ef,Varf,lpy] = gp_loopred(gp, x, y);\nmlpd_loo(1) = mean(lpy);\nrmse_loo(1) = sqrt(mean((y-Ef).^2));\n\n% --- MCMC approach ---\ndisp('MCMC integration over the parameters')\n\n% Do the sampling (this takes about 1 minute)\n[rfull,g,opt] = gp_mc(gp, x, y, 'nsamples', 220, 'display', 20);\n\n% After sampling delete the burn-in and thin the sample chain\nrfull = thin(rfull, 21, 2);\n\n% Evaluate the effective number of parameters, DIC and WAIC. \nmodels{2} = 'full_MCMC';\n% For easier comparison to other methods, compute mean log\n% predictive density (mlpd) instead of deviance (-2n*mlpd)\n[DIC(2), p_eff(2)] = gp_dic(rfull, x, y, 'focus', 'hyper');\n[DIC2(2), p_eff2(2)] = gp_dic(rfull, x, y);\nWAICV(2) = gp_waic(rfull,x,y);\nWAICG(2) = gp_waic(rfull,x,y, 'method', 'G');\n\n% Evaluate the 10-fold cross validation results. \n%\n% We reduce the number of samples so that the sampling takes less time. \n% 50 is too small sample size, though, and for reliable results the 10-CV \n% should be run with larger sample size.\ndisp('MCMC integration over the parameters - k-fold-CV')\nopt.nsamples= 50; \ncvres = gp_kfcv(gp, x, y, 'inf_method', 'MCMC', 'opt', opt, 'rstream', 1, 'display', 'fold');\nmlpd_cv(2) = cvres.mlpd_cv;\nrmse_cv(2) = cvres.mrmse_cv;\n\ndisp('MCMC integration over the parameters - LOO-CV')\n[Ef,Varf,lpy] = gp_loopred(rfull, x, y);\nmlpd_loo(2) = mean(lpy);\nrmse_loo(2) = sqrt(mean((y-Ef).^2));\n\n% --- Integration approximation approach ---\ndisp('Grid integration over the parameters')\n\ngp_array = gp_ia(gp, x, y, 'int_method', 'grid');\n\nmodels{3} = 'full_IA'; \n% For easier comparison to other methods, compute mean log\n% predictive density (mlpd) instead of deviance (-2n*mlpd)\n[DIC(3), p_eff(3)] = gp_dic(gp_array, x, y, 'focus', 'hyper');\n[DIC2(3), p_eff2(3)] = gp_dic(gp_array, x, y);\nWAICV(3) = gp_waic(gp_array,x,y);\nWAICG(3) = gp_waic(gp_array,x,y, 'method', 'G');\n\n% Then the 10 fold cross-validation.\ndisp('Grid integration over the parameters - k-fold-CV')\nclear opt\nopt.int_method = 'grid';\ncvres = gp_kfcv(gp, x, y, 'inf_method', 'IA', 'opt', opt, 'display', 'fold');\nmlpd_cv(3) = cvres.mlpd_cv;\nrmse_cv(3) = cvres.mrmse_cv;\n\ndisp('Grid integration over the parameters - LOO-CV')\n[Ef,Varf,lpy] = gp_loopred(gp_array, x, y);\nmlpd_loo(3) = mean(lpy);\nrmse_loo(3) = sqrt(mean((y-Ef).^2));\n\n%========================================================\n% PART 2 data analysis with FIC GP\n%========================================================\ndisp('GP with FIC sparse approximation')\n\n% ---------------------------\n% --- Construct the model ---\n\n% Here we conduct the same analysis as in part 1, but this time we \n% use FIC approximation\n\n% Initialize the inducing inputs in a regular grid over the input space\n[u1,u2]=meshgrid(linspace(-1.8,1.8,6),linspace(-1.8,1.8,6));\nX_u = [u1(:) u2(:)];\n\n% Create the FIC GP structure\ngp_fic = gp_set('type', 'FIC', 'lik', lik, 'cf', gpcf, 'jitterSigma2', 1e-6, 'X_u', X_u)\n\n% -----------------------------\n% --- Conduct the inference ---\n\n% --- MAP estimate using scaled conjugate gradient algorithm ---\ndisp('MAP estimate for the parameters')\n\n% Set the options for the optimization\nopt=optimset('TolFun',1e-3,'TolX',1e-3);\n% Optimize with the BFGS quasi-Newton method\ngp_fic=gp_optim(gp_fic,x,y,'opt',opt,'optimf',@fminlbfgs);\n\n% Evaluate the effective number of parameters and DIC with focus on\n% latent variables.\nmodels{4} = 'FIC_MAP';\np_eff_latent(4) = gp_peff(gp_fic, x, y);\n[DIC_latent(4), p_eff_latent2(4)] = gp_dic(gp_fic, x, y);\nWAICV(4) = gp_waic(gp_fic,x,y);\nWAICG(4) = gp_waic(gp_fic,x,y, 'method', 'G');\n\n% Evaluate the 10-fold cross validation results. \ndisp('MAP estimate for the parameters - k-fold-CV')\ncvres = gp_kfcv(gp_fic, x, y, 'display', 'fold');\nmlpd_cv(4) = cvres.mlpd_cv;\nrmse_cv(4) = cvres.mrmse_cv;\n\ndisp('MAP estimate for the parameters - LOO-CV')\n[Ef,Varf,lpy] = gp_loopred(gp_fic, x, y);\nmlpd_loo(4) = mean(lpy);\nrmse_loo(4) = sqrt(mean((y-Ef).^2));\n\n% --- MCMC approach ---\n% (the inducing inputs are fixed)\ndisp('MCMC integration over the parameters')\n\n% Do the sampling (this takes about 1 minute)\nrfic = gp_mc(gp_fic, x, y, 'nsamples', 220, 'display', 20);\n\n% After sampling we delete the burn-in and thin the sample chain\nrfic = thin(rfic, 21, 2);\n\n% Evaluate the effective number of parameters, DIC and WAIC. Note that \n% the effective number of parameters as a second output, but here \n% we use explicitly the gp_peff function\nmodels{5} = 'FIC_MCMC'; \n[DIC(5), p_eff(5)] = gp_dic(rfic, x, y, 'focus', 'hyper');\n[DIC2(5), p_eff2(5)] = gp_dic(rfic, x, y);\nWAICV(5) = gp_waic(rfic,x,y);\nWAICG(5) = gp_waic(rfic,x,y, 'method', 'G');\n\n% We reduce the number of samples so that the sampling takes less time. \n% 50 is too small sample size, though, and for reliable results the 10-CV \n% should be run with larger sample size. We also set the save option to 0.\nclear opt\nopt.nsamples= 50; opt.display=20; \ndisp('MCMC integration over the parameters - k-fold-CV')\ncvres = gp_kfcv(gp_fic, x, y, 'inf_method', 'MCMC', 'opt', opt, 'display', 'fold');\nmlpd_cv(5) = cvres.mlpd_cv;\nrmse_cv(5) = cvres.mrmse_cv;\n\ndisp('MCMC integration over the parameters - LOO-CV')\n[Ef,Varf,lpy] = gp_loopred(rfic, x, y);\nmlpd_loo(5) = mean(lpy);\nrmse_loo(5) = sqrt(mean((y-Ef).^2));\n\n% --- Integration approximation approach ---\ndisp('Grid integration over the parameters')\ngpfic_array = gp_ia(gp_fic, x, y, 'int_method', 'grid');\n\nmodels{6} = 'FIC_IA'; \n[DIC(6), p_eff(6)] = gp_dic(gpfic_array, x, y, 'focus', 'hyper');\n[DIC2(6), p_eff2(6)] = gp_dic(gpfic_array, x, y);\nWAICV(6) = gp_waic(gpfic_array,x,y);\nWAICG(6) = gp_waic(gpfic_array,x,y, 'method', 'G');\n\n% Then the 10 fold cross-validation.\ndisp('Grid integration over the parameters - k-fold-CV')\nclear opt\nopt.int_method = 'grid';\ncvres = gp_kfcv(gp_fic, x, y, 'inf_method', 'IA', 'opt', opt, 'display', 'fold');\nmlpd_cv(6) = cvres.mlpd_cv;\nrmse_cv(6) = cvres.mrmse_cv;\n\ndisp('Grid integration over the parameters - LOO-CV')\n[Ef,Varf,lpy] = gp_loopred(gpfic_array, x, y);\nmlpd_loo(6) = mean(lpy);\nrmse_loo(6) = sqrt(mean((y-Ef).^2));\n\n%========================================================\n% PART 3 data analysis with PIC approximation\n%========================================================\ndisp('GP with PIC sparse approximation')\n\n[u1,u2]=meshgrid(linspace(-1.8,1.8,6),linspace(-1.8,1.8,6));\nX_u = [u1(:) u2(:)];\n\n% Initialize test points\n[p1,p2]=meshgrid(-1.8:0.1:1.8,-1.8:0.1:1.8);\np=[p1(:) p2(:)];\n\n% set the data points into clusters. Here we construct two cell arrays. \n% trindex contains the block index vectors for training data. That is \n% x(trindex{i},:) and y(trindex{i},:) belong to the i'th block.\nb1 = [-1.7 -0.8 0.1 1 1.9];\nmask = zeros(size(x,1),size(x,1));\ntrindex={}; \nfor i1=1:4\n for i2=1:4\n ind = 1:size(x,1);\n ind = ind(: , b1(i1)<=x(ind',1) & x(ind',1) < b1(i1+1));\n ind = ind(: , b1(i2)<=x(ind',2) & x(ind',2) < b1(i2+1));\n trindex{4*(i1-1)+i2} = ind';\n end\nend\n\n% Create the PIC GP structure and set the inducing inputs and block indexes\ngpcf = gpcf_sexp('lengthScale', [1 1], 'magnSigma2', 0.2^2);\nlik = lik_gaussian('sigma2', 0.2^2);\n\ngp_pic = gp_set('type', 'PIC', 'lik', lik, 'cf', gpcf, 'jitterSigma2', 1e-6, 'X_u', X_u);\ngp_pic = gp_set(gp_pic, 'tr_index', trindex);\n\n% -----------------------------\n% --- Conduct the inference ---\n\n% --- MAP estimate using scaled conjugate gradient algorithm ---\ndisp('MAP estimate for the parameters')\n\n% Set the options for the optimization\nopt=optimset('TolFun',1e-3,'TolX',1e-3);\n% Optimize with the BFGS quasi-Newton method\ngp_pic=gp_optim(gp_pic,x,y,'opt',opt,'optimf',@fminlbfgs);\n\nmodels{7} = 'PIC_MAP';\np_eff_latent(7) = gp_peff(gp_pic, x, y);\n[DIC_latent(7), p_eff_latent2(7)] = gp_dic(gp_pic, x, y);\nWAICV(7) = gp_waic(gp_pic, x, y);\nWAICG(7) = gp_waic(gp_pic, x, y, 'method', 'G');\n\n% Evaluate the 10-fold cross validation results. \ndisp('MAP estimate for the parameters - k-fold-CV')\ncvres = gp_kfcv(gp_pic, x, y, 'display', 'fold');\nmlpd_cv(7) = cvres.mlpd_cv;\nrmse_cv(7) = cvres.mrmse_cv;\n\ndisp('MAP estimate for the parameters - LOO-CV')\n[Ef,Varf,lpy] = gp_loopred(gp_pic, x, y);\nmlpd_loo(7) = mean(lpy);\nrmse_loo(7) = sqrt(mean((y-Ef).^2));\n\n% --- MCMC approach ---\ndisp('MCMC integration over the parameters')\n\n% Do the sampling (this takes about 1 minute)\nrpic = gp_mc(gp_pic, x, y, 'nsamples', 220, 'display', 20);\n\n% After sampling we delete the burn-in and thin the sample chain\nrpic = rmfield(rpic, 'tr_index');\nrpic = thin(rpic, 21, 2);\nrpic.tr_index = trindex;\n\n% Evaluate the effective number of parameters and DIC. Note that \n% the effective number of parameters as a second output, but here \n% we use explicitly the gp_peff function\nmodels{8} = 'PIC_MCMC'; \n[DIC(8), p_eff(8)] = gp_dic(rpic, x, y, 'focus', 'hyper');\n[DIC2(8), p_eff2(8)] = gp_dic(rpic, x, y);\nWAICV(8) = gp_waic(rpic, x, y);\nWAICG(8) = gp_waic(rpic, x, y, 'method', 'G');\n\n% We reduce the number of samples so that the sampling takes less time. \n% 50 is too small sample size, though, and for reliable results the 10-CV \n% should be run with larger sample size. We also set the save option to 0.\nclear opt\nopt.nsamples= 50; opt.display=20;\ndisp('MCMC integration over the parameters - k-fold-CV')\ncvres = gp_kfcv(gp_pic, x, y, 'inf_method', 'MCMC', 'opt', opt, 'display', 'fold');\nmlpd_cv(8) = cvres.mlpd_cv;\nrmse_cv(8) = cvres.mrmse_cv;\n\ndisp('MCMC integration over the parameters - LOO-CV')\n[Ef,Varf,lpy] = gp_loopred(rpic, x, y);\nmlpd_loo(8) = mean(lpy);\nrmse_loo(8) = sqrt(mean((y-Ef).^2));\n\n% --- Integration approximation approach ---\ndisp('Grid integration over the parameters')\n\ngppic_array = gp_ia(gp_pic, x, y, 'int_method', 'grid');\n\nmodels{9} = 'PIC_IA'; \n[DIC(9), p_eff(9)] = gp_dic(gppic_array, x, y, 'focus', 'hyper');\n[DIC2(9), p_eff2(9)] = gp_dic(gppic_array, x, y);\nWAICV(9) = gp_waic(gppic_array, x, y);\nWAICG(9) = gp_waic(gppic_array, x, y, 'method', 'G');\n\n% Then the 10 fold cross-validation.\ndisp('Grid integration over the parameters - k-fold-CV')\nclear opt\nopt.int_method = 'grid';\ncvres = gp_kfcv(gp_pic, x, y, 'inf_method', 'IA', 'opt', opt, 'display', 'fold');\nmlpd_cv(9) = cvres.mlpd_cv;\nrmse_cv(9) = cvres.mrmse_cv;\n\ndisp('Grid integration over the parameters - LOO-CV')\n[Ef,Varf,lpy] = gp_loopred(gppic_array, x, y);\nmlpd_loo(9) = mean(lpy);\nrmse_loo(9) = sqrt(mean((y-Ef).^2));\n\n%========================================================\n% PART 4 Print the results\n%========================================================\ndisp('Summary of the results')\nS = ' ';\nfor i = 1:length(models)\n S = [S ' ' models{i}];\nend\n\nS = sprintf([S '\\n CV-mlpd %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f'], mlpd_cv);\nS = sprintf([S '\\n CV-rmse %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f'], rmse_cv);\nS = sprintf([S '\\n LOO-mlpd %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f'], mlpd_loo);\nS = sprintf([S '\\n LOO-rmse %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f'], rmse_loo);\nS = sprintf([S '\\n ']);\nS = sprintf([S '\\n WAIC_V %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f'], WAICV);\nS = sprintf([S '\\n WAIC_G %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f'], WAICG);\nS = sprintf([S '\\n ']);\nS = sprintf([S '\\n DIC_h %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f'], DIC);\nS = sprintf([S '\\n DIC_a %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f'], DIC2);\nS = sprintf([S '\\n DIC_l %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f'], DIC_latent);\nS = sprintf([S '\\n peff_h %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f'], p_eff);\nS = sprintf([S '\\n peff_a %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f'], p_eff2);\nS = sprintf([S '\\n peff_l %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f'], p_eff_latent);\nS = sprintf([S '\\n peff_l2 %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f'], p_eff_latent2);\nS = sprintf([S '\\n ']);\nS = sprintf([S '\\n ']);\nS = sprintf([S '\\n The notation is as follows:']);\nS = sprintf([S '\\n CV-mlpd = mean log predictive density from the 10-fold CV. ']);\nS = sprintf([S '\\n CV-rmse = root mean squared error from the 10-fold LOO-CV. ']);\nS = sprintf([S '\\n LOO-mlpd = mean log predictive density from the LOO-CV. ']);\nS = sprintf([S '\\n LOO-rmse = root mean squared error from the 10-fold CV. ']);\nS = sprintf([S '\\n WAIC_V = WAIC via variance method ']);\nS = sprintf([S '\\n WAIC_G = WAIC via Gibbs training utility method ']);\nS = sprintf([S '\\n DIC_h = DIC with focus on parameters. ']);\nS = sprintf([S '\\n DIC_a = DIC with focus on parameters and latent variables (all). ']);\nS = sprintf([S '\\n DIC_l = DIC with focus on latent variables. ']);\nS = sprintf([S '\\n peff_h = effective number of parameters (latent variables marginalized). ']);\nS = sprintf([S '\\n peff_a = effective number of parameters and latent variables. ']);\nS = sprintf([S '\\n peff_l = effective number of latent variables evaluated with gp_peff. ']);\nS = sprintf([S '\\n peff_l2 = effective number of latent variables evaluated with gp_dic. ']);\nS = sprintf([S '\\n '])\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/gp/demo_modelassesment1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.6844256603967672}} {"text": "function [X S Y dist] = OptSpace(M_E,r,niter,tol)\n% An algorithm for Matrix Reconstruction from a partially revealed set. \n% See \"Matrix Completion from a Few Entries\"(http://arxiv.org/pdf/0901.3150) for details\n% Usage :\n% [X S Y dist] = OptSpace(A,r,niter,tol);\n% [X S Y dist] = OptSpace(A);\n% \n% INPUT :\n% A : The partially revealed matrix.\n% Sparse matrix with zeroes at the unrevealed indices.\n%\n% r : The rank to be used for reconstruction. Use [] to guess the rank.\n% niter : The max. no. of iterations. Use [] to use default (50).\n% tol : Stop iterations if norm( (XSY' - M_E).*E , 'fro' )/sqrt(|E|) < tol, where\n% - E_{ij} = 1 if M_{ij} is revealed and zero otherwise, \n% - |E| is the size of the revealed set.\t\t\t\t\n% - Use [] to use the default (1e-6)\n%\n%\n% OUTPUT :\n% X : A size(A,1)xr matrix\n% S : An rxr matrix\n% Y : A size(A,2)xr matrix\n% such that M_hat = X*S*Y' \n% dist : A vector containing norm( (XSY' - M_E).*E , 'fro' )/sqrt(|E|) at each\n% successive iteration\n%\n% Date : 21st April, 2009\n% COPYRIGHT 2009 Raghunandan H. Keshavan, Andrea Montanari, Sewoong Oh\n\n\n\n\n\nif(nargin==1)\n\t\n\tM_E = sparse(M_E);\n\t[n m] = size(M_E);\n\tE = spones(M_E);\n\teps = nnz(E)/sqrt(m*n) ;\n\n\ttol = 1e-6;\n\n\tfprintf(1,'Rank not specified. Trying to guess ...\\n');\n\tr = guessRank(M_E) ;\n\tfprintf(1,'Using Rank : %d\\n',r);\n\t\n\tm0 = 10000 ;\n\trho = 0;\n\t\n\tniter = 50;\nelseif(nargin==4)\n\t\n\tM_E = sparse(M_E);\n\t[n m] = size(M_E);\n\tE = spones(M_E);\n\teps = nnz(E)/sqrt(m*n) ;\n\n\tif( length(tol) == 0 )\n\t\ttol = 1e-6;\n\tend\n\n\tif( length(r) == 0 )\n\n\t\tfprintf(1,'Rank not specified. Trying to guess ...\\n');\n\t\tr = guessRank(M_E) ;\n\t\tfprintf(1,'Using Rank : %d\\n',r);\n\tend\n\n\tm0 = 10000 ;\n\trho = 0;\n\n\tif( length(niter) == 0 )\n\t\tniter = 50 ;\n\tend\t\nelse\n\tfprintf(1,'Improper arguments (See \"help OptSpace\")\\n');\n\tfprintf(1,'Usage :\\n[X S Y dist] = OptSpace(A,r,niter,tol) \\n') ;\n\tfprintf(1,'[X S Y dist] = OptSpace(A)\\n');\n\treturn;\nend\t\n\nrescal_param = sqrt( nnz(E) * r / norm(M_E,'fro')^2 ) ;\nM_E = M_E * rescal_param ;\n\nfprintf(1,'Trimming ...\\n');\n% Trimming\n\nM_Et = M_E ;\nd = sum(E);\nd_=mean(full(d));\nfor col=1:m\n if ( sum(E(:,col))>2*d_ )\n list = find( E(:,col) > 0 );\n p = randperm(length(list));\n M_Et( list( p(ceil(2*d_):end) ) , col ) = 0;\n end\nend\n\nd = sum(E');\nd_= mean(full(d));\nfor row=1:n\n if ( sum(E(row,:))>2*d_ )\n list = find( E(row,:) > 0 );\n p = randperm(length(list));\n M_Et(row,list( p(ceil(2*d_):end) ) ) = 0;\n end\nend\n\nfprintf(1,'Sparse SVD ...\\n');\n% Sparse SVD\n[X0 S0 Y0] = svds(M_Et,r) ;\n\nclear M_Et;\n\n% Initial Guess\nX0 = X0*sqrt(n) ; Y0 = Y0*sqrt(m) ;\nS0 = S0 / eps ;\n\n\nfprintf(1,'Iteration\\tFit Error\\n');\n\n% Gradient Descent\nX = X0;Y=Y0;\nS = getoptS(X,Y,M_E,E);\n\n\ndist(1) = norm( (M_E - X*S*Y').*E ,'fro')/sqrt(nnz(E) ) ;\nfprintf(1,'0\\t\\t%e\\n',dist(1) ) ;\n\nfor i = 1:niter\n\n% Compute the Gradient \n\t[W Z] = gradF_t(X,Y,S,M_E,E,m0,rho);\n\n% Line search for the optimum jump length\t\n\tt = getoptT(X,W,Y,Z,S,M_E,E,m0,rho) ;\n\tX = X + t*W;Y = Y + t*Z;S = getoptS(X,Y,M_E,E) ;\n\t\n% Compute the distortion\t\n\tdist(i+1) = norm( (M_E - X*S*Y').*E,'fro' )/sqrt(nnz(E));\n\tfprintf(1,'%d\\t\\t%e\\n',i,dist(i+1) ) ;\n\tif( dist(i+1) < tol )\n\t\tbreak ;\n\tend\nend\n\nS = S /rescal_param ;\n\n% Function to Guess the Rank of the input Matrix\nfunction r = guessRank(M_E);\n\t[n m] = size(M_E);\n\tepsilon = nnz(M_E)/sqrt(m*n);\n S0 = svds(M_E,100) ;\n\n S1=S0(1:end-1)-S0(2:end);\n S1_ = S1./mean(S1(end-10:end));\n r1=0;\n lam=0.05;\n while(r1<=0)\n for idx=1:length(S1_)\n cost(idx) = lam*max(S1_(idx:end)) + idx;\n end\n [v2 i2] = min(cost);\n r1 = max(i2-1);\n lam=lam+0.05;\n end\n\n\tclear cost;\n for idx=1:length(S0)-1\n cost(idx) = (S0(idx+1)+sqrt(idx*epsilon)*S0(1)/epsilon )/S0(idx);\n end\n [v2 i2] = min(cost);\n r2 = max(i2);\n\n\tr = max([r1 r2]);\n\n\n\n\n\n\n% * * * * * * * * * * * * * * * * * * * *\n% Function to compute the distortion\nfunction out = F_t(X,Y,S,M_E,E,m0,rho)\n[n r] = size(X) ;\n\nout1 = sum( sum( ( (X*S*Y' - M_E).*E ).^2 ) )/2 ;\n\nout2 = rho*G(Y,m0,r) ;\nout3 = rho*G(X,m0,r) ;\nout = out1+out2+out3 ;\n\nfunction out = G(X,m0,r)\n\nz = sum(X.^2,2)/(2*m0*r) ;\ny = exp( (z-1).^2 ) - 1 ;\ny( find(z < 1) ) = 0 ;\nout = sum(y) ;\n% * * * * * * * * * * * * * * * * * * * *\n\n\n\n% Function to compute the gradient\nfunction [W Z] = gradF_t(X,Y,S,M_E,E,m0,rho)\n[n r] = size(X);\n[m r] = size(Y);\n\nXS = X*S ;\nYS = Y*S' ;\nXSY = XS*Y' ;\n\nQx = X'* ( (M_E - XSY).*E )*YS /n;\nQy = Y'* ( (M_E - XSY).*E )'*XS /m;\n\nW = ( (XSY - M_E).*E )*YS + X*Qx + rho*Gp(X,m0,r);\nZ = ( (XSY - M_E).*E )'*XS + Y*Qy + rho*Gp(Y,m0,r);\n\nfunction out = Gp(X,m0,r)\nz = sum(X.^2,2) /(2*m0*r) ;\nz = 2*exp( (z-1).^2 ).*(z-1) ;\nz( find(z<0) ) = 0;\n\nout = X.*repmat(z,1,r) / (m0*r) ;\n% * * * * * * * * * * * * * * * * * * * *\n\n\n% * * * * * * * * * * * * * * * * * * * *\n% Function to find Sopt given X, Y\nfunction out = getoptS(X,Y,M_E,E)\n\n[n r] = size(X);\nC = X' * ( M_E ) * Y ; C = C(:) ;\n\nfor i = 1:r\n for j = 1:r\n ind = (j-1)*r + i ;\n temp = X' * ( (X(:,i) * Y(:,j)').*E ) * Y ;\n A(:,ind) = temp(:) ;\n end\nend\n\nS = A\\C ;\nout = reshape(S,r,r) ;\n% * * * * * * * * * * * * * * * * * * * *\n\n\n% * * * * * * * * * * * * * * * * * * * *\n% Function to perform line search\nfunction out = getoptT(X,W,Y,Z,S,M_E,E,m0,rho)\nnorm2WZ = norm(W,'fro')^2 + norm(Z,'fro')^2;\nf(1) = F_t(X, Y,S,M_E,E,m0,rho) ;\n\nt = -1e-1 ;\nfor i = 1:20\n f(i+1) = F_t(X+t*W,Y+t*Z,S,M_E,E,m0,rho) ;\n\n if( f(i+1) - f(1) <= .5*(t)*norm2WZ )\n out = t ;\n return;\n end\n t = t/2 ;\nend\nout = t ;\n\n\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/mc/OptSpace/OptSpace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6844233953300184}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\t[velo2, tmax]= SINCHRONIZE(qini, qfinal, velocity) Finds a mean speed and the required \n% time to perform a movement between the joint coordinates qini and qfinal. \n% If the speed of each joint is different, the maximum time to perform the movement\n% by the slower joint is taken as a basis.\n% \n% Inputs:\n%\t\tQini: initial position in joint coordinates.\n%\t\tQfinal: final position in joint coordinates.\n%\t\tVelocity: stores the maximum velocity of each joint.\n% Outputs:\n% velo2: new maximum speed for each joint.\n% tmax: time needed to perform the movement.\n%\n%\tSee also: MOVEJ, COMPUTE_JOINT_TRAJECTORY_INDEP\n% \n% Author: Arturo Gil\n% Date: 29/03/2012\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser 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% ARTE 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 Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction [actual_speed, maxtime]=synchronize(qini, qfinal, speed, accel)\n\ntacel = speed./accel;\n\ntcte = (abs(qfinal(:)-qini(:))-accel(:).*tacel.^2)./speed(:);\n\ntime_total = tcte + 2*tacel;\n\nmaxtime=max(time_total);\n\nactual_speed = (qfinal(:)-qini(:)-accel(:).*tacel.^2)/maxtime(:);", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/RAPID/functions/synchronize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114858, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6844233935692432}} {"text": "function [alpha, b0] = qp_learn(K,Y,C)\n\n a=qpc(K,Y,-C*(Y==-1),C*(Y==1),zeros(length(K),1),1);\n a=a.*Y;\n alpha=a;\n\n H = K.*(Y*Y');\n\n class1 = find (a > max(a)/1e3 & a < 0.99*C & Y == 1);\n class2 = find (a > max(a)/1e3 & a < 0.99*C & Y == -1);\n nAsv = length (class1);\n nBsv = length (class2);\n if (nAsv == 0) & (nBsv==0) \n b0=(min(H(find(a < 0.99*C & Y== 1),:)*a)- min(H(find(a < 0.99*C & Y==-1),:)*a))/2;\n warning ('Threshold might be inacurate');\n else\n\n A = sum(H(class1,:)*a)-nAsv;\n B = sum(H(class2,:)*a)-nBsv;\n b0 = -(A-B)/(nAsv+nBsv);\nend\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/spider/Optimization/qp_learn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6843841333873396}} {"text": "function value = bst_prctile(vector, percentile)\n% BST_PRCTILE: Returns the percentile value in vector\n%\n% USAGE: value = bst_prctile(vector, percentile)\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Martin Cousineau, 2020\n% Raymundo Cassani, 2022 \n\n% Try to use toolbox function\nif exist('prctile','file')\n value = prctile(vector, percentile);\n return;\nend\n\n% Check inputs\nif ~isvector(vector)\n error('Only vectors supported.');\nend\nif any(percentile < 0 | percentile > 100)\n error('Input percentile must be a real value between 0 and 100.');\nend\n\n% Custom implementation\nvector = sort(vector);\nrank = percentile / 100 * length(vector);\nlowerRank = floor(rank + 0.5);\nupperRank = lowerRank + 1;\nfraction = rank - lowerRank;\nlowerRank(lowerRank < 1) = 1;\nupperRank(upperRank > length(vector)) = length(vector);\nvalue = 0.5 * (vector(lowerRank) + vector(upperRank));\n\nif fraction ~= 0\n value = value + fraction * (vector(upperRank) - vector(lowerRank));\nend\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/math/bst_prctile.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.6842925487897791}} {"text": "function plot_laplace( x,params,hAx,plot_num,fontsize )\n% plot the laplace distribution with parameter \"u\" and \"b\"\n% \n% the distribution is given by:\n%\n% p(x) = 1/(2*b)*exp(-abs(x-u)/b)\n%\n% format: plot_laplace( x,params,hAx,plot_num,fontsize )\n%\n% input: x - X axis, for the plot\n% params - the distribution parameter, RMS error and VAR or CRB\n% hAx - where to plot the distribution curve\n% plot_num - since the curve is added with a text to the axes,\n% this parameter specifies where the text should be displayed\n% and what color to choose for the curve\n% fontsize - size of the font of the text, default 9\n%\n%\n% example: plot_laplace( x,fit_ML_laplace(data),hAx,3 )\n%\n\n% init graphic parameters\nswitch plot_num\ncase 1, cl = [1 0 0];\ncase 2, cl = [0 1 0];\ncase 3, cl = [1 0 1];\ncase 4, cl = [0 1 1];\ncase 5, cl = [0.5 0.5 0];\nend\nif ~exist('fontsize')\n fontsize = 9;\nend\np = plot_num*0.15 + 0.3;\nylimit = ylim(hAx);\nxlimit = xlim(hAx);\nfnc_txt = '\\it{1/2\\bfb}\\rm \\bf{\\cdot e}^{-\\mid\\bf{x-\\mu}\\mid/\\bf{b}}\\rm';\nif isfield( params,'VAR' )\n txt = sprintf( '\\\\fontsize{%d}\\\\bfLaplace PDF\\\\rm with %s: %s\\n\\\\mu = %g b = %g\\nVAR(b) = %1.3g\\nRMS err = %1.3g\\n',...\n fontsize,params.type,fnc_txt,params.u,params.b,params.VAR_b,params.RMS );\nelse\n txt = sprintf( '\\\\fontsize{%d}\\\\bfLaplace PDF\\\\rm with %s: %s\\n\\\\mu = %g b = %g\\nCRB(b) = %1.3g\\nRMS err = %1.3g\\n',...\n fontsize,params.type,fnc_txt,params.u,params.b,params.CRB_b,params.RMS ); \nend\n\n% calculate distribution\nu = params.u;\nb = params.b;\ny = 1/(2*b)*exp(-abs(x-u)/b);\n\n% plot and write the text\nline( 'parent',hAx,'xdata',x,'ydata',y,'linewidth',2,'color',cl );\nhTxt = text( 1.2*mean(x),ylimit(2)*p,txt,'parent',hAx );\next = get( hTxt,'Extent' );\nline( ext(1) - xlimit/15 ,(ext(2)+ext(4)/2)*[1 1],'linewidth',3,'color',cl );\n% ext(3) = ext(3)+xlimit(2)/15;\n% rectangle( 'position',ext );", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/FitFunc/Plot/plot_laplace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256353465631, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.6842925386584884}} {"text": "function [h0, h1, g0, g1] = daubf(K,str);\n% [h0, h1, g0, g1] = daubf(K);\n% h0 - low-pass analysis\n% h1 - high-pass analysis\n% g0 - low-pass analysis\n% g1 - high-pass analysis\n%\n% K zeros at z=-1\n% Use daubf(K,'mid') for mid-phase type\n\n% Ivan Selesnick\n% selesi@nyu.edu\n% NYU - School of Engineering\n\n[h,s,g] = maxflatI(K,K-1);\n\nr = roots(g);\nr = r(abs(r) < 1);\nq = real(poly(r));\n\nif nargin > 1\n\tif strcmp(str,'mid')\n\t\tq = sfact_mid(g);\n\tend\nend\n\nq = q/sum(q); % normalize\nh0 = q; % set h0 = q;\nfor k = 1:K % make h0 = q * [(z^(-1)+1)/2]^K\n h0 = conv(h0,[1 1]/2);\nend\nh0 = sqrt(2)*h0; % normalize so that sum(h0) = sqrt(2)\n\nh1 = h0(end:-1:1);\nh1(2:2:end) = -h1(2:2:end);\n\ng0 = h0(end:-1:1);\ng1 = h1(end:-1:1);\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_Proximal/Denoising/WaveletFunctions/daubf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6842733762740192}} {"text": "function c = tapas_softmax_wld_config\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Contains the configuration for the softmax observation model for multinomial responses with phasic\n% volatility exp(mu3) as the decision temperature and parameters accounting for win- and\n% loss-distortion of state values.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2019 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n% Config structure\nc = struct;\n\n% Is the decision based on predictions or posteriors? Comment as appropriate.\nc.predorpost = 1; % Predictions\n%c.predorpost = 2; % Posteriors\n\n% Model name\nc.model = 'softmax_wld';\n\n% Sufficient statistics of Gaussian parameter priors\n\n% Beta\nc.logbemu = log(1);\nc.logbesa = 4^2;\n\n% Win-distortion\nc.la_wdmu = 0;\nc.la_wdsa = 2^-2;\n\n% Loss-distortion\nc.la_ldmu = 0;\nc.la_ldsa = 2^-2;\n\n% Gather prior settings in vectors\nc.priormus = [\n c.logbemu,...\n c.la_wdmu,...\n c.la_ldmu,...\n ];\n\nc.priorsas = [\n c.logbesa,...\n c.la_wdsa,...\n c.la_ldsa,...\n ];\n\n% Model filehandle\nc.obs_fun = @tapas_softmax_wld;\n\n% Handle to function that transforms observation parameters to their native space\n% from the space they are estimated in\nc.transp_obs_fun = @tapas_softmax_wld_transp;\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_softmax_wld_config.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6842733750904543}} {"text": "clear;clc\n\n%% Designing a decimation filter.\n% We start by desinging a decimation filter in double precision. The\n% decimation filter is a low pass filter with a decimation rate of 64. The\n% filter specification is from the AD1877 Anolog Devices Sigma-Delta\n% data sheet. You can find the data sheet at\n% http://www.analog.com/UploadedFiles/Data_Sheets/AD1877.pdf\n\n% The desing of the filter takes about 10 seconds. As such, for a faster\n% start up the design is stored in a file. If you need to redesign the\n% filter, simply uncomment the lines below and run the script.\n\nDecimation_Factor=64;\nPassband_Ripple=.006; %dB\nStopband_Attenuation=90; %dB\nFs=48e3;\nPassband=21.6e3; %dB\nStopband=26.4e3; %dB\n\nInput_Sampling_Rate = Decimation_Factor*Fs;\nf=fdesign.decimator(Decimation_Factor,'lowpass',Passband,Stopband,...\n Passband_Ripple,Stopband_Attenuation,Input_Sampling_Rate);\nh=design(f);\n\nsave one_stage h\nfvtool(h,'Fs',Input_Sampling_Rate);\n\n\n%% To have a more efficnet implementation, we break down the filter into\n\nhm=design(f,'multistage','Nstages',3);\n\nsave multi_stage hm\nfvtool(h,'Fs',Input_Sampling_Rate);\n\n%% We then convert the filter into fixed-point.\nhf=hm;\n\nhf.stage(1).Arithmetic = 'fixed';\nhf.stage(1).CoeffWordLength = 24;\nhf.stage(1).InputWordLength = 2;\nhf.stage(1).InputFracLength = 0;\nspecifyall(hf.stage(1));\nhf.stage(1).OutputWordLength = 12;\nhf.stage(1).OutputFracLength = 10;\nhf.stage(1).ProductWordLength = 8;\nhf.stage(1).ProductFracLength = 10;\nhf.stage(1).AccumWordLength = 13;\nhf.stage(1).AccumFracLength = 10;\nhf.stage(1).RoundMode = 'nearest';\n\nhf.stage(2).Arithmetic = 'fixed';\nhf.stage(2).CoeffWordLength = 24;\nhf.stage(2).InputWordLength = 13;\nhf.stage(2).InputFracLength = 10;\nspecifyall(hf.stage(2));\nhf.stage(2).OutputWordLength = 13;\nhf.stage(2).OutputFracLength = 10;\nhf.stage(2).ProductWordLength = 10;\nhf.stage(2).ProductFracLength = 10;\nhf.stage(2).AccumWordLength = 13;\nhf.stage(2).AccumFracLength = 10;\nhf.stage(2).RoundMode = 'nearest';\n\nhf.stage(3).Arithmetic = 'fixed';\nhf.stage(3).CoeffWordLength = 24;\nhf.stage(3).InputWordLength = 13;\nhf.stage(3).InputFracLength = 10;\nspecifyall(hf.stage(3));\nhf.stage(3).ProductWordLength = 11;\nhf.stage(3).ProductFracLength = 12;\nhf.stage(3).AccumWordLength = 14;\nhf.stage(3).AccumFracLength = 12;\nhf.stage(3).OutputWordLength = 16;\nhf.stage(3).OutputFracLength = 15;\nhf.stage(3).RoundMode = 'nearest';\nhf.stage(3).OverflowMode = 'saturate';\n\nsave multi_stage_fixed hf\n\nfvtool(hf,'Fs',Input_Sampling_Rate);\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/16416-sigma-delta-adc-from-behavioral-model-to-verilog-and-vhdl/Sigma_Delta/filter_design.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6842733735664979}} {"text": "function r = acosh(a)\n%ACOSH Hessian (elementwise) inverse hyperbolic cosine\n%\n\n% written 04/04/04 S.M. Rump\n% modified 04/06/05 S.M. Rump rounding unchanged\n% modified 09/28/08 S.M. Rump check for rounding to nearest improved\n% modified 08/26/12 S.M. Rump global variables removed\n%\n\n e = 1e-30;\n if 1+e==1-e % fast check for rounding to nearest\n rndold = 0;\n else\n rndold = getround;\n setround(0)\n end\n\n K = prod(size(a.x));\n if K==1 % scalar hessian\n \n r.x = acosh(a.x);\n f = sqr(a.x) - 1;\n fs = 1 / ( sqrt(a.x+1)*sqrt(a.x-1) );\n r.dx = a.dx * fs;\n r.hx = a.hx * fs - reshape( ( (0.5*a.x/f)*r.dx ) * a.dx.' , size(a.hx) );\n \n else % matrix hessian\n \n N = getappdata(0,'INTLAB_HESSIAN_NUMVAR');\n N2 = N^2;\n \n r.x = acosh(a.x);\n if issparse(a.hx) % input sparse\n \n ax = full(a.x(:));\n f = sqr(ax) - 1;\n ax = 1 ./ ( sqrt(ax+1).*sqrt(ax-1) );\n sizeax = length(ax);\n [ia,ja,sa] = find(a.dx);\n % check for emptyness: cures Matlab bug\n % a=sparse([],[],[],2,1), [i,j,s]=find(a), s(i).*s(:) yields error\n if isempty(ia)\n r.dx = sparse([],[],[],N,sizeax);\n r.hx = sparse([],[],[],N2,sizeax);\n else\n adx1 = ( -0.5*full(a.x(:)) ) ./ f;\n if isa(a.x,'intval') % sparse intval\n rdx = times(ax(ja),sa(:),0);\n adx1 = times(adx1(ja),sa(:),0);\n if rdx.complex\n r.dx = intval( sparse(ia,ja,rdx.mid,N,sizeax) , sparse(ia,ja,rdx.rad,N,sizeax) , 'midrad' );\n else\n r.dx = intval( sparse(ia,ja,rdx.inf,N,sizeax) , sparse(ia,ja,rdx.sup,N,sizeax) , 'infsup' );\n end\n if adx1.complex\n adx1 = intval( sparse(ia,ja,adx1.mid,N,sizeax) , sparse(ia,ja,adx1.rad,N,sizeax) , 'midrad' );\n else\n adx1 = intval( sparse(ia,ja,adx1.inf,N,sizeax) , sparse(ia,ja,adx1.sup,N,sizeax) , 'infsup' );\n end\n else % sparse point \n r.dx = sparse(ia,ja,ax(ja).*sa(:),N,sizeax); \n adx1 = sparse(ia,ja,adx1(ja).*sa(:),N,sizeax); \n end \n r.hx = adx2rhx(N,sizeax,adx1,r.dx);\n end\n [ia,ja,sa] = find(a.hx); % sparse point or intval\n % check for emptyness: cures Matlab bug\n % a=sparse([],[],[],2,1), [i,j,s]=find(a), s(i).*s(:) yields error\n if ~isempty(ia)\n if isa(a.x,'intval')\n rhx = times(ax(ja),sa(:),0);\n if rhx.complex\n r.hx = r.hx + intval( sparse(ia,ja,rhx.mid,N2,sizeax) , sparse(ia,ja,rhx.rad,N2,sizeax) , 'midrad' );\n else\n r.hx = r.hx + intval( sparse(ia,ja,rhx.inf,N2,sizeax) , sparse(ia,ja,rhx.sup,N2,sizeax) , 'infsup' );\n end\n else\n r.hx = r.hx + sparse(ia,ja,ax(ja).*sa(:),N2,sizeax);\n end\n end\n \n else % input full\n \n r.x = acosh(a.x);\n ax = a.x(:).';\n f = sqr(ax) - 1;\n fs = 1 ./ ( sqrt(ax+1).*sqrt(ax-1) );\n fs = fs(ones(N*N,1),:);\n r.dx = a.dx .* fs(1:N,:);\n adx = repmat(0.5*ax./f,N,1) .* r.dx;\n r.hx = a.hx .* fs - adx(repmat(1:N,N,1),:) .* a.dx(repmat(1:N,1,N),:);\n \n end\n \n end\n \n r = class(r,'hessian');\n \n if rndold\n setround(rndold)\n end\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/hessian/@hessian/acosh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6842733699268018}} {"text": "function FPDF = GammaGenPDF (a)\n% Return function handles to routines to calculate the area, mean,\n% and second moment of a unit-variance, zero-mean, generalized\n% Gamma probability density function with parameter a.\n% b\n% Farea(a,b) = Int p(x) dx\n% a\n% b\n% Fmean(a,b) = Int x p(x) dx\n% a\n% b\n% Fvar(a,b) = Int x^2 p(x) dx\n% a\n% where p(x) = b/(2G(a) exp(-b|x|) (b|x|)^(a-1)\n% with b=sqrt(a(a+1)) and where G(a) is the complete gamma function.\n\n% global GGenPar\nGGenPar = a; % GGenPar available to nested functions\n\nFPDF = {@GGenarea, @GGenmean, @GGenvar};\n\nreturn\n\n%----- ----- begin nested functions\nfunction v = GGenarea (a, b)\n\n% Evaluate the function so as to avoid taking differences\n% between nearly equal quantities (e.g. when a<0 and b<0)\nif (b >= 0)\n if (a >= 0)\n v = F0(b) - F0(a); % Both a and b positive\n else\n v = (F0(b) + 0.5) + (F0(-a) + 0.5); % a negative, b positive\n end\nelse\n if (a < 0)\n v = F0(-a) - F0(-b); % Both a and b negative\n else\n v = (-0.5 - F0(a)) + (-0.5 - F0(-b)); % a positive, b negative\n end\nend\n\nreturn\nend\n\n% -----\n% Evaluate the indefinite integral\n% The definite integral between a and b is F0(b) - F0(a)\n\nfunction v = F0(x)\n\n% global GGenPar\n\nv = -Gamma2aCCDF(x, GGenPar);\n\nreturn\nend\n\n% ----- ------\nfunction v = GGenmean (a, b)\n\n% Since the integrand x*p(x) is odd, Gmean(A,B)=Gmean(abs(A),abs(B))\nv = F1(abs(b)) - F1(abs(a));\n\nreturn\nend\n\n% -----\n% Evaluate the indefinite integral\n% The definite integral between a and b is F1(b) - F1(a)\n\nfunction v = F1 (x)\n\n% global GGenPar\n\nn = 1;\na1 = GGenPar;\na2 = a1 + n;\nb1 = sqrt(a1*(a1+1));\nb2 = sqrt(a2*(a2+1));\nv = -gamma(a2)/(gamma(a1)*b1^n) * Gamma2aCCDF(b1*abs(x)/b2, a2);\n% Simplifications for n=1,\n% G(a2)=(a1+1) G(a1)\n% Then\n% G(a2)/(G(a1) b1) = sqrt((a1+1)/a1)\n% b1/b2 = sqrt(a1/(a1+1))\n\nreturn\nend\n\n% ----- ------\nfunction v = GGenvar (a, b)\n\n% Evaluate the function so as to avoid taking differences\n% between nearly equal quantities (e.g. when a<0 and b<0)\nif (b >= 0)\n if (a >= 0)\n v = F2(b) - F2(a); % Both a and b positive\n else\n v = (F2(b) + 0.5) + (F2(-a) + 0.5); % a negative, b positive\n end\nelse\n if (a < 0)\n v = F2(-a) - F2(-b); % Both a and b negative\n else\n v = (-0.5 - F2(a)) + (-0.5 - F2(-b)); % a positive, b negative\n end\nend\n\nreturn\nend\n\n% -----\n% Evaluate the indefinite integral\n% The definite integral between a and b is F2(b) - F2(a)\n\nfunction v = F2 (x)\n\n% global GGenPar\n\nn = 2;\na1 = GGenPar;\na2 = a1 + n;\nb1 = sqrt(a1*(a1+1));\nb2 = sqrt(a2*(a2+1));\nv = -gamma(a2)/(gamma(a1)*b1^n) * Gamma2aCCDF(b1*x/b2, a2);\n% Simplifications for n=2,\n% G(a2)=(a1+2)(a1+1) G(a1)\n% Then\n% G(a2)/(G(a1) b1^2) = (a1+2)/a1\n% b1/b2 = sqrt(a1(a1+1)/((a1+2)(a1+3))\nreturn\nend\n\n% ---- end of the nested functions\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/24333-quantizers/Quantizer/private/GammaGenPDF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624557, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6842733596884989}} {"text": "function t = fractile(x, f)\n%FRACTILE finds fractiles of a distribution\n% T = FRACTILE(X, F) finds a value T for which a fraction F of the\n% elements of X are less than T. A fractile is like a centile, except\n% that the argument is a fraction rather then a percentage.\n% \n% Linear interpolation is used between data points. The minimum and\n% maximum values in X are returned for F=0 and F=1 respectively. F may be\n% a matrix; the result is the corresponding matrix of fractiles.\n\n% Note on the algorithm:\n% Forming a histogram seems to take as long as SORT, but sort is much\n% simpler, since histogramming always needs to be used recursively to work\n% with uneven distributions. However, for very large amounts of data it may\n% be worthwhile to look at providing a recursive histogram method.\n\nvalidateattributes(x, {'numeric'}, {});\nvalidateattributes(f, {'numeric'}, {'>=' 0 '<=' 1});\n\nx = sort(x(:));\nn = numel(x);\nfn = n * f(:); % the ideal index into sorted g\n\ni = floor(fn + 0.5); % index of value just less than f\n\nga = x(max(i, 1));\ngb = x(min(i+1, n));\n\nr = fn + 0.5 - i;\nt = (1-r) .* ga + r .* gb; % interpolate\n\nt = reshape(t, size(f));\n\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/canny/fractile.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6842661682806984}} {"text": "function [ a, more ] = vec_colex_next2 ( dim_num, base, a, more )\n\n%*****************************************************************************80\n%\n%% VEC_COLEX_NEXT2 generates vectors in colex order.\n%\n% Discussion:\n%\n% The vectors are produced in colexical order, starting with\n% (0,0,...,0),\n% (1,0,...,0),\n% ...\n% (BASE(1)-1,BASE(2)-1,...,BASE(DIM_NUM)-1).\n%\n% Example:\n%\n% DIM_NUM = 2, \n% BASE = [ 3, 3]\n%\n% 0 0\n% 1 0\n% 2 0\n% 0 1\n% 1 1\n% 2 1\n% 0 2\n% 1 2\n% 2 2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Dennis Stanton, Dennis White,\n% Constructive Combinatorics,\n% Springer, 1986,\n% ISBN: 0387963472,\n% LC: QA164.S79.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer BASE(DIM_NUM), the base to be used in each dimension.\n%\n% Input, integer A(DIM_NUM), except on the first call, this should\n% be the output value of A on the last call.\n%\n% Input, logical MORE, should be FALSE on the first call, and\n% thereafter should be the output value of MORE from the previous call. \n%\n% Output, integer A(DIM_NUM), the next vector.\n%\n% Output, logical MORE, is TRUE if another vector was computed.\n% If MORE is FALSE on return, then ignore the output value A, and\n% stop calling the routine.\n%\n if ( ~more )\n\n a(1:dim_num) = 0;\n more = 1;\n\n else\n \n for i = 1 : dim_num\n\n a(i) = a(i) + 1;\n\n if ( a(i) < base(i) )\n return\n end\n\n a(i) = 0;\n\n end\n\n more = 0;\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_open/vec_colex_next2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.6842661532375847}} {"text": "function a = rutis3_eigen_right ( )\n\n%*****************************************************************************80\n%\n%% RUTIS3_EIGEN_RIGHT returns the right eigenvectors of the RUTIS3 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, complex A(4,4), the right eigenvector matrix.\n%\n i = sqrt ( -1.0 );\n\n a(1:4,1:4) = [\n 1.0, - 1.0, 1.0, 1.0; ...\n 1.0, - i - i, -1.0; ...\n 1.0, i, i, -1.0; ...\n 11.0, 1.0, - 1.0, 1.0 ]';\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/test_mat/rutis3_eigen_right.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6842661521905353}} {"text": "%% Perceptually Uniform Colormaps from MatPlotLib\n% The submission includes the\n% default colormap family and default line colororder family from\n% MatPlotLib 2 and 3. This document shows examples of their usage.\n%% Overview\nmatplotlib_plot\n%% |VIRIDIS| Default Colormap\nclose()\nload spine\nimage(X)\ncolormap(viridis)\n%% |CIVIDIS|\ncolormap(cividis)\n%% |INFERNO|\ncolormap(inferno)\n%% |MAGMA|\ncolormap(magma)\n%% |PLASMA|\ncolormap(plasma)\n%% |TWILIGHT| (cyclical)\ncolormap(twilight)\n%% |TAB10| Default Line ColorOrder\nN = 20;\nclf()\naxes('ColorOrder',tab10(N),'NextPlot','replacechildren')\nX = linspace(0,pi*3,1000);\nY = bsxfun(@(x,n)n*sin(x+2*n*pi/N), X(:), 1:N);\nplot(X,Y, 'linewidth',4)\n%% |TAB20|\nclf()\naxes('ColorOrder',tab20(N),'NextPlot','replacechildren')\nplot(X,Y, 'linewidth',4)\n%% |TAB20B|\nclf()\naxes('ColorOrder',tab20b(N),'NextPlot','replacechildren')\nplot(X,Y, 'linewidth',4)\n%% |TAB20C|\nclf()\naxes('ColorOrder',tab20c(N),'NextPlot','replacechildren')\nplot(X,Y, 'linewidth',4)", "meta": {"author": "kavli-ntnu", "repo": "MINI2P_toolbox", "sha": "83311a49baea69ecf027e19390e608fd4eaeae8d", "save_path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox", "path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox/MINI2P_toolbox-83311a49baea69ecf027e19390e608fd4eaeae8d/Analysis/+CMP_WJ/matplotlib_doc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6842661501836245}} {"text": "function y=bitsprec(x,n,mode)\n%BITSPREC round values to a specified fixed or floating precision (X,N,MODE)\n%\n% mode is of the form 'uvw' where:\n% u: s - n significant bits (default) \n% f - fixed point: n bits after binary point\n% v: n - round to nearest (default)\n% p - round towards +infinity\n% m - round towards -infinity\n% z - round towards zero\n% w is only needed if v=n in which case it dictates what to\n% do if x is min-way between two rounded values:\n% w: p,m - as above\n% e - round to nearest even number (default)\n% o - round to nearest odd number\n% a - round away from zero\n% mode='*ne' and '*no' are convergent rounding and introduce\n% no DC offset into the result so long as even and odd integer parts are\n% equally common.\n%\n% Examples of y=bitsprec(x,0,'***'):\n%\n% x fp- fm- fz- fne fno fnp fnm fna \n% \n% 2.5 3 2 2 2 3 3 2 3\n% 1.5 2 1 1 2 1 2 1 2\n% 1.1 2 1 1 1 1 1 1 1\n% 1.0 1 1 1 1 1 1 1 1\n% 0.9 1 0 0 1 1 1 1 1\n% 0.5 1 0 0 0 1 1 0 1\n% 0.1 1 0 0 0 0 0 0 0\n% -0.1 0 -1 0 0 0 0 0 0\n% -0.5 0 -1 0 0 -1 0 -1 -1\n% -0.9 0 -1 0 -1 -1 -1 -1 -1\n% -1.5 -1 -2 -1 -2 -1 -1 -2 -2\n\n% Copyright (C) Mike Brookes 1997\n% Version: $Id: bitsprec.m 713 2011-10-16 14:45:43Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\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 can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin<3\n mode='sne';\nend\nif mode(1)=='f'\n e=0;\nelse\n [x,e]=log2(x);\nend\nswitch mode(2)\ncase 'p'\n y=pow2(ceil(pow2(x,n)),e-n);\ncase 'm'\n y=pow2(floor(pow2(x,n)),e-n);\ncase 'z'\n y=pow2(fix(pow2(x,n)),e-n);\notherwise\n switch mode(3)\n case 'a'\n y=pow2(round(pow2(x,n)),e-n);\n case 'p'\n y=pow2(floor(pow2(x,n)+0.5),e-n);\n case 'm'\n y=pow2(ceil(pow2(x,n)-0.5),e-n);\n otherwise\n z=pow2(x,n-1);\n switch mode(3)\n case 'e'\n y=pow2(floor(pow2(x,n)+0.5)-floor(z+0.75)+ceil(z-0.25),e-n);\n case 'o'\n y=pow2(ceil(pow2(x,n)-0.5)+floor(z+0.75)-ceil(z-0.25),e-n);\n end \n end\nend\n\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/bitsprec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6842615025984112}} {"text": "function a = daub8 ( n )\n\n%*****************************************************************************80\n%\n%% DAUB8 returns the DAUB8 matrix.\n%\n% Discussion:\n%\n% The DAUB8 matrix is the Daubechies wavelet transformation matrix\n% with 8 coefficients.\n%\n% Properties:\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% 04 July 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Gilbert Strang, Truong Nguyen,\n% Wavelets and Filter Banks,\n% Wellesley-Cambridge Press, 1997,\n% ISBN: 0-9614088-7-1,\n% LC: TK7872.F5S79 / QA403.3.S87\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be at least 8, and a multiple of 2.\n%\n% Output, real A(N,N), the matrix.\n%\n if ( n < 8 || mod ( n, 2 ) ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'DAUB8 - Fatal error!\\n' );\n fprintf ( 1, ' N must be at least 6 and a multiple of 2.\\n' );\n error ( 'DAUB8 - Fatal error!' );\n end\n\n a = zeros ( n, n );\n\n c = [ ...\n 0.2303778133088964, ... \n 0.7148465705529154, ...\n 0.6308807679298587, ...\n -0.0279837694168599, ...\n -0.1870348117190931, ...\n 0.0308413818355607, ...\n 0.0328830116668852, ...\n -0.0105974017850690 ]';\n\n for i = 1 : 2 : n - 1\n\n a(i,i) = c(1);\n a(i,i+1) = c(2);\n a(i,i4_wrap(i+2,1,n)) = c(3);\n a(i,i4_wrap(i+3,1,n)) = c(4);\n a(i,i4_wrap(i+4,1,n)) = c(5);\n a(i,i4_wrap(i+5,1,n)) = c(6);\n a(i,i4_wrap(i+6,1,n)) = c(7);\n a(i,i4_wrap(i+7,1,n)) = c(8);\n\n a(i+1,i) = c(8);\n a(i+1,i+1) = - c(7);\n a(i+1,i4_wrap(i+2,1,n)) = c(6);\n a(i+1,i4_wrap(i+3,1,n)) = - c(5);\n a(i+1,i4_wrap(i+4,1,n)) = c(4);\n a(i+1,i4_wrap(i+5,1,n)) = - c(3);\n a(i+1,i4_wrap(i+6,1,n)) = c(2);\n a(i+1,i4_wrap(i+7,1,n)) = - c(1);\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/test_mat/daub8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772220439509, "lm_q2_score": 0.7826624890918021, "lm_q1q2_score": 0.6841074542633664}} {"text": "\nfunction [rfAmp,rfPhase,rfFreq,rfCoil,rfTime]=rfTanhTan(p)\n%create a Tanh/Tan adiabatic inversion rf pulse starting from tStart and ending at tEnd\n%tStart rf start time\n%tEnd rf end time\n%dt rf sample time\n%rfPhase rf phase\n%rfFreq rf off-res freq\n\ntStart=p.tStart;\ntEnd=p.tEnd;\ndt=p.dt;\nMaxB1=p.MaxB1; % Maxium B1\nTBP=p.TBP; % Time bandwidth product\nrfPhase=p.rfPhase;\nrfCoil=p.CoilID;\nDuplicates=max(1,p.Duplicates);\nDupSpacing=max(0,p.DupSpacing);\n\ntEnd=tEnd-tStart;\ntStart=0; % time scale shift to 0\n\nZeta=10;\nKappa=atan(20);\nA=TBP*pi/(tEnd-tStart);\n\nrfTime=linspace(tStart,tEnd,ceil((tEnd-tStart)/dt)+1);\n\nrfTime1=rfTime(rfTime<(tEnd-tStart)/2);\nrfAmp1=MaxB1.*tanh((2*Zeta.*rfTime1)/(tEnd-tStart)); % rf amplitude modulation\nrfFreq1=A.*(tan(Kappa*(1-2*rfTime1/(tEnd-tStart)))/tan(Kappa))/(2*pi); % rf frequency modulation\nrfTime2=(tEnd-tStart)-rfTime(rfTime>=(tEnd-tStart)/2);\nrfAmp2=MaxB1.*tanh((2*Zeta.*rfTime2)/(tEnd-tStart)); % rf amplitude modulation\nrfFreq2=-A.*(tan(Kappa*(1-2*rfTime2/(tEnd-tStart)))/tan(Kappa))/(2*pi); % rf frequency modulation\n\nrfAmp=[rfAmp1 rfAmp2];\nrfFreq=[rfFreq1 rfFreq2];\nrfPhase=(rfPhase)*ones(size(rfTime)); % rf Phase\n\nrfTime=rfTime+p.tStart; % time scale shift back\nrfCoil=(rfCoil)*ones(size(rfTime));\nrfAmp(1)=0;\nrfAmp(end)=0;\nrfFreq(1)=0;\nrfFreq(end)=0;\nrfPhase(1)=0;\nrfPhase(end)=0;\n\n% Create Duplicates\nif Duplicates~=1 & DupSpacing ~=0\n rfAmp=repmat(rfAmp,[1 Duplicates]);\n rfFreq=repmat(rfFreq,[1 Duplicates]);\n rfPhase=repmat(rfPhase,[1 Duplicates]);\n rfCoil=repmat(rfCoil,[1 Duplicates]);\n TimeOffset = repmat(0:DupSpacing:(Duplicates-1)*DupSpacing,[length(rfTime) 1]);\n rfTime=repmat(rfTime,[1 Duplicates]) + (TimeOffset(:))';\nend\n\nend", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/Macro/SeqElem/rf/rfTanhTan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787563, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6840260926297366}} {"text": "function x3 = mltply ( xx, x2, npl )\n\n%*****************************************************************************80\n%\n%% MLTPLY multiplies two Chebyshev series.\n%\n% Discussion:\n%\n% This routine multiplies two given Chebyshev series, XX and X2,\n% to produce an output Chebyshev series, X3.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Roger Broucke.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Roger Broucke,\n% Algorithm 446:\n% Ten Subroutines for the Manipulation of Chebyshev Series,\n% Communications of the ACM,\n% October 1973, Volume 16, Number 4, pages 254-256.\n%\n% Parameters:\n%\n% Input, real XX(NPL), the first Chebyshev series.\n%\n% Input, real X2(NPL), the second Chebyshev series.\n%\n% Input, integer NPL, the number of terms in the \n% Chebyshev series.\n%\n% Output, real X3(NPL), the Chebyshev series of the\n% product.\n%\n x3(1:npl) = 0.0;\n\n for k = 1 : npl\n ex = 0.0;\n mm = npl - k + 1;\n for m = 1 : mm\n l = m + k - 1;\n ex = ex + xx(m) * x2(l) + xx(l) * x2(m);\n end\n x3(k) = 0.5 * ex;\n end\n\n x3(1) = x3(1) - 0.5 * xx(1) * x2(1);\n\n for k = 3 : npl\n ex = 0.0;\n mm = k - 1;\n for m = 2 : mm\n l = k - m + 1;\n ex = ex + xx(m) * x2(l);\n end\n x3(k) = 0.5 * ex + x3(k);\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/toms446/mltply.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.683998436310779}} {"text": "%==============================================================================\n% (c) Jan Modersitzki 2011/04/26, see FAIR.2 and FAIRcopyright.m.\n% http://www.mic.uni-luebeck.de/people/jan-modersitzki.html\n%\n% For an extended documentation, see:\n% Jan Modersitzki. FAIR: Flexible Algorithms for Image Registration, SIAM, 2009.\n% http://www.siam.org/books/fa06/\n% \n% KERNEL/MATRIXFREE\n%\n% Contents of FAIR MATRIXFREE\n%\n% MGsolver - calls MG solver\n% mfvcyce - MG solver\n% mfPu.m - matrix free prolongation operator\n% mfJacobi - MG smoother\n% mfAy - MG matrix vector operation (M+alpha*B'*B)\n% mfBy - matrix free B*y for discrete regularizer\n% testMatrixFree - test the files in this folder\n%==============================================================================\n\nfunction debit = contents\nif nargout == 0, help(mfilename); return; end;\n\ndebit = {\n 'contents.m'\n \n 'MGsolver.m'\n 'mfvcycle.m'\n 'mfAy.m'\n 'mfJacobi.m'\n 'mfPu.m'\n \n 'testMatrixFree.m' \n };\n%==============================================================================\n\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/matrixfree/contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6839984334500607}} {"text": "function FIM=observedFisherInfo(z,RInv,h,JacobMat,HessMat)\n%%OBSERVEDFISHERINFO Assuming that a linear or nonlinear measurement is\n% corrupted with zero-mean Gaussian noise, the observed Fisher\n% information matrix (FIM) has a standard form in terms of the\n% values of the measurement function and its first and second\n% derivatives. This function takes those values and returns the\n% observed FIM. Summing the FIMs from multiple simultaneous\n% independent measurements or measurement components returns the\n% observed FIM for the fused measurement. The inverse of the FIM\n% is the Cram\u00e9r-Rao lower bound (CRLB). If only a single\n% measurement is considered, and h=z, then h, z, and HessMat can\n% all be omitted. Usualy, there is no benefit to including the\n% terms.\n%\n%INPUTS: z The zDimX1 measurement, or if multiple measurements of the same\n% time are to the zDimXnumMeas matrix of those measurements. This\n% can be omitted if one just wants the FIM without this.\n% RInv The zDimXzDim inverse of the covariance matrix associated with\n% the multivariate Gaussian noise corrupting z, or if multiple\n% measurements are to be fused AND RInv differs among them, then a\n% zDimXzDimXnumMeas collection of all of the inverse matrices. If\n% z is omitted and multiple measurements are fused, then RInv MUST\n% be specified as a zDimXzDimXnumMeas matrix, not as a single\n% zDimXzDim matrix.\n% h The zDimX1 value of the xDimX1 state converted into the\n% measurement domain. If z is omitted, then this is not needed.\n% JacobMat The zDimXxDim Jacobian matrix of derivatives of the measurement\n% function h taken with respect to the elements of the target\n% state. This is assumed the same for all measurements fused by\n% this function.\n% HessMat The xDimXxDimXzDim matrix of second derivatives of the\n% measurement function h with respect to the elements of the state\n% x. HessMat(i,j,k) is the Hessian for the kth measurement\n% component with derivatives taken with respect to elements i and\n% j of the x vector. i and j can be equal. Note that all\n% HessMat(:,:,k) are symmetric matrices. In 3D, the order of the\n% second derivatives in each submatrix is of the form:\n% [d^2/(dxdx), d^2/(dxdy), d^2/(dxdz);\n% d^2/(dydx), d^2/(dydy), d^2/(dydz);\n% d^2/(dzdx), d^2/(dzdy), d^2/(dzdz)];\n%\n%OUTPUTS: FIM The xDimXxDim observed Fisher information matrix.\n%\n%The FIM and CRLB and in many statistics texts. When considering target\n%tracking, one can look at Chapter 2.7.2 of [1]. Since no expectation is\n%taken for the observed Fisher information matrix, only the form in terms\n%of second derivatives in [1] can be used, not the form in terms of an\n%outer product of first derivatives. The use of the inverse of the observed\n%FIM in characterizing the accuracy of ML estimates is discussed in [2].\n%\n%The observed FIM is simply the negative of the matrix of second\n%derivatives of the logarithm of the likelihood function. In the problem at\n%hand:\n%nabla_{x}(\\nabla_x)'log(p(z|x))\n%where here p(z|x)=1/sqrt(det(2*pi*R))*exp(-(1/2)*(z-h(x))'*inv(R)*(z-h(x))\n%The gradient of the logarithm of the likelihood function is\n%nabla_{x}log(p(z|x))=-H'*inv(R)(h(x)-z)\n%where H=nabla_{x} h(x)'\n%The matrix of second derivatives is thus\n%nabla_{x}(\\nabla_x)'log(p(z|x))=-H'*inv(R)*H-C\n%where the jth column of C is given by\n%C(:,j)=((\\partial / \\partial x_j)H')*inv(R)*(h(x)-z)\n%\n%EXAMPLE 1:\n%In this example, we consider how well the observed FIM can be used as the\n%covariance matrix of a fused measurement. In this instance, with all of\n%the measurement being the same accuracy, we just average the measurements\n%to get a fused measurement. We then find the NEES both with and without\n%using the Hessian term. It is seen that when using the Hessian term, the\n%NEES is closet to 1 than when not using the Hessian term.\n% numMCRuns=10000;\n% numMeas=3;\n% sigmaR=100;\n% sigmaAz=3*(pi/180);\n% sigmaEl=3*(pi/180);\n% SR=diag([sigmaR;sigmaAz;sigmaEl]);\n% R=SR*SR';\n% RInv=inv(R);\n% \n% zTrue=[30e3;60*(pi/180);3*(pi/180)];\n% systemType=0;\n% useHalfRange=true;\n% xTrue=spher2Cart(zTrue,systemType,useHalfRange);\n% \n% NEESWithHess=0;\n% NEESWithoutHess=0;\n% for k=1:numMCRuns\n% zMeas=zeros(3,numMeas);\n% for curMeas=1:numMeas\n% zMeas(:,curMeas)=zTrue+SR*randn(3,1);\n% end\n% xAvg=mean(spher2Cart(zMeas,systemType,useHalfRange),2);\n% \n% h=Cart2Sphere(xAvg,systemType,useHalfRange);\n% JacobMat=calcSpherJacob(xAvg,systemType,useHalfRange);\n% HessMat=calcSpherHessian(xAvg,systemType,useHalfRange);\n% \n% FIMWithHess=observedFisherInfo(zMeas,RInv,h,JacobMat,HessMat);\n% FIMWithoutHess=numMeas*observedFisherInfo([],RInv,[],JacobMat,HessMat);\n% diff=xAvg-xTrue;\n% NEESWithHess=NEESWithHess+diff'*FIMWithHess*diff;\n% NEESWithoutHess=NEESWithoutHess+diff'*FIMWithoutHess*diff;\n% end\n% NEESWithHess=NEESWithHess/(3*numMCRuns)\n% NEESWithoutHess=NEESWithoutHess/(3*numMCRuns)\n%\n%EXAMPLE 2:\n%In this instance, we used the observed Fisher information as a covariance\n%matrix of a single spherical measurement in the absence of knowing the\n%truth. Thus, we just take h(z)=z and can omit the matrix of second\n%derivatives. Evaluating the NEES, one sees it is consistent (near 1, maybe\n%like 0.99 or 1.001). Of course, at higher angular noise levels, a debiased\n%function like spher2CartTaylor can perform better.\n% numMCRuns=10000;\n% sigmaR=10;\n% sigmaAz=0.1*(pi/180);\n% sigmaEl=0.1*(pi/180);\n% SR=diag([sigmaR;sigmaAz;sigmaEl]);\n% R=SR*SR';\n% RInv=inv(R);\n% \n% zTrue=[1e3;60*(pi/180);3*(pi/180)];\n% systemType=0;\n% useHalfRange=true;\n% xTrue=spher2Cart(zTrue,systemType,useHalfRange);\n% \n% NEES=0;\n% for k=1:numMCRuns\n% zMeas=zTrue+SR*randn(3,1);\n% xConv=spher2Cart(zMeas,systemType,useHalfRange);\n% JacobMat=calcSpherJacob(xConv,systemType,useHalfRange);\n% \n% invCRLB=observedFisherInfo([],RInv,[],JacobMat);\n% \n% diff=xConv-xTrue;\n% NEES=NEES+diff'*invCRLB*diff;\n% end\n% NEES=NEES/(3*numMCRuns)\n%\n%REFERENCES:\n%[1] Y. Bar-Shalom, X. R. Li, and T. Kirubarajan, Estimation with\n% Applications to Tracking and Navigation: Theory, Algorithms and\n% Software. New York: John Wiley and Sons, 2001.\n%[2] B. Efron and D. Hinkley, \"Assessing the accuracy of the maximum\n% likelihood estimator: Observed versus expected Fisher information,\"\n% Department of Statistics, Stanford, University, Tech. Rep. 108, 8 Mar.\n% 1978.\n%\n%December 2020 David F.Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(~isempty(z))\n numZ=size(z,2);\n \n xDim=size(HessMat,1);\n zDim=size(HessMat,3);\n FIM=zeros(xDim,xDim);\n \n C=zeros(xDim,xDim);\n for curMeas=1:numZ\n if(size(RInv,3)>1)\n RInvCur=RInv(:,:,curMeas);\n else\n RInvCur=RInv; \n end\n FIM=FIM+JacobMat'*RInv*JacobMat;\n \n RhzVal=RInvCur*(h-z(:,curMeas));\n for k=1:xDim\n C(:,k)=reshape(HessMat(:,k,:),[xDim,zDim])*RhzVal;\n end\n FIM=FIM+C;\n end\nelse\n numMeas=size(RInv,3);\n xDim=size(JacobMat,2);\n FIM=zeros(xDim,xDim);\n for k=1:numMeas\n FIM=FIM+JacobMat'*RInv(:,:,k)*JacobMat;\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/Statistics/observedFisherInfo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145053, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.6839984298113527}} {"text": "function x = InvMeyerPartition(y, L, deg)\n% InvMeyerPartition: Inverse the scale partitioning\n% Usage:\n% y = MeyerPartition(xhat, L, deg);\n% Inputs: \n% y Vector of length 2*n; signal separated into disjoint scales \n% L Coarsest Scale\n% deg Degree of the polynomial\n% Outputs:\n% x Vector of length n\n% Description\n% Performs the inverse of MeyerPartition; i.e., reconstruct\n% an object from its different scale contributions.\n%\n% By Emmanuel candes, 2003-2004\n\n\n n = length(y)/2;\n\tJ = log2(n);\n\tx = zeros(1,n);\n\n% \n% Unfold Partition at Coarse Level.\n%\n [index, window] = CoarseMeyerWindow(L-1,deg);\n\tl_index = reverse(n/2 + 1 - index);\n\tr_index = n/2 + index;\n\tx(l_index) = y(1:2^L).* reverse(window);\n\tx(r_index) = y((2^L+1):2^(L+1)).* window; \n\t\n\t\n%\n% Loop to Unfold Partition for j = L - 1, ..., J - 3.\n%\n\tfor j = L-1:(J-3),\n\t dyadic_points = [2^j 2^(j+1)];\n\t [index, window] = DetailMeyerWindow(dyadic_points,deg); \n\t yy = y((2^(j+2)+1):(2^(j+3)));\n\t m = length(yy)/2;\n\t l_index = reverse(n/2 + 1 - index);\n\t x(l_index) = x(l_index) + yy(1:m).* reverse(window);\n\t r_index = n/2 + index;\n\t x(r_index) = x(r_index) + yy((m+1):(2*m)).* window; \t \n\tend\n\n%\n% Finest Subband (for j = J - 2).\n%\n \n j = J - 2;\n [index, window] = FineMeyerWindow(j,deg);\n\tyy = y((2^(j+2)+1):(2^(j+3)));\n\tm = length(yy)/2;\n\tl_index = reverse(n/2 + 1 - index);\n x(l_index) = x(l_index) + yy(1:m).* reverse(window);\n r_index = n/2 + index;\n\tx(r_index) = x(r_index) + yy((m+1):(2*m)).* window; \t \n\t\n\t\n\t\n\t", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/CurveLab-2.1.3/fdct_usfft_matlab/Windows/Meyer/InvMeyerPartition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236823, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6839984178417309}} {"text": "function value = alnorm ( x, upper )\n\n%*****************************************************************************80\n%\n%% ALNORM computes the cumulative density of the standard normal distribution.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 January 2008\n%\n% Author:\n%\n% Original FORTRAN77 version by David Hill\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% David Hill,\n% Algorithm AS 66:\n% The Normal Integral,\n% Applied Statistics,\n% Volume 22, Number 3, 1973, pages 424-427.\n%\n% Parameters:\n%\n% Input, real X, is one endpoint of the semi-infinite interval\n% over which the integration takes place.\n%\n% Input, logical UPPER, determines whether the upper or lower\n% interval is to be integrated:\n% 1 => integrate from X to + Infinity;\n% 0 => integrate from - Infinity to X.\n%\n% Output, real VALUE, the integral of the standard normal\n% distribution over the desired interval.\n%\n a1 = 5.75885480458; \n a2 = 2.62433121679; \n a3 = 5.92885724438; \n b1 = -29.8213557807; \n b2 = 48.6959930692; \n c1 = -0.000000038052; \n c2 = 0.000398064794; \n c3 = -0.151679116635; \n c4 = 4.8385912808; \n c5 = 0.742380924027; \n c6 = 3.99019417011;\n con = 1.28;\n d1 = 1.00000615302;\n d2 = 1.98615381364;\n d3 = 5.29330324926;\n d4 = -15.1508972451;\n d5 = 30.789933034;\n ltone = 7.0;\n p = 0.39894228044; \n q = 0.39990348504;\n r = 0.398942280385;\n utzero = 18.66;\n\n up = upper;\n z = x;\n\n if ( z < 0.0 )\n if ( up )\n up = 0;\n else\n up = 1;\n end\n z = - z;\n end\n\n if ( ltone < z & ( ( ~up ) | utzero < z ) )\n\n if ( up )\n value = 0.0;\n else\n value = 1.0;\n end\n\n return\n\n end\n\n y = 0.5 * z * z;\n\n if ( z <= con )\n\n value = 0.5 - z * ( p - q * y ...\n / ( y + a1 + b1 ...\n / ( y + a2 + b2 ...\n / ( y + a3 ))));\n\n else\n\n value = r * exp ( - y ) ...\n / ( z + c1 + d1 ...\n / ( z + c2 + d2 ...\n / ( z + c3 + d3 ...\n / ( z + c4 + d4 ...\n / ( z + c5 + d5 ...\n / ( z + c6 ))))));\n\n end\n\n if ( ~up )\n value = 1.0 - value;\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/asa310/alnorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.6839858871144541}} {"text": "function [Btu] = kJ2Btu(kJ)\n% Convert energy or work from kilojoules to British thermal units.\n% Chad A. Greene 2012\nBtu = kJ*0.94781707775;", "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/35258-unit-converters/unit_converters/kJ2Btu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.6839858807095938}} {"text": "function [V,nr,nre]=lcon2vert(A,b,Aeq,beq,TOL,checkbounds)\nimport iris.thirdParty.polytopes.*;\n%An extension of Michael Kleder's con2vert function, used for finding the \n%vertices of a bounded polyhedron in R^n, given its representation as a set\n%of linear constraints. This wrapper extends the capabilities of con2vert to\n%also handle cases where the polyhedron is not solid in R^n, i.e., where the\n%polyhedron is defined by both equality and inequality constraints.\n% \n%SYNTAX:\n%\n% [V,nr,nre]=lcon2vert(A,b,Aeq,beq,TOL)\n%\n%The rows of the N x n matrix V are a series of N vertices of the polyhedron\n%in R^n, defined by the linear constraints\n% \n% A*x <= b\n% Aeq*x = beq\n%\n%By default, Aeq=beq=[], implying no equality constraints. The output \"nr\"\n%lists non-redundant inequality constraints, and \"nre\" lists non-redundant \n%equality constraints.\n%\n%The optional TOL argument is a tolerance used for both rank-estimation and \n%for testing feasibility of the equality constraints. Default=1e-10. \n%The default can also be obtained by passing TOL=[];\n%\n%\n%EXAMPLE: \n%\n%The 3D region defined by x+y+z=1, x>=0, y>=0, z>=0\n%is described by the following constraint data.\n% \n%\n% A =\n% \n% 0.4082 -0.8165 0.4082\n% 0.4082 0.4082 -0.8165\n% -0.8165 0.4082 0.4082\n% \n% \n% b =\n% \n% 0.4082\n% 0.4082\n% 0.4082\n% \n% \n% Aeq =\n% \n% 0.5774 0.5774 0.5774\n% \n% \n% beq =\n% \n% 0.5774\n%\n%\n% >> V=lcon2vert(A,b,Aeq,beq)\n%\n% V =\n% \n% 1.0000 0.0000 0.0000\n% 0.0000 0.0000 1.0000\n% -0.0000 1.0000 0.0000\n%\n%\n\n\n\n\n %%initial argument parsing\n \n nre=[];\n nr=[];\n if nargin<5 || isempty(TOL), TOL=1e-10; end\n if nargin<6, checkbounds=true; end\n \n switch nargin \n \n case 0\n \n error 'At least 1 input argument required'\n \n\n case 1\n \n b=[]; Aeq=[]; beq=[]; \n \n \n case 2\n \n Aeq=[]; beq=[];\n \n case 3\n \n beq=[];\n error 'Since argument Aeq specified, beq must also be specified'\n \n end\n \n \n b=b(:); beq=beq(:);\n \n if xor(isempty(A), isempty(b)) \n error 'Since argument A specified, b must also be specified'\n end\n \n if xor(isempty(Aeq), isempty(beq)) \n error 'Since argument Aeq specified, beq must also be specified'\n end\n \n \n nn=max(size(A,2)*~isempty(A),size(Aeq,2)*~isempty(Aeq));\n \n if ~isempty(A) && ~isempty(Aeq) && ( size(A,2)~=nn || size(Aeq,2)~=nn)\n \n error 'A and Aeq must have the same number of columns if both non-empty'\n \n end\n \n \n inequalityConstrained=~isempty(A); \n equalityConstrained=~isempty(Aeq);\n\n [A,b]=rownormalize(A,b);\n [Aeq,beq]=rownormalize(Aeq,beq);\n \n if equalityConstrained && nargout>2\n \n \n [discard,nre]=lindep([Aeq,beq].',TOL); \n \n if ~isempty(nre) %reduce the equality constraints\n \n Aeq=Aeq(nre,:);\n beq=beq(nre);\n \n else \n equalityConstrained=false;\n end\n \n end\n \n\n \n %%Find 1 solution to equality constraints within tolerance\n \n \n if equalityConstrained\n \n \n Neq=null(Aeq); \n\n\n x0=pinv(Aeq)*beq;\n\n if norm(Aeq*x0-beq)>TOL*norm(beq), %infeasible\n\n nre=[]; nr=[]; %All constraints redundant for empty polytopes\n V=[]; \n return;\n \n elseif isempty(Neq)\n\n V=x0(:).'; \n nre=(1:nn).'; %Equality constraints determine everything. \n nr=[];%All inequality constraints are therefore redundant. \n return\n \n end\n \n rkAeq= nn - size(Neq,2);\n \n \n end \n \n %%\n if inequalityConstrained && equalityConstrained\n \n AAA=A*Neq;\n bbb=b-A*x0;\n \n elseif inequalityConstrained\n \n AAA=A;\n bbb=b;\n \n elseif equalityConstrained && ~inequalityConstrained\n \n error('Non-bounding constraints detected. (Consider box constraints on variables.)')\n \n \n end\n \n nnn=size(AAA,2);\n \n\n if nnn==1 %Special case\n \n idxu=sign(AAA)==1;\n idxl=sign(AAA)==-1;\n idx0=sign(AAA)==0;\n \n Q=bbb./AAA;\n U=Q; \n U(~idxu)=inf;\n L=Q;\n L(~idxl)=-inf;\n\n \n [ub,uloc]=min(U);\n [lb,lloc]=max(L);\n \n if ~all(bbb(idx0)>=0) || ub1\n nr=unique([lloc,uloc]); nr=nr(:);\n end\n \n \n else \n \n if nargout>1\n [Zt,nr]=con2vert(AAA,bbb,TOL,checkbounds);\n else\n Zt=con2vert(AAA,bbb,TOL,checkbounds); \n end\n \n end\n \n\n\n if equalityConstrained && ~isempty(Zt)\n \n V=bsxfun(@plus,Zt*Neq.',x0(:).'); \n \n else\n \n V=Zt;\n \n end\n \n if isempty(V),\n nr=[]; nre=[]; \n end\n \n\n function [V,nr] = con2vert(A,b,TOL,checkbounds)\n% CON2VERT - convert a convex set of constraint inequalities into the set\n% of vertices at the intersections of those inequalities;i.e.,\n% solve the \"vertex enumeration\" problem. Additionally,\n% identify redundant entries in the list of inequalities.\n% \n% V = con2vert(A,b)\n% [V,nr] = con2vert(A,b)\n% \n% Converts the polytope (convex polygon, polyhedron, etc.) defined by the\n% system of inequalities A*x <= b into a list of vertices V. Each ROW\n% of V is a vertex. For n variables:\n% A = m x n matrix, where m >= n (m constraints, n variables)\n% b = m x 1 vector (m constraints)\n% V = p x n matrix (p vertices, n variables)\n% nr = list of the rows in A which are NOT redundant constraints\n% \n% NOTES: (1) This program employs a primal-dual polytope method.\n% (2) In dimensions higher than 2, redundant vertices can\n% appear using this method. This program detects redundancies\n% at up to 6 digits of precision, then returns the\n% unique vertices.\n% (3) Non-bounding constraints give erroneous results; therefore,\n% the program detects non-bounding constraints and returns\n% an error. You may wish to implement large \"box\" constraints\n% on your variables if you need to induce bounding. For example,\n% if x is a person's height in feet, the box constraint\n% -1 <= x <= 1000 would be a reasonable choice to induce\n% boundedness, since no possible solution for x would be\n% prohibited by the bounding box.\n% (4) This program requires that the feasible region have some\n% finite extent in all dimensions. For example, the feasible\n% region cannot be a line segment in 2-D space, or a plane\n% in 3-D space.\n% (5) At least two dimensions are required.\n% (6) See companion function VERT2CON.\n% (7) ver 1.0: initial version, June 2005\n% (8) ver 1.1: enhanced redundancy checks, July 2005\n% (9) Written by Michael Kleder\n%\n%Modified by Matt Jacobson - March 30, 2011\n% \n import iris.thirdParty.polytopes.*;\n\n\n %%%3/4/2012 Improved boundedness test - unfortunately slower than Michael Kleder's\n if checkbounds\n \n [aa,bb,aaeq,bbeq]=vert2lcon(A,TOL);\n \n if any(bb<=0) || ~isempty(bbeq)\n error('Non-bounding constraints detected. (Consider box constraints on variables.)')\n end\n \n clear aa bb aaeq bbeq\n \n end\n \n dim=size(A,2);\n \n %%%Matt J initialization\n if strictinpoly(b,TOL) \n \n c=zeros(dim,1);\n \n else\n \n \n slackfun=@(c)b-A*c;\n\n %Initializer0\n c = pinv(A)*b; %02/17/2012 -replaced with pinv()\n s=slackfun(c);\n\n if ~approxinpoly(s,TOL) %Initializer1\n\n c=Initializer1(TOL,A,b,c);\n s=slackfun(c);\n\n end\n\n if ~approxinpoly(s,TOL) %Attempt refinement\n\n %disp 'It is unusually difficult to find an interior point of your polytope. This may take some time... '\n %disp ' ' \n\n c=Initializer2(TOL,A,b,c);\n %[c,fval]=Initializer1(TOL,A,b,c,10000);\n s=slackfun(c);\n\n\n end\n\n\n if ~approxinpoly(s,TOL)\n %error('Unable to locate a point near the interior of the feasible region.')\n V=[];\n nr=[];\n return\n end\n\n\n\n if ~strictinpoly(s,TOL) %Added 02/17/2012 to handle initializers too close to polytope surface\n\n %disp 'Recursing...'\n\n\n idx=( abs(s)<=max(s)*TOL );\n\n Amod=A; bmod=b; \n Amod(idx,:)=[]; \n bmod(idx)=[];\n\n Aeq=A(idx,:); %pick the nearest face to c\n beq=b(idx);\n\n\n faceVertices=lcon2vert(Amod,bmod,Aeq,beq,TOL,1);\n if isempty(faceVertices)\n disp 'Something''s wrong. Couldn''t find face vertices. Possibly polyhedron is unbounded.'\n keyboard\n end\n\n c=faceVertices(1,:).'; %Take any vertex - find local recession cone vector\n s=slackfun(c);\n\n idx=( abs(s)<=max(s)*TOL );\n\n Asub=A(idx,:); bsub=b(idx,:);\n\n [aa,bb,aaeq,bbeq]=vert2lcon(Asub);\n aa=[aa;aaeq;-aaeq];\n bb=[bb;bbeq;-bbeq];\n\n clear aaeq bbeq\n\n\n [bmin,idx]=min(bb);\n\n if bmin>=-TOL\n disp 'Something''s wrong. We should have found a recession vector (bb<0).'\n keyboard\n end \n\n\n\n Aeq2=null(aa(idx,:)).';\n beq2=Aeq2*c; %find intersection of polytope with line through facet centroid.\n\n linetips = lcon2vert(A,b,Aeq2,beq2,TOL,1);\n\n if size(linetips,1)<2\n disp 'Failed to identify line segment through interior.'\n disp 'Possibly {x: Aeq*x=beq} has weak intersection with interior({x: Ax<=b}).'\n keyboard\n end\n\n\n lineCentroid=mean(linetips);%Relies on boundedness\n\n clear aa bb\n\n c=lineCentroid(:);\n s=slackfun(c);\n\n\n end\n\n\n b = s;\n end\n %%%end Matt J initialization\n \n \n D=bsxfun(@rdivide,A,b); \n \n \n k = convhulln(D);\n nr = unique(k(:));\n \n \n \n G = zeros(size(k,1),dim);\n ee=ones(size(k,2),1);\n discard=false( 1, size(k,1) );\n \n for ix = 1:size(k,1) %02/17/2012 - modified\n \n F = D(k(ix,:),:);\n if lindep(F,TOL)4\n [c,fval]=fminsearch(@(x) max([thresh;A*x-b]), c,optimset('MaxIter',maxIter));\n else\n [c,fval]=fminsearch(@(x) max([thresh;A*x-b]), c); \n end\n \nreturn \n\n\nfunction c=Initializer2(TOL,A,b,c)\n %norm( (I-A*pinv(A))*(s-b) ) subj. to s>=0 \n \n \n \n maxIter=100000;\n \n [mm,nn]=size(A);\n \n \n \n \n Ap=pinv(A); \n Aaug=speye(mm)-A*Ap;\n Aaugt=Aaug.';\n\n \n M=Aaugt*Aaug;\n C=sum(abs(M),2);\n C(C<=0)=min(C(C>0));\n \n slack=b-A*c;\n slack(slack<0)=0;\n \n \n % relto=norm(b);\n % relto =relto + (relto==0); \n % \n % relres=norm(A*c-b)/relto;\n\n \n IterThresh=maxIter; \n s=slack; \n ii=0;\n %for ii=1:maxIter\n while ii<=2*maxIter %HARDCODE\n \n ii=ii+1; \n if ii>IterThresh, \n %warning 'This is taking a lot of iterations'\n IterThresh=IterThresh+maxIter;\n end \n \n s=s-Aaugt*(Aaug*(s-b))./C; \n s(s<0)=0;\n\n \n c=Ap*(b-s);\n %slack=b-A*c;\n %relres=norm(slack)/relto;\n %if all(0= tol*diagr(1), 1, 'last'); %rank estimation\n\n if nargout>1\n idx=sort(E(1:r));\n idx=idx(:);\n end\n \n \n if nargout>2\n Xsub=X(:,idx); \n end \n\n \n function [A,b]=rownormalize(A,b)\n %Modifies A,b data pair so that norm of rows of A is either 0 or 1\n \n if isempty(A), return; end\n \n normsA=sqrt(sum(A.^2,2));\n idx=normsA>0;\n A(idx,:)=bsxfun(@rdivide,A(idx,:),normsA(idx));\n b(idx)=b(idx)./normsA(idx); \n \n function tf=approxinpoly(s,TOL)\n \n \n smax=max(s);\n \n if smax<=0\n tf=false; return \n end\n \n tf=all(s>=-smax*TOL);\n \n function tf=strictinpoly(s,TOL)\n \n smax=max(s);\n \n if smax<=0\n tf=false; return \n end\n \n tf=all(s>=smax*TOL);\n \n \n \n \n \n \n \n \n \n \n ", "meta": {"author": "rdeits", "repo": "iris-distro", "sha": "ff624610a82a858862d55732136dbc2cc9ab16fc", "save_path": "github-repos/MATLAB/rdeits-iris-distro", "path": "github-repos/MATLAB/rdeits-iris-distro/iris-distro-ff624610a82a858862d55732136dbc2cc9ab16fc/src/matlab/+iris/+thirdParty/+polytopes/lcon2vert.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6839858752149505}} {"text": "function y = normalizeAngle360(u)\n% Normalize angle in degrees to [0 360]\ny = mod(u, 360);\nend\n\n", "meta": {"author": "TUMFTM", "repo": "mod_vehicle_dynamics_control", "sha": "48b12705b72740b0c1574b0da2eab66fe0c75127", "save_path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control", "path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control/mod_vehicle_dynamics_control-48b12705b72740b0c1574b0da2eab66fe0c75127/misc/src/normalizeAngle360.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6839858642256631}} {"text": "function [A]=patchArea(F,V)\n\n% function [A]=patchArea(F,V)\n% ------------------------------------------------------------------------\n% This simple function calculates the areas of the faces specified by F and\n% V. The output is a vector A containing size(F,1) elements. The face areas\n% are calculated via triangulation of the faces. If faces are already\n% triangular triangulation is skipped are area calculation is direction\n% performed. \n%\n%\n%\n% Kevin Mattheus Moerman\n%\n% 2011/04/12\n% 2021/09/13 Updated to use more efficient patchEdgeCrossProduct method\n% 2021/09/14 Renamed to patchArea\n%------------------------------------------------------------------------\n\n%%\n\nC=patchEdgeCrossProduct(F,V);\nA=sqrt(sum(C.^2,2));\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/patchArea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.6839858633154464}} {"text": "function jac = p07_jac ( option, nvar, x )\n\n%*****************************************************************************80\n%\n%% P07_JAC evaluates the jacobian for problem 7.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 September 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer OPTION, the option index.\n%\n% Input, integer NVAR, the number of variables.\n%\n% Input, real X(NVAR), the argument of the jacobian.\n%\n% Output, real JAC(NVAR-1,NVAR), the jacobian matrix evaluated\n% at X. The NVAR-th row is not set by this routine.\n%\n jac = zeros ( nvar, nvar );\n\n for i = 1 : nvar - 1\n jac(i,i) = 100.0 * ( 1.0 - x(i) * x(i) ) ...\n / ( 1.0 + x(i) + x(i) * x(i) )^2;\n end\n\n jac(1,1) = jac(1,1) + 2.0;\n jac(1,2) = jac(1,2) - 1.0;\n jac(1,nvar) = jac(1,nvar) - 1.0;\n\n for i = 2 : nvar-2\n jac(i,i-1) = jac(i,i-1) - 1.0;\n jac(i,i) = jac(i,i) + 3.0;\n jac(i,i+1) = jac(i,i+1) - 1.0;\n jac(i,nvar) = jac(i,nvar) - 1.0;\n end\n\n jac(nvar-1,nvar-2) = jac(nvar-1,nvar-2) - 1.0;\n jac(nvar-1,nvar-1) = jac(nvar-1,nvar-1) + 2.0;\n jac(nvar-1,nvar) = jac(nvar-1,nvar) - 1.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/test_con/p07_jac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6839858544611123}} {"text": "function [maxel,IJ]= max2(M,userows,usecols)\n% finds the location of the single overall maximum element in a 2-d array\n% usage: [maxel,IJ] = max2(M)\n% usage: [maxel,IJ] = max2(M,userows,usecols)\n%\n% The location in a 2-d array of the overall\n% maximum element (or the first incidence of\n% several, if the maximum is not unique), where\n% you may restrict the search to a set of\n% specified rows and/or columns.\n%\n% Note that max2 does NOT convert the matrix to\n% linear indexing, so that really huge arrays\n% can be worked with.\n%\n% arguments: (input)\n% M - an (nxm) 2-dimensional numeric array (or\n% vector) that max is able to operate on. M\n% may contain inf or -inf elements.\n%\n% userows - (OPTIONAL) a list of the rows to be\n% searched for the maximum. The search will\n% be restricted to this set of rows. If empty.\n% there will be no row restriction.\n%\n% userows must be a list of integers\n%\n% usecols - (OPTIONAL) a list of the columns to be\n% searched for the maximum. The search will\n% be restricted to this set of columnss. If\n% empty. there will be no column restriction.\n%\n% arguments: (output)\n% maxel - overall maximum element found. If the\n% maximum was ot unique, then this is the\n% first element identified. Ties will be\n% resolved in a way consistent with find.\n%\n% IJ - a (1x2) row vector, comtaining respectively\n% the row and column indices of the maximum as\n% found.\n%\n% Example:\n% M = magic(4)\n% ans =\n% 16 2 3 13\n% 5 11 10 8\n% 9 7 6 12\n% 4 14 15 1\n%\n% % the overall maximum\n% [maxel,IJ] = max2(M)\n% maxel =\n% 16\n% IJ =\n% 1 1\n%\n%\n% % a restricted maximum\n% [maxel,IJ] = max2(M,[1 2 3],[2 3])\n% maxel =\n% 11\n% IJ =\n% 2 2\n%\n%\n% See also: max2, max, min, find\n% \n%\n% Author: John D'Errico\n% e-mail: woodchips@rochester.rr.com\n% Release: 1.0\n% Release date: 2/16/09\n\n% check the arguments\nif (nargin<1) || (nargin>3)\n error('max2 may have 1, 2, or 3 arguments only')\nend\n\nif length(size(M)) > 2\n error('M must be a 2-d array or a vector')\nend\n[n,m] = size(M);\n\n% default for userows?\nif (nargin<2) || isempty(userows)\n userows = 1:n;\nelse\n userows = unique(userows);\n if ~isnumeric(userows) || any(diff(userows)==0) || ...\n any(userows<1) || any(userows>n) || any(userows~=round(userows))\n error('userows must be a valid set of indices into the rows of M')\n end\nend\n\n% default for usecols?\nif (nargin<3) || isempty(usecols)\n usecols = 1:m;\nelse\n usecols = unique(usecols);\n if ~isnumeric(usecols) || any(diff(usecols)==0) || ...\n any(usecols<1) || any(usecols>m) || any(usecols~=round(usecols))\n error('usecols must be a valid set of indices into the columns of M')\n end\nend\n\n% restrict the search\nMuse = M(userows,usecols);\n\n% The maximum down the rows\n[maxrows,rowind] = max(Muse,[],1);\n\n% find the best of these maxima\n% across the columns\n[maxel,colind] = max(maxrows,[],2);\nrowind = rowind(colind);\n\n% package the row and column indices\n% together, in terms of the original\n% matrix in case there was a restiction.\nIJ = [userows(rowind),usecols(colind)];\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/22995-min2-max2/MIN2_MAX2/max2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.6839591865235986}} {"text": "%% -------------\nfunction s = ComputeSaliency(img, sigma, alpha)\n \n % --------- Check the input --------\n if (1 ~= size(img, 3)),\n error('The input image should be GRAY.');\n end\n \n [dx, dy] = GradientMethod(double(img), 'zhou'); \n grad = dx +1j*dy;\n \n [~, cc] = EigDecBlock(grad, sigma);\n wt = sqrt((sqrt(cc(1,:,:))+sqrt(cc(2,:,:))).^2 + alpha*(sqrt(cc(1,:,:))-sqrt(cc(2,:,:))).^2);\n s = squeeze(wt);\nend\n\n\n\n%% ------------------------------------------------\n% [c11, c12 [dxx, dxy\n% c21, c22] = dyx, dyy]\n% B = -(c11+c22), C = c11*c22-c12*c21\nfunction [postMap, ss] = EigDecBlock(img, sigma)\n\n winSize = ceil(sigma*6);\n if ~mod(winSize, 2),\n winSize = winSize + 1;\n end\n \n h = fspecial('gauss', [winSize winSize], sigma);\n [hh, ww] = size(img); \n ss = zeros(2, hh, ww);\n\n dx = real(img);\n dy = imag(img);\n dxx = imfilter(dx.*dx, h, 'symmetric');\n dxy = imfilter(dx.*dy, h, 'symmetric');\n dyy = imfilter(dy.*dy, h, 'symmetric');\n \n A = ones(size(img));\n B = -(dxx+dyy);\n C = dxx.*dyy - dxy.*dxy;\n \n ss(1, :, :) = abs((-B+sqrt(B.^2-4*A.*C))./(2*A));\n ss(2, :, :) = abs((-B-sqrt(B.^2-4*A.*C))./(2*A));\n \n V12 = (dxx-dyy + sqrt((dxx-dyy).^2+4*dxy.*dxy))./(2*dxy+eps);\n \n postMap = sqrt(squeeze(ss(1, :, :))).*(V12 + 1i)./sqrt(V12.^2+1+eps);\n \nend\n\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/MWGF_Image_Fusion_Codes/ComputeSaliency.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.683945294520118}} {"text": "function varargout = svd( A, b )\n%\n% [U, S, V] = svd(A);\n% [U, S, V] = svd(A, b);\n%\n% Overloaded SVD method for psfMatrix objects.\n%\n% Input: \n% A is a psfMatrix\n%\n% Optional Input:\n% b is a blurred image. Since A often uses a compact storage\n% scheme, this is sometimes needed to determine \"real size\" \n% of the matrix.\n%\n% Output:\n% This depends on the type of blur, and boundary conditions.\n% * If A.boundary = 'periodic', then U and V are\n% transformMatrix objects, with U.transform V.transform = 'fft'\n% S is a column vector containing the eigenvalues of A.\n% * If A.boundary = 'reflexive', and A is symmetric, then\n% U and V are transformMatrix objects, with\n% U.transform = V.transform = 'dct'\n% S is a column vector containing the eigenvalues of A.\n% * In all other cases, a Kronecker product approximation of\n% A is first computed, and U and V are then kronMatrix objects.\n% S is a column vector containing the singular values of A\n% (they are not sorted, though).\n%\n\n% J. Nagy 6/2/02\n% Modifications:\n% 7/7/03 - J. Nagy, now allows to use a preliminary version\n% of space variant SVD approximations.\n% 22/03/07 - J. Nagy, this tries FFT, DCT and Kronecker product\n% SVD bases to find which approximation\n% is best.\n\nswitch A.type\n case 'invariant'\n P = A.psf;\n P1 = P.image;, c = P.center;\n PSF = P1{1};, center = c{1};\n\n if (nargin == 2)\n PSF = padarray(PSF, size(b) - size(PSF), 'post');\n else\n b = PSF; % This is used to define correct dimensions only.\n end\n \n switch A.boundary\n case 'periodic'\n [U, S, V] = fft_svd(PSF, center);\n case 'reflexive'\n if issymmetric(A)\n [U, S, V] = dct_svd(PSF, center);\n else\n [U, S, V] = svd_approx( kronApprox(A, b) );\n end\n case 'zero'\n [U, S, V] = svd_approx( kronApprox(A, b) );\n otherwise\n error('Invalid boundary condition')\n end\n \n case 'variant'\n [U, S, V] = svd_approx( kronApprox(A, b) );\n \n otherwise\n error('invalid matrix type')\nend\n\nif nargout == 1\n varargout{1} = S;\nelseif nargout == 3\n varargout{1} = U;\n varargout{2} = S;\n varargout{3} = V;\nelse\n error('In correct number of output variables')\nend\n\n", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/Extra/prblur_tools/@psfMatrix/svd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.683945294520118}} {"text": "function [pb,theta] = pbTG(im,radius,norient)\n% function [pb,theta] = pbTG(im,radius,norient)\n%\n% Compute probability of boundary using TG.\n%\n% David R. Martin \n% April 2003\n\nif nargin<2, radius=0.02; end\nif nargin<3, norient=8; end\n\n% beta from logistic fits (trainTG.m)\nif radius==0.02, % 64 textons\n beta = [ -4.7151584e+00 1.2222425e+00 ];\n fstd = [ 1.0000000e+00 1.9171689e-01 ];\n beta = beta ./ fstd;\nelse\n error(sprintf('no parameters for radius=%g\\n',radius));\nend\n\n% get gradients\n[tg,gtheta] = detTG(im,radius,norient);\n\n% compute oriented pb\n[h,w,unused] = size(im);\npball = zeros(h,w,norient);\nfor i = 1:norient,\n t = tg(:,:,i); t = t(:);\n x = [ones(size(t)) t];\n pbi = 1 ./ (1 + (exp(-x*beta')));\n pball(:,:,i) = reshape(pbi,[h w]);\nend\n\n% nonmax suppression and max over orientations\n[unused,maxo] = max(pball,[],3);\npb = zeros(h,w);\ntheta = zeros(h,w);\nr = 2.5;\nfor i = 1:norient,\n mask = (maxo == i);\n a = fitparab(pball(:,:,i),r,r,gtheta(i));\n pbi = nonmax(max(0,a),gtheta(i));\n pb = max(pb,pbi.*mask);\n theta = theta.*~mask + gtheta(i).*mask;\nend\npb = max(0,min(1,pb));\n\n% mask out 1-pixel border where nonmax suppression fails\npb(1,:) = 0;\npb(end,:) = 0;\npb(:,1) = 0;\npb(:,end) = 0;\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/external/segbench/lib/matlab/pbTG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6839452845289048}} {"text": "% Fig. 9.33 Feedback Control of Dynamic Systems, 6e \n% Franklin, Powell, Emami\n%\n\nclear all;\nclose all;\n%saturation nonlinearity (Figure 9.33)\n\nN=0.1;\nk= 1;\nn=10\nj=1;\nfor i=0.1:0.01:n\n Keq(j) = (2/pi)*(k*asin(N/(k*i))+(N/i)*sqrt(1-(N/(k*i))^2));\n j=j+1;\nend;\nplot([0,0.1:0.01:n],[1 Keq]);\naxis([0 10 0 1.1]) \ntitle('Describing function for saturation nonlinearity')\nxlabel('a')\nylabel('K_{eq}');\nnicegrid;\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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig9_33.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6839172706810471}} {"text": "function x = isnr(ref, sig, obs)\n% \n% snr -- Compute Improvement Signal-to-Noise Ratio for images\n%\n% Usage:\n% x = isnr(ref, sig, obs)\n%\n% Input:\n% ref Reference image\n% sig Modified image\n% obs Observed image\n% \n% Output:\n% x SNR value\n% \n% Authors\n% Paul Rodriguez prodrig@pucp.edu.pe\n% Brendt Wohlberg brendt@tmail.lanl.gov\n% \n\nmse1 = mean((ref(:)-sig(:)).^2);\nmse2 = mean((obs(:)-sig(:)).^2);\nx = 10*log10(mse2/mse1);\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/GTF/source/isnr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6839172575779892}} {"text": "function psnr = calc_psnr(V, W, H)\n\n % PSNR = 10 log10 (MAX^2/MSE)\n %\n % MAX_VAL: Maximum value of pixels\n \n max_val = max(max(V));\n mse = calc_mse(V, W, H);\n psnr = 10 * log10 (max_val.^2/mse); \n \nend\n", "meta": {"author": "hiroyuki-kasai", "repo": "NMFLibrary", "sha": "ed44132dfe1b5495df685006b42259f0bd16bea3", "save_path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary/NMFLibrary-ed44132dfe1b5495df685006b42259f0bd16bea3/auxiliary/calc_psnr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6839172526994934}} {"text": "function [l1, l2, l3]=dtiEigenvaluesFromWestinShapes(cl, cp, vol, method)\n%V is the volume of original tensor\n%solution\n%Method specifies whether the Westin shapes aligned are computed with\n%simple (\"new\") denominator, l1, or original definition (old) denominator,\n%l1+l2+l3\nif ~exist('method', 'var')\n method='westinShapes_l1';\nend\n\n\nswitch method\n case 'westinShapes_l1'\n%westin shapes are new(simplified) versions, NOT the ones computed by dtiComputeWestinShapes: \n%cl=(l1-l2)/l1; \n%cp=(l2-l3)/l1;\n%cs=l3/l1;\n\nl1_sol(:, 1)=-((-3/pi).^(1/3).*vol.^(1/3))./(2^(2/3).*((-1+cl).*(-1+cl+cp)).^(1/3)); \nl3_sol(:, 1)=(-1+cl+cp).*l1_sol(:, 1); \nl1_sol(:, 2)=(3/pi)^(1/3)./(2^(2/3).*(((-1+cl).*(-1+cl+cp))./vol).^(1/3));\nl3_sol(:, 2)=-(-1+cl+cp).*l1_sol(:, 2); \nl1_sol(:, 3)=-((-1)^(2/3).*(3/pi)^(1/3))./(2^(2/3).*(((-1+cl).*(-1+cl+cp))./vol).^(1/3));\nl3_sol(:, 3)=(-1+cl+cp).*l1_sol(:, 3); \n\n case 'westinShapes_lsum'\n%westin shapes as those computed by dtiComputeWestinShapes: \n%cl=(l1-l2)/(l1+l2+l3); \n%cp=(l2-l3)/(l1+l2+l3);\n%cs=l3/(l1+l2+l3);\n\n%I am not sure whether the results produced by this method make sence -- at\n%least when protted in barycentric coordinates. If you want to use it,\n%check the code.\n\nl1_sol(:, 1)=-((3/pi).^(1/3).*(-(2+4*cl+cp).^2.*vol).^(1/3))./(2*((-2+2*cl-cp).*(-1+cl+cp)).^(1/3));\nl3_sol(:, 1)=-2*l1_sol(1).*(-1+cl+cp)./(2+4*cl+cp);\nl1_sol(:, 2)=((3/pi).^(1/3))./(2*(((-2+2*cl-cp).*(-1+cl+cp))./((2+4*cl+cp).^2.*vol)).^(1/3));\nl3_sol(:, 2)=-2*l1_sol(2).*(-1+cl+cp)./(2+4*cl+cp);\nl1_sol(:, 3)=((-1).^(2/3).*(3/pi).^(1/3))./(2*(((-2+2*cl-cp).*(-1+cl+cp))./((2+4*cl+cp).^2.*vol)).^(1/3));\nl3_sol(:, 3)=-2*l1_sol(3).*(-1+cl+cp)./(2+4*cl+cp);\n\n otherwise\n fprintf('Enter either \"westinShapes_lsum\" or \"westinShapes_l1\" for method'); return;\nend\n\n%The three solutions are only different in that some of them are not real! The second one is usually good enough. \nsolN=1;\n\nwhile(~isreal(l1_sol(:, solN)) || ~isreal(l3_sol(:, solN)))\nsolN=solN+1;\nend\nl1=l1_sol(:, solN); \nl3=l3_sol(:, solN); \nl2=vol./(l1.*l3.*4.*pi./3);\nl2(isnan(l2))=0;\n\nend\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/tensor/dtiEigenvaluesFromWestinShapes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6838048243806312}} {"text": "x=@(alpha,beta) 4*cos(alpha);\ny=@(alpha,beta) (5+4*sin(alpha)).*cos(beta);\nz=@(alpha,beta) (5+4*sin(alpha)).*sin(beta);\nezsurf(x,y,z)\n", "meta": {"author": "Eurus-Holmes", "repo": "Mathematical_Modeling", "sha": "cb9dd53af84ffbd455ec62ab89886351e0ec98d9", "save_path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling", "path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling/Mathematical_Modeling-cb9dd53af84ffbd455ec62ab89886351e0ec98d9/Mathematical_Modeling_Algorithms_and_Applications_Second_Edition_Procedures_and_Data/17\u9644\u5f55A/exA_8_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6838048229839074}} {"text": "function [Az, El, D] = topocent(XR, XS)\n\n% SYNTAX:\n% [Az, El, D] = topocent(XR, XS);\n%\n% INPUT:\n% XR = receiver coordinates (X,Y,Z)\n% XS = satellite coordinates (X,Y,Z)\n%\n% OUTPUT:\n% D = rover-satellite distance\n% Az = satellite azimuth\n% El = satellite elevation\n%\n% DESCRIPTION:\n% Computation of satellite distance, azimuth and elevation with respect to\n% the receiver.\n\n%--- * --. --- --. .--. ... * ---------------------------------------------\n% ___ ___ ___\n% __ _ ___ / __| _ | __|\n% / _` / _ \\ (_ | _|__ \\\n% \\__, \\___/\\___|_| |___/\n% |___/ v 1.0RC1\n%\n%--------------------------------------------------------------------------\n% Copyright (C) Kai Borre\n% Written by: Kai Borre\n% Contributors: Kai Borre 09-26-97\n% Mirko Reguzzoni, Eugenio Realini, 2009\n% A list of all the historical goGPS contributors is in CREDITS.nfo\n%--------------------------------------------------------------------------\n%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\n%conversion from geocentric cartesian to geodetic coordinates\n[phi, lam] = cart2geod(XR(1), XR(2), XR(3));\n\n%new origin of the reference system\nX0(:,1) = XR(1) * ones(size(XS,1),1);\nX0(:,2) = XR(2) * ones(size(XS,1),1);\nX0(:,3) = XR(3) * ones(size(XS,1),1);\n\n%computation of topocentric coordinates\ncl = cos(lam); sl = sin(lam);\ncb = cos(phi); sb = sin(phi);\nF = [-sl -sb*cl cb*cl;\n cl -sb*sl cb*sl;\n 0 cb sb];\nlocal_vector = F' * (XS-X0)';\nE = local_vector(1,:)';\nN = local_vector(2,:)';\nU = local_vector(3,:)';\nhor_dis = sqrt(E.^2 + N.^2);\n\nif hor_dis < 1.e-20\n %azimuth computation\n Az = 0;\n %elevation computation\n El = 90;\nelse\n %azimuth computation\n Az = atan2(E,N)/pi*180;\n %elevation computation\n El = atan2(U,hor_dis)/pi*180;\nend\n\ni = find(Az < 0);\nAz(i) = Az(i)+360;\n\n%receiver-satellite distance, corrected by the Shapiro delay\n[~, D] = relativistic_range_error_correction(XR, XS);\n\n%receiver-satellite distance\n% D = sqrt(sum((XS-X0).^2 ,2));\n", "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/positioning/topocent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625145783428, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6838048151091373}} {"text": "function [D,rho,dD,drho,d2Phi] = MI(Rc,Tc,Omega,m,varargin)\nh = Omega./m;\nhd = prod(h);\nPARA = varargin{1};\ndoDerivative = (nargout > 3);\n\n% D = phi(rho(y))\n% dD = dPhi(res(y)) * dRes(y)\n% d2D = res(y)' * d2Phi(res(y)) * dRes(y) + stuff we don't consider\n \n% example MI:\n% phi = res' * log(res + tol) + ...\n% dPhi = log(res + tol) + res./(res + tol) + ...\n% d2Phi = (res + 2*tol)./(res + tol)^2 + ...\n% res = rho(T,R)\n% dRes = drho, see pdfestimate\n\ntol = PARA.entropyTol;\n[rho,drho] = pdfestimate(Rc,Tc,PARA,doDerivative);\n[n1,n2] = size(rho);\n \nrhoR = sum(rho,2);\nrhoT = sum(rho,1)';\nrho = rho(:);\n \nD = rhoR'*log(rhoR+tol)+rhoT'*log(rhoT+tol) - rho'*log(rho+tol);\n \nif ~doDerivative, return; end;\n\nSR = sparse(kron(ones(1,n2),speye(n1,n1)));\nST = sparse(kron(speye(n2,n2),ones(1,n1)));\n \ndPhi = ...\n (log(rhoR+tol)+rhoR./(rhoR+tol))'*SR ...\n +(log(rhoT+tol)+rhoT./(rhoT+tol))'*ST ...\n -(log(rho +tol)+rho ./(rho +tol))';\n \ndD = dPhi * drho;\n \nd2Phi = ...\n SR'*sdiag((rhoR + 2*tol)./(rhoR+tol).^2)*SR ...\n +ST'*sdiag((rhoT + 2*tol)./(rhoT+tol).^2)*ST ...\n -sdiag((rho + 2*tol)./(rho+tol).^2);\n \na = 1/sqrt(PARA.ngvR*PARA.ngvT);\na = 1e0;\nd2Phi = - a * d2Phi;\n \nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/RetinotopyModelFit/Version10/distance/MI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6838048107504427}} {"text": "function M1 = spm_eeg_inv_headcoordinates(nas, lpa, rpa)\n% Returns the homogenous coordinate transformation matrix\n% that converts the specified fiducials in any coordinate system (e.g. MRI)\n% into the rotated and translated headccordinate system.\n%\n% M1 = headcoordinates(nas, lpa, rpa)\n%\n% The headcoordinate system in CTF is defined as follows:\n% the origin is exactly between lpa and rpa\n% the X-axis goes towards nas\n% the Y-axis goes approximately towards lpa, orthogonal to X and in the plane spanned by the fiducials\n% the Z-axis goes approximately towards the vertex, orthogonal to X and Y\n%_______________________________________________________________________\n% Copyright (C) 2003 Robert Oostenveld\n\n% Robert Oostenveld\n% $Id: spm_eeg_inv_headcoordinates.m 3589 2009-11-20 17:17:41Z guillaume $\n\n% ensure that they are row vectors\nlpa = lpa(:)';\nrpa = rpa(:)';\nnas = nas(:)';\n\n% compute the origin and direction of the coordinate axes in MRI coordinates\n\n% follow CTF convention\norigin = [lpa+rpa]/2;\ndirx = nas-origin;\ndirx = dirx/norm(dirx);\ndirz = cross(dirx,lpa-rpa);\ndirz = dirz/norm(dirz);\ndiry = cross(dirz,dirx);\n\n% compute the rotation matrix\nrot = eye(4);\nrot(1:3,1:3) = inv(eye(3) / [dirx; diry; dirz]);\n% compute the translation matrix\ntra = eye(4);\ntra(1:4,4) = [-origin(:); 1];\n% compute the full homogenous transformation matrix from these two\nM1 = rot * tra;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_eeg_inv_headcoordinates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6838048096907665}} {"text": "function [S] = L1QP_FeatureSign_Set(X, B, Sigma, beta, gamma)\n\n[dFea, nSmp] = size(X);\nnBases = size(B, 2);\n\n% sparse codes of the features\nS = sparse(nBases, nSmp);\n\nA = B'*B + 2*beta*Sigma;\n\nfor ii = 1:nSmp,\n b = -B'*X(:, ii);\n% [net] = L1QP_FeatureSign(gamma, A, b);\n S(:, ii) = L1QP_FeatureSign_yang(gamma, A, b);\nend", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/ScSR/RegularizedSC/L1QP_FeatureSign_Set.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6838048068973196}} {"text": "function [w,mu,P]=EMAlgGaussClust(z,w,mu,P,numIter)\n%%EMALGGAUSSCLUST Use the expectation maximization (EM) algorithm to\n% refine estimates of the components of a Gaussian mixture\n% with a known number of terms given a set of samples.\n%\n%INPUTS: z A zDim X numPoints set of samples of the Gaussian mixture.\n% w A KX1 set of initial weight estimates of the K Gaussians in the\n% mixture.\n% mu A zDim X K set of initial mean estimates of the component\n% Gaussians in the mixture.\n% P A zDim X zDim X K hypermatrix of initial covariance matrix\n% estimates of the components of the Gaussians in the mixture.\n% numIter The number of iterations of the EM algorithm to perform.\n%\n%OUTPUTS: w The refined weights.\n% mu The refined means.\n% P The refined covariance matrix estimates.\n%\n%The EM algorithm for Gaussian mixtures is an implementation of the\n%algorithm described in Chapter 9.2.2 of [1].\n%\n%REFERENCES:\n%[1] C. M. Bishop, Pattern Recognition and Machine Learning. Cambridge,\n% United Kingdom: Springer, 2007.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n %zDim=size(z,1);\n numPoints=size(z,2);\n K=size(mu,2);\n\n gamma=zeros(numPoints,K);\n for curIter=1:numIter\n %Calculate the posterior weights.\n for k=1:K\n gamma(:,k)=GaussianPDF(z,mu(:,k),P(:,:,k))*w(k);\n end\n %Normalize the weights for each measurement.\n gamma=bsxfun(@rdivide,gamma,sum(gamma,2));\n\n %Update the means, covariances and weights using the posterior\n %weights.\n for k=1:K\n Nk=sum(gamma(:,k));\n w(k)=Nk/numPoints;\n \n [mu(:,k), P(:,:,k)]=calcMixtureMoments(z,gamma(:,k)/Nk);\n end\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/Clustering_and_Mixture_Reduction/EMAlgGaussClust.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225574, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.6837211196219464}} {"text": "function varargout = solveTSP( cities, display)\n% cities = solveTSP( cities, maxItt, display)\n%\n% cities - An Nx2 matrix containing cartesian coordinates of the \"cities\"\n% beeing visited. The initial trail is assumed from the first city to the\n% scond and so on...\n% \n% display - bolean flag decide if to display the progress of the program (slows the running time). \n% default = false;\n% \n% maxIteration - maximum iterations for the program\n% default = 10,000\n% \n% \n% [cities ind] = solveTSP( cities, display) returns the aranged cities and\n% an index vector of the visiting order \n% \n% [cities ind totalDist] = solveTSP( cities, display)\n% totalDist is the route total distance\n%\n% demo1:\n% cities = solveTSP( rand(100,2), true );\n%\n% demo2:\n% t = (0:999)' /1000;\n% cities = [ t.^2.*cos( t*30 ) t.^2.*sin( t*30 ) ];\n% [ans ind] = sort( rand(1000,1) );\n% [cities ind] = solveTSP( cities(ind,:), true );\n\n if nargin < 2\n display = false;\n end\n \n siz = size(cities);\n if siz(2) ~= 2\n error( 'The program is expecting cities to be an Nx2 matix of cartesian coordinates' );\n end\n N = siz(1);\n \n order = (1:N)'; % initial cities visit order\n\n if display\n hFig = figure;\n hAx = gca;\n updateRate = ceil( N/50 );\n end\n\n itt = 1;\n maxItt = min(20*N,1e5);\n noChange = 0;\n \n while itt < maxItt && noChange < N\n\n dist = calcDistVec( cities(order,:),1 ); % travel distance between the cities\n \n %% ----------- Displaying current route -----------------------\n if display && ~mod(itt,updateRate) && ishandle( hFig ) \n hold(hAx,'off');\n plot( hAx, cities( order,1),cities( order,2),'r.' );\n hold( hAx,'on');\n plot( hAx, cities( order,1),cities( order,2) );\n str = {[ 'iteration: ' num2str( itt ) ] ;\n [ 'total route: ' num2str( sum( dist) ) ] };\n title( hAx,str );\n pause(0.02)\n end\n\n flip = mod( itt-1, N-3 )+2 ;\n\n untie = dist(1:end-flip) + dist(flip+1:end); % the distance saved by untying a loop\n shufledDist = calcDistVec( cities( order,:),flip ); \n connect = shufledDist(1:end-1) + shufledDist( 2:end); % the distance payed by connecting the loop (after flip) \n benifit = connect - untie; % \"what's the distance benifit from this loop fliping\n \n %% --------------- Finding the optimal flips (most benficial) ---------------- \n localMin = imerode(benifit,ones(2*flip+1,1) );\n minimasInd = find( localMin == benifit);\n reqFlips = minimasInd( benifit(minimasInd) < -eps );\n\n %% -------- fliping all loops found worth fliping --------------------\n prevOrd = order; \n for n=1:numel( reqFlips )\n order( reqFlips(n) : reqFlips(n)+flip-1 ) = order( reqFlips(n) +flip-1: -1 :reqFlips(n) );\n end\n \n %% ------- counting how many iterations there was no improvement\n if isequal( order,prevOrd )\n noChange = noChange + 1;\n else\n noChange = 0;\n end\n \n itt = itt+1;\n \n end % while itt < maxItt && noChange < N\n \n output = {cities( order,:), order, sum( dist)};\n varargout = output(1:nargout);\n \nfunction dist = calcDistVec( cord,offset )\n% dist = calcDistVec( cord,offset )\n% offset is the number of cities to calculate the distence between\n% the distance for the first city is allway 0\n \n dist = zeros( size(cord,1)-offset+1,1 ); \n temp = cord( 1:end-offset,:) - cord( offset+1:end,:);\n dist(2:end) = sqrt( sum(temp.^2,2) );", "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/24857-another-tsp-solver/solveTSP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.870597268408361, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6836875141274079}} {"text": "function[kappa,lambda,theta,phi,alpha,beta]=ellparams(varargin)\n%ELLPARAMS Ellipse parameters of a modulated bivariate or trivariate oscillation.\n%\n% [KAPPA,LAMBDA,THETA,PHI]=ELLPARAMS(X,Y) where X and Y are analytic \n% signals, returns the parameters of the complex-valued signal \n% Z=REAL(X)+i REAL(Y), expressed as a modulated ellipse.\n%\n% Here KAPPA is the RMS ellipse amplitude, LAMBDA is the linearity, \n% THETA is the orientation, and PHI is the instantaneous orbital phase.\n%\n% ELLPARAMS(M), where M is matrix with two columns, also works.\n%\n% See Lilly and Gascard (2006) and Lilly and Olhede (2010a) for details.\n%\n% ELLPARAMS is inverted by ELLSIG, which returns the X and Y signals \n% given the ellipse parameters.\n%\n% ELLPARAMS(...,DIM) performs the analysis with time running along\n% dimension DIM, as opposed to the default behavior of DIM=1. \n%\n% ELLPARAMS also works if X and Y are cell arrays with each cell holding\n% a different analytic signal. The output will then also be cell arrays. \n% _______________________________________________________________________\n%\n% Trivariate signals\n%\n% ELLPARAMS also works for trivariate signals, which can be expressed as\n% a modulated ellipse in three dimensions.\n%\n% [KAPPA,LAMBDA,THETA,PHI,ALPHA,BETA]=ELLPARAMS(X,Y,Z), where X, Y, and Z\n% are all analytic signals, also returns the zenith angle ALPHA and the \n% azimuth angle BETA in addition to the other ellipse parameters.\n%\n% ELLPARAMS(M), where M is matrix with three columns, also works.\n%\n% See Lilly (2010) for details on the trivariate case.\n% __________________________________________________________________\n%\n% 'ellparams --t' runs a test.\n%\n% See also ELLSIG, ELLBAND, ELLDIFF, ELLVEL, ELLRAD, KL2AB, AB2KL. \n%\n% Usage: [kappa,lambda,theta,phi]=ellparams(x,y);\n% [kappa,lambda,theta,phi]=ellparams(x,y,dim);\n% [kappa,lambda,theta,phi,alpha,beta]=ellparams(x,y,z);\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2009--2018 J.M. Lilly --- type 'help jlab_license' for details\n\nif strcmpi(varargin{1}, '--t')\n ellparams_test,normvect_test,return\nend\n\n[na,k,l,theta,phi,alpha,beta]=vempty;\n\nif ~iscell(varargin{end})&&length(varargin{end})==1\n dim=varargin{end};\n varargin=varargin(1:end-1);\nelse\n dim=1;\nend\n\n[z,kappa,lambda,theta,phi,alpha,beta]=vempty;\nif ~isempty(varargin{1})\n if ~iscell(varargin{1})\n x=varargin{1};\n y=varargin{2};\n if length(varargin)==3\n z=varargin{3};\n end\n [kappa,lambda,theta,phi,alpha,beta]=ellparams_one(x,y,z,dim);\n else\n x=varargin{1};\n y=varargin{2};\n for i=1:length(x)\n if ~isempty(x{i})\n if length(varargin)==2\n [kappa{i,1},lambda{i,1},theta{i,1},phi{i,1}]=ellparams_one(x{i},y{i},[],dim);\n else\n z=varargin{3};\n [kappa{i,1},lambda{i,1},theta{i,1},phi{i,1},alpha{i,1},beta{i,1}]=...\n ellparams_one(x{i},x{i},z{3}{i},dim);\n end\n else\n [kappa{i,1},lambda{i,1},theta{i,1},phi{i,1},alpha{i,1},beta{i,1}]=vempty;\n end\n end\n end\nend\n\nfunction[kappa,lambda,theta,phi,alpha,beta]=ellparams_one(x,y,z,dim)\n\n[alpha,beta]=vempty;\n\nif isempty(z)\n [kappa,lambda,theta,phi]=ellconv_xy2kl(abs(x),abs(y),angle(x),angle(y),dim);\nelse\n [nx,ny,nz]=normvect(x,y,z);\n warning('off','MATLAB:log:logOfZero')\n alpha=imag(log(sqrt(-1)*nx-ny));\n warning('on','MATLAB:log:logOfZero')\n beta=imag(log(nz+sqrt(-1)*sqrt(nx.^2+ny.^2)));\n [x,y,z]=vectmult(jmat3(-alpha,3),x,y,z);\n [x,y,z]=vectmult(jmat3(-beta,1),x,y,z);\n [kappa,lambda,theta,phi]=ellconv_xy2kl(abs(x),abs(y),angle(x),angle(y),dim);\nend\n \nfunction[kappa,lambda,theta,phi]=ellconv_xy2kl(X,Y,phix,phiy,dim)\n%phia=double(phix+phiy+pi/2)/2;\n%phid=double(phix-phiy-pi/2)/2;\n%P=double(frac(1,2)*sqrt(squared(X)+squared(Y)+2.*X.*Y.*cos(2*phid)));\n%N=double(frac(1,2)*sqrt(squared(X)+squared(Y)-2.*X.*Y.*cos(2*phid)));\n\nphia=(phix+phiy+pi/2)/2;\nphid=(phix-phiy-pi/2)/2;\n\nP=frac(1,2)*sqrt(squared(X)+squared(Y)+2.*X.*Y.*cos(2*phid));\nN=frac(1,2)*sqrt(squared(X)+squared(Y)-2.*X.*Y.*cos(2*phid));\n\nphip=unwrap(phia+imlog(X.*rot(phid)+Y.*rot(-phid)),[],dim);\nphin=unwrap(phia+imlog(X.*rot(phid)-Y.*rot(-phid)),[],dim);\n\nkappa=sqrt(P.^2+N.^2);\nlambda=frac(2*P.*N.*sign(P-N),P.^2+N.^2);\n\n%For vanishing linearity, put in very small number to have sign information \nlambda(lambda==0)=sign(P(lambda==0)-N(lambda==0))*(1e-10);\n\ntheta=phip/2-phin/2;\nphi= phip/2+phin/2;\n\ntheta=unwrap(theta,[],dim);\nphi=unwrap(phi,[],dim);\n\nlambda=real(lambda);\n\n\nfunction[nx,ny,nz]=normvect(x,y,z)\n%NORMVECT Unit normal vector to the ellipse plane in three dimensions.\n%\n% [NX,NY,NZ]=NORMVECT(X,Y,Z) returns the three components of the unit \n% normal vector to the plane containing the ellipse specified by the \n% three complex-valued arrays X, Y, and Z.\n%\n% In vector notation the normal vector is defined as N=IMAG(X) x REAL(X),\n% where ``x'' is the vector cross product, and the unit normal is N/||N||.\n%\n% The input arrays and output arrays are all the same size.\n% \n% See Lilly (2010) for details.\n%\n% 'normvect --t' runs a test.\n%\n% Usage: [nx,ny,nz]=normvect(x,y,z);\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2010 J.M. Lilly --- type 'help jlab_license' for details\n \nnx= (imag(y).*real(z)-imag(z).*real(y));\nny=-(imag(x).*real(z)-imag(z).*real(x));\nnz= (imag(x).*real(y)-imag(y).*real(x));\n \ndenom=sqrt(nx.^2+ny.^2+nz.^2);\nnx=frac(nx,denom);\nny=frac(ny,denom);\nnz=frac(nz,denom);\n\nfunction[]=normvect_test\n \nload solomon \nuse solomon\n\n[x,y,z]=anatrans(x./1e4,y./1e4,z./1e4);\n[nx,ny,nz]=normvect(x,y,z);\n\ndot=nx.*x+ny.*y+nz.*z;\n\nreporttest('NORMVECT parallel part of X_+ vanishes, Solomon Islands',allall(abs(dot)<1e-10))\n\n\n%Choose central part where signal is elliptical\nvindex(x,y,z,7000:10000,1);\n\n[ax,omx,upx]=instmom(x);\n[ay,omy,upy]=instmom(y);\n[az,omz,upz]=instmom(z);\n \ndx=x.*(upx+sqrt(-1)*omx);\ndy=y.*(upy+sqrt(-1)*omy);\ndz=z.*(upz+sqrt(-1)*omz);\n\n[nx,ny,nz]=normvect(x,y,z);\n\ndot=nx.*dx+ny.*dy+nz.*dz; %Parallel part of derivative\n\n[dnx,dny,dnz]=vdiff(nx,ny,nz,1);\n\ndot2=-(dnx.*x+dny.*y+dnz.*z); \n\nerr=abs(dot-dot2).^2./abs(dot).^2;\nerr=flipud(sort(err));\nerr=err(60:end);\n\n\nreporttest('NORMVECT derivative of parallel part matches, Solomon Islands (removing worst outliers)',allall(err<0.05))\n\n\n\n\nfunction[]=ellparams_test\n \nt=(0:1:925)';\nkappa=3*exp(2*0.393*(t/1000-1));\nlambda=0.5+0*kappa;\nphi=(t/1000*5)*2*pi;\ntheta=pi/4+phi./14.45;\n\nbeta=pi/6+phi./14.45*lambda(1);\nalpha=pi/6-phi./14.45*2*lambda(1)*sqrt(2);\n\n[x,y,z]=ellsig(kappa,lambda,theta,phi,alpha,beta);\n[kappa2,lambda2,theta2,phi2,alpha2,beta2]=ellparams(x,y,z);\n\nx1=[kappa lambda theta phi alpha beta];\nx2=[kappa2 lambda2 theta2 phi2 alpha2 beta2];\nreporttest('ELLPARAMS rapidly changing trivariate ellipse',aresame(x1,x2,1e-8))\n\n\n\n% %/*******************************************************************\n% %Flip ellipse parameters if unit normal is pointing radially inwards\n% %Components of unit normal vector to surface of earth\n% [nx,ny,nz]=normvect(xr,yr,zr);\n% \n% %Replicate x, y, and z along columns\n% xmat=vrep(x,size(nx,2),2)./radearth;\n% ymat=vrep(y,size(ny,2),2)./radearth;\n% zmat=vrep(z,size(nz,2),2)./radearth;\n% \n% %Projection of normal vector to plane onto normal to sphere\n% proj=xmat.*nx+ymat.*ny+zmat.*nz;\n% \n% bool=(proj<0);\n% theta(bool)=-theta(bool);\n% lambda(bool)=-lambda(bool);\n% beta(bool)=pi+beta(bool);\n% nx(bool)=-nx(bool);\n% ny(bool)=-ny(bool);\n% nz(bool)=-nz(bool);\n% \n% if length(find(bool))>0\n% [xr2,yr2,zr2]=ellsig(kappa,lambda,theta,phi,alpha,beta);\n% tol=1e-6;\n% reporttest('ELLIPSEXTRACT adjustment for sign of normal vector',aresame(xr2,xr,tol)&&aresame(yr2,yr,tol)&&aresame(zr2,zr,tol))\n% end\n% \n% %dev=1-abs(proj);\n% %figure,plot(dev)\n% [latn,lonn]=xyz2latlon(nx*radearth,ny*radearth,nz*radearth);\n% %\\*******************************************************************\n", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jEllipse/ellparams.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7853085758631158, "lm_q1q2_score": 0.6836875062773728}} {"text": "function [out_image_m,out_ref_points_m] = rotate_image( degree, in_image_m, in_ref_points_m )\n%\n% rotate_image - rotates an image given inside a matrix by the amount of \"degree\" counter-clockwise\n% using linear interpolation of the output grid points from the back-rotated input points\n% in this way, the output image will never have a \"blank\" point\n%\n% Format: [out_image_m,out_ref_points_m] = rotate_image( degree, in_image_m, in_ref_points_m )\n%\n% Input: degree - rotation degree in dergees, counter-clockwise\n% in_image_m - input image, given inside a matrix (gray level image only)\n% in_ref_points_m - points on the image wich their output coordinates will be given\n% after the rotation. given format of this matrix is:\n% [ x1,x2,...,xn;y1,y2,...,yn]\n%\n% Output: out_image_m - the output image\n% out_ref_points_m - the position of the input handle points after the rotation.\n% this element is given in \"in_ref_points_m\" exists\n% format of the matrix is the same as of \"in_ref_points_m\"\n% \n% NOTE: By definition of rotation, in order to perserve all the image inside the\n% rotated image space, the output image will be a matrix with a bigger size. \n%\n\n% NO INPUT ARGs - Launch demo and exit\nif (nargin == 0)\n rotate_image_demo;\n out_image_m = [];\n return;\nend\n\n% check input\nif ~exist('in_ref_points_m')\n in_ref_points_m = [];\nend\n\n% check for easy cases\nswitch (mod(degree,360))\ncase 0, \n out_image_m = in_image_m;\n out_ref_points_m = in_ref_points_m;\n return;\ncase 90, \n out_image_m = in_image_m(:,end:-1:1)';\n out_ref_points_m = in_ref_points_m(end:-1:1,:); \n out_ref_points_m(2,:) = size(out_image_m,1) - out_ref_points_m(2,:);\n return;\ncase 180, % TBD for rotation of the ref_points\n out_image_m = in_image_m(end:-1:1,end:-1:1);\n out_ref_points_m = in_ref_points_m;\n out_ref_points_m(2,:) = size(out_image_m,2) - out_ref_points_m(2,:);\n out_ref_points_m(1,:) = size(out_image_m,1) - out_ref_points_m(1,:);\n return;\ncase 270, \n out_image_m = in_image_m(end:-1:1,:)';\n out_ref_points_m = in_ref_points_m(end:-1:1,:);\n out_ref_points_m(1,:) = size(out_image_m,2) - out_ref_points_m(1,:);\n return;\notherwise, % enter the routine and do some calculations\nend\n\n% wrap input image by zeros from all sides\nzeros_row = zeros(1,size(in_image_m,2)+2);\nzeros_column = zeros(size(in_image_m,1),1);\nin_image_m = [zeros_row; zeros_column,in_image_m,zeros_column; zeros_row ];\n\n% build the rotation matrix\ndegree_rad = degree * pi / 180;\nR = [ cos(degree_rad), sin(degree_rad); sin(-degree_rad) cos(degree_rad) ];\n\n% input and output size of matrices (output size is found by rotation of 4 corners)\nin_size_x = size(in_image_m,2);\nin_size_y = size(in_image_m,1);\nin_mid_x = (in_size_x-1) / 2;\nin_mid_y = (in_size_y-1) / 2;\nin_corners_m = [ [0,0,in_size_x-1,in_size_x-1] - in_mid_x;\n [0,in_size_y-1,in_size_y-1,0] - in_mid_y ];\nout_corners_m = R * in_corners_m;\n\n% the grid (integer grid) of the output image and the output image\n[out_x_r,out_y_r] = rotated_grid( out_corners_m );\nout_size_x = max( out_x_r ) - min( out_x_r ) + 1;\nout_size_y = max( out_y_r ) - min( out_y_r ) + 1;\nout_image_m = zeros( ceil( out_size_y ),ceil( out_size_x ) );\nout_points_span = (out_x_r-min(out_x_r))*ceil(out_size_y) + out_y_r - min(out_y_r) + 1;\nif ~isempty( in_ref_points_m )\n out_ref_points_m = (R * [in_ref_points_m(1,:)-in_mid_x;in_ref_points_m(2,:)-in_mid_y]);\n out_ref_points_m = [out_ref_points_m(1,:)-min( out_x_r )+1;out_ref_points_m(2,:)-min( out_y_r )+1];\nelse\n out_ref_points_m = [];\nend\n \n% % for debug\n% out_image_m(out_points_span) = 1;\n% return;\n% % end of for debug\n\n% the position of points of the output grid in terms of the input grid\nin_cords_dp_m = inv(R) * [out_x_r;out_y_r];\n\nx_span_left = floor(in_cords_dp_m(1,:) + in_mid_x + 10*eps );\ny_span_down = floor(in_cords_dp_m(2,:) + in_mid_y + 10*eps );\nx_span_right = x_span_left + 1;\ny_span_up = y_span_down + 1;\ndx_r = in_cords_dp_m(1,:) - floor( in_cords_dp_m(1,:) + 10*eps );\ndy_r = in_cords_dp_m(2,:) - floor( in_cords_dp_m(2,:) + 10*eps );\n\npoint_span_0_0 = x_span_left*ceil(in_size_y) + y_span_down + 1; % position of combined index in output matrix\npoint_span_1_0 = x_span_left*ceil(in_size_y) + y_span_up + 1;\npoint_span_0_1 = x_span_right*ceil(in_size_y) + y_span_down + 1;\npoint_span_1_1 = x_span_right*ceil(in_size_y) + y_span_up + 1;\n\nout_image_m(out_points_span) = ...\n in_image_m( point_span_0_0 ).*(1-dx_r).*(1-dy_r) + ...\n in_image_m( point_span_1_0 ).*(1-dx_r).*( dy_r) + ...\n in_image_m( point_span_0_1 ).*( dx_r).*(1-dy_r) + ...\n in_image_m( point_span_1_1 ).*( dx_r).*( dy_r);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Inner function implementation %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [x_r,y_r] = rotated_grid( rect_points_m )\n%\n% rotated_grid - creates a grid of points bounded inside a rotated RECTANGLE\n%\n% Format: [x_m,y_m] = rotated_grid( rect_points_m )\n%\n% Input: rect_points_m - a set of (x;y) points which define a rectangle ordered clock-wise\n% ( format: [x1,x2,x3,x4;y1,y2,y3,y4] )\n%\n% Output: x_r,y_r - 2 row vectors which hold the x and y positions of \n% the output grid\n% \n% NOTE: THE ASSUMPTION IS THAT THE RECTANGLE IS ORDERED CLOCK-WISE !!!\n% AND THAT THE GIVEN CO-ORDINATES ARE A RECTANGLE !\n%\n\n\n% make sure that the first point of the clock-wise-ordered rectange is of the most left point\n[temp,idx] = min( rect_points_m(1,:) );\nif ( idx > 1 )\n rect_points_m = [ rect_points_m(:,idx:end) , rect_points_m(:,1:idx-1) ];\nend\n\n% put into variables so it is easier to access/read the numbers\nx1 = rect_points_m(1,1);\nx2 = rect_points_m(1,2);\nx3 = rect_points_m(1,3);\nx4 = rect_points_m(1,4);\ny1 = rect_points_m(2,1);\ny2 = rect_points_m(2,2);\ny3 = rect_points_m(2,3);\ny4 = rect_points_m(2,4);\n\n% initialization for grid creation\nclipped_top = floor( y2 );\nclipped_bottom = ceil( y4 );\nfraction_bottom = clipped_bottom - y4;\nrows = ( clipped_top - clipped_bottom );\nleft_crossover = y1 - y4;\nright_crossover = y3 - y4;\n\n% calculate the position of the edges (left and right) along the y axis\nm = [0:rows] + fraction_bottom ;\nswitch (y1)\ncase y2, x_left = repmat( ceil( x4 ),size(m) );\ncase y4, x_left = repmat( ceil( x2 ),size(m) );\notherwise \n x_left = ( m >= left_crossover ).*ceil( x2 - (x1-x2)/(y1-y2)*(rows-m+2*fraction_bottom) ) + ...\n ( m < left_crossover ).*ceil( x4 + (x1-x4)/(y1-y4)*m );\nend\nswitch (y3)\ncase y2, x_right = repmat( floor( x4 ),size(m) );\ncase y4, x_right = repmat( floor( x2 ),size(m) );\notherwise\n x_right = ( m >= right_crossover ).*floor( x2 - (x3-x2)/(y3-y2)*(rows-m+2*fraction_bottom) ) + ...\n ( m < right_crossover ).*floor( x4 + (x3-x4)/(y3-y4)*m );\nend\n \n% build the output vectors (initialize) \nvec_length = sum(x_right-x_left+1);\nx_r = zeros(1,vec_length );\ny_r = zeros(1,vec_length );\n\n% build the grid into the output vectors\ncursor = 1;\nfor n = 1:length(m)\n if ( x_right(n) >= x_left(n) )\n span = cursor:(x_right(n) - x_left(n) + cursor);\n x_r( span ) = x_left(n):x_right(n);\n y_r( span ) = m(n) + y4;\n cursor = cursor + x_right(n) - x_left(n) + 1; \n end\nend\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Demo implementation of this routine %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction rotate_image_demo\n\n% plot the \"child\" image, and get it's matrix\nclose all;\nh = imagesc;\nin_image_m = get( h,'cdata' );\nset( get( h,'parent' ),'ydir','reverse' );\ntitle( 'original image' );\n\n% create targets on the image\n[sy,sx] = size( in_image_m );\nhold on;\nin_ref_points_m = [ [0.05 0.05 0.5 0.95 0.75 0.95]*sx; [0.05 0.7 0.95 0.7 0.3 0.05]*sy ];\nplot( in_ref_points_m(1,:),in_ref_points_m(2,:),'k','linewidth',2 );\nhold off;\n\n% loop over selected angles and plot the roated image with it's targets\nfor degree = [0 15 25 30 45 60 75 90]\n [out_image_m,out_ref_points_m] = rotate_image( degree, in_image_m, in_ref_points_m );\n figure;\n imagesc( out_image_m );\n title( sprintf( 'Rotated image by %d degrees',degree ) );\n hold on;\n plot( out_ref_points_m(1,:),out_ref_points_m(2,:),'k','linewidth',2 );\n hold off;\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/4071-rotate-image/rotate_image.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6836875062174809}} {"text": "%% check Clebsch Gordan Tensor\n\n\n%% the reference\n\n% some arbitrary rotation\ng = rotation.byEuler(-72*degree,-88*degree,-134*degree);\n\n% we want to express the product of two wigner D functions\nD2 = WignerD(g,'order',2);\nD1D2_ref = D2(:) * D2(:).';\n\n%% expansion into Wigner functions of lower order\n\n% zero order component\nD0 = WignerD(g,'order',0);\nCG0 = ClebschGordanTensor(2,2,0);\nC0 = EinsteinSum(CG0,[1 3 -1],D0,[-1,-2],CG0,[2 4 -2])\n\n% first order component\nD1 = WignerD(g,'order',1);\nCG1 = ClebschGordanTensor(2,2,1);\nC1 = EinsteinSum(CG1,[1 3 -1],D1,[-1 -2],CG1,[2 4 -2])\n\n% second order component\nD2 = WignerD(g,'order',2);\nCG2 = ClebschGordanTensor(2,2,2);\nC2 = EinsteinSum(CG2,[1 3 -1],D2,[-1 -2],CG2,[2 4 -2])\n\n% third order component\nD3 = WignerD(g,'order',3);\nCG3 = ClebschGordanTensor(2,2,3);\nC3 = EinsteinSum(CG3,[1 3 -1],D3,[-1 -2],CG3,[2 4 -2])\n\n% fourth order component\nD4 = WignerD(g,'order',4);\nCG4 = ClebschGordanTensor(2,2,4);\nC4 = EinsteinSum(CG4,[1 3 -1],D4,[-1 -2],CG4,[2 4 -2])\n\n\na = reshape(matrix(C0 + C1 + C2 + C3 + C4),[25,25]) ./ D1D2_ref;\n\nimagesc(real(a))\nmtexColorMap white2black\n\n%% next we expand D1 * D1 * D1 * D1 in the same way\n\n%% the reference\n\n% some arbitrary rotation\ng = rotation.byEuler(-72*degree,-88*degree,-134*degree);\n\n% we want to express the product of four wigner D functions\nD1 = WignerD(g,'order',1);\n\nT2D1_ref = D1(:) * D1(:).';\nT4D1_ref = T2D1_ref(:) * T2D1_ref(:).';\n\n%% expansion into Wigner functions of lower order\n\n%% zero order component\n\nT4D1 = tensor(zeros(repmat(3,1,8)));\nfor J = 0:4\n\n DJ = WignerD(g,'order',J);\n\n CGJ = tensor(zeros([repmat(3,1,8),2*J+1,2*J+1]),'rank',10);\n for j1 = 0:2\n for j2 = 0:2\n CGj1 = ClebschGordanTensor(1,1,j1);\n CGj2 = ClebschGordanTensor(1,1,j2);\n CGj1j2J = ClebschGordanTensor(j1,j2,J);\n C = EinsteinSum(...\n CGj1,[1 3 -1],...\n CGj1,[2 4 -2],...\n CGj2,[5 7 -3],...\n CGj2,[6 8 -4],...\n CGj1j2J,[-1 -3 9],...\n CGj1j2J,[-2 -4 10]);\n CGJ = CGJ + C;\n end\n end\n T4D1 = T4D1 + EinsteinSum(CGJ,[1:8 -1 -2],DJ,[-1 -2])\n\nend\n\n%%\n\na = reshape(double(T4D1),[3*3*3*3,3*3*3*3]) ./ T4D1_ref;\n\nimagesc(real(a))\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/tests/check_ClebschCordan4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6836134299430076}} {"text": "function nearest = find_closest2 ( m, nr, r, ns, s )\n\n%*****************************************************************************80\n%\n%% FIND_CLOSEST2 finds the nearest R point to each S point.\n%\n% Discussion:\n%\n% We are given R, a set of NR points in M dimensions.\n%\n% We are given S, a set of NS points in M dimensions.\n%\n% For each S(I) in S, we seek the index J of the point R(J)\n% which is nearest to S(I) over all points in R.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 July 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer NR, the number of cell generators.\n%\n% Input, real R(M,NR), the cell generators.\n%\n% Input, integer SN, the number of sample points.\n%\n% Input, real S(M,NS), the points to be checked.\n%\n% Output, integer NEAREST(NS), the index of the nearest cell generators.\n%\n\n%\n% Find nearest R to each S.\n%\n nearest = zeros ( ns, 1 );\n\n for js = 1 : ns\n\n rs = sum ( ( r - repmat ( s(:,js), 1, nr ) ).^2 );\n\n [ dummy, nearest(js) ] = min ( rs );\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/test_nearest/find_closest2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.6835783567858061}} {"text": "function hermite_polynomial_test16 ( )\n\n%*****************************************************************************80\n%\n%% HERMITE_POLYNOMIAL_TEST16 tests Hermite projection.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 December 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HERMITE_POLYNOMIAL_TEST16:\\n' );\n fprintf ( 1, ' As a sanity check, make sure that the projection of\\n' );\n fprintf ( 1, ' He(i,x) is 1 for the i-th component and zero for all others.\\n' );\n\n n = 3;\n\n [ x, w ] = he_quadrature_rule ( n + 1 );\n\n phi = hen_polynomial_value ( n + 1, n, x );\n\n for j = 0 : n\n\n c = zeros ( n + 1, 1 );\n\n f_vec(1:n+1,1) = phi ( 1 : n + 1, j + 1 );\n\n for i = 1 : n + 1\n phiw(i,1:n+1) = phi(i,1:n+1) * w(i);\n end\n\n c = phiw' * f_vec;\n title = sprintf ( ' Coefficients for He(%d,x)', j );\n\n r8vec_print ( n + 1, c, title );\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/hermite_polynomial/hermite_polynomial_test16.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.6835783548307574}} {"text": "function [minscale,crit,delta_list,lgd] = compute_minimum_scale(D, options)\n\n% compute_minimum_scale - compute minimum deconvolution scale\n%\n% D should be a (p,n) dictionary matrix. Each D(:,i) is an atom located\n% at some position i.\n%\n% mscale(i) is a minimum scale as computed using a given criterion:\n% i=1 WERC criterion\n% i=2 ERC criterion\n% i=3 Fuchs criterion\n% one has mscale(i)>mscale(i+1) since the Fuch criterion is the finest\n% criterion (depends on sign).\n%\n% options.mscale_type can be 'train' (spike train) or 'twodiracs'.\n% options.display=1 to display a graph of the criterions\n%\n% Copyright (c) 2008 Gabriel Peyre\n\n\np = size(D,2); n = size(D,1);\n\noptions.null = 0;\nmscale_type = getoptions(options, 'mscale_type', 'train');\ndelta_max = getoptions(options, 'delta_max', p/4);\ndisp = getoptions(options, 'display', 0);\ndelta_max = min(delta_max,p/2);\nverb = getoptions(options, 'verb', 1);\n\nsubsampling = getoptions(options, 'subsampling', 1);\n\ndelta_list = 2:delta_max;\nntests = length(delta_list);\n\n% record normalized gram\nd = sqrt(sum(D.^2));\nD1 = D ./ repmat(d, [size(D,1),1]);\nG = abs(D1'*D1);\n\n\nerc = [];\nwerc = [];\nfuchs = [];\nfor i=1:ntests\n if verb\n progressbar(i,ntests);\n end\n delta = delta_list(i);\n % generate signal with spacing delta\n x = zeros(p,1); \n switch mscale_type\n case 'train'\n x(1:delta:p-delta+1) = 1;\n case 'twodiracs'\n x(round(end/2)) = 1;\n x(round(end/2)+delta) = 1;\n otherwise\n error('Unknown type');\n end\n % compute criterias\n werc(i) = compute_werc_criterion(D1,x,G);\n erc(i) = 1 - compute_erc_criterion(D1,x);\n fuchs(i) = compute_fuchs_criterion(D1,x); \nend\n\n\ncrit = [werc; erc; fuchs];\nlgd = {'werc', 'erc', 'fuchs'};\ncol = {'b', 'g', 'r'};\nvmin = .7; vmax = 1.8;\n\nif disp\n clf;\n hold on;\n aa = plot(delta_list*subsampling, crit); axis tight;\n set(aa, 'LineWidth', 2);\nend\nfor i=1:3\n k = ntests;\n while crit(i,k)<1 && k>0\n k = k-1;\n end\n minscale(i) = delta_list(min(k+1,end))*subsampling;\n if disp\n aa = plot([1 1]*minscale(i), [vmin vmax], [col{i}(1) ':']);\n set(aa, 'LineWidth', 2);\n end\nend\nif disp\n axis([0 max(delta_list)*subsampling vmin vmax]);\n hold off; box on;\n legend(lgd);\nend", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_sparsity/compute_minimum_scale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.6835783516922627}} {"text": "function value = r4_erf ( x )\n\n%*****************************************************************************80\n%\n%% R4_ERF evaluates the error function of an R4 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the error function of X.\n%\n persistent erfcs\n persistent nterf\n persistent sqeps\n persistent sqrtpi\n persistent xbig\n\n sqrtpi = 1.7724538509055160;\n\n if ( isempty ( nterf ) )\n\n erfcs = [ ...\n -0.049046121234691808, ...\n -0.14226120510371364, ...\n 0.010035582187599796, ...\n -0.000576876469976748, ...\n 0.000027419931252196, ...\n -0.000001104317550734, ...\n 0.000000038488755420, ...\n -0.000000001180858253, ...\n 0.000000000032334215, ...\n -0.000000000000799101, ...\n 0.000000000000017990, ...\n -0.000000000000000371, ...\n 0.000000000000000007 ]';\n\n nterf = r4_inits ( erfcs, 13, 0.1 * r4_mach ( 3 ) );\n xbig = sqrt ( - log ( sqrtpi * r4_mach ( 3 ) ) );\n sqeps = sqrt ( 2.0 * r4_mach ( 3 ) );\n\n end\n\n y = abs ( x );\n\n if ( y <= sqeps )\n value = 2.0 * x / sqrtpi;\n elseif ( y <= 1.0 )\n value = x * ( 1.0 + r4_csevl ( 2.0 * x * x - 1.0, erfcs, nterf ) );\n elseif ( y <= xbig )\n value = 1.0 - r4_erfc ( y );\n if ( x < 0.0 )\n value = - value;\n end\n else\n value = 1.0;\n if ( x < 0.0 )\n value = - value;\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/fn/r4_erf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6835783461868757}} {"text": "function res = matricize( U, mode )\n %MATRICIZE Matricize 3D Matlab array. \n % A = MATRICIZE(U, MODE) matricizes the 3D Matlab array U along the \n % specified mode MODE. Higher dimensions than 3 are not supported.\n %\n % See also TENSORIZE, TENSORPROD_TTEMPS, UNFOLD.\n \n % TTeMPS Toolbox. \n % Michael Steinlechner, 2013-2016\n % Questions and contact: michael.steinlechner@epfl.ch\n % BSD 2-clause license, see LICENSE.txt\n\n d = size(U);\n % pad with 1 for the last dim (annoying)\n if length(d) == 2\n d = [d, 1];\n end\n\n switch mode\n case 1\n res = reshape( U, [d(1), d(2)*d(3)] );\n case 2 \n res = reshape( permute( U, [2, 1, 3]), [d(2), d(1)*d(3)] );\n case 3 \n res = transpose( reshape( U, [d(1)*d(2), d(3)] ) );\n otherwise\n error('Invalid mode input in function matricize')\n end\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/ttfixedrank/TTeMPS_1.1/matricize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6835783461868756}} {"text": "function [c] = cov(x, varargin)\n\n% [C] = COV(X, NORMALIZEFLAG, DIM) computes the covariance, across all cells in x along \n% the dimension dim. W\n% [C] = COV(X, Y, NORMALIZEFLAG, DIM) computes the covariance between all cells in x and y\n% \n% X (and Y) should be linear cell-array(s) of matrices for which the size in at \n% least one of the dimensions should be the same for all cells \n\nif numel(varargin)==0\n normalizeflag = 0;\n dim = [];\n flag = 0;\nend\n\nif numel(varargin)>=1 && iscell(varargin{1})\n y = varargin{1};\n varargin = varargin(2:end);\nelse \n y = []; \nend\n\nif numel(varargin)>=1 && isempty(varargin{1})\n normalizeflag = 0;\n varargin = varargin(2:end);\nelseif numel(varargin)>=1\n normalizeflag = varargin{1};\n varargin = varargin(2:end);\nend\n\nif numel(varargin)>=1\n dim = varargin{1};\n varargin = varargin(2:end);\nend\n\nif numel(varargin>=1)\n flag = varargin{1};\nelse\n flag = 1;\nend\n\nif isempty(dim)\n [scx1, scx2] = size2(x, [], 'cell');\n if all(scx1==scx1(1)), dim = 2;\n elseif all(scx2==scx2(1)), dim = 1; %let second dimension prevail\n else error('no dimension to compute covariance for');\n end\nend\n\nnx = size(x);\nif ~iscell(x) || length(nx)>2 || all(nx>1)\n error('incorrect input for cellcov');\nend\n\nnx = max(nx);\nnsmp = cellfun('size', x, dim);\nn = sum(nsmp);\nif isempty(y) \n for k = 1:nx\n [tmp1, tmp2] = covc(x{k}, dim);\n if k==1\n C = tmp1;\n M = tmp2;\n else\n C = C + tmp1;\n M = M + tmp2;\n end\n end\n Mx = M;\n My = M;\nelse\n for k = 1:nx\n [tmp1, tmp2, tmp3] = covc(x{k}, y{k}, dim);\n if k==1\n C = tmp1;\n Mx = tmp2;\n My = tmp3;\n else \n C = C + tmp1;\n Mx = Mx + tmp2;\n My = My + tmp3;\n end \n end\nend\n\nif normalizeflag || n==1\n % normalize by n\n n1 = n;\n n2 = n;\nelse\n % normalize by n-1\n n1 = n;\n n2 = n-1;\nend\n\nif flag\n c = (C-(Mx(:)*My(:)')./n1)./n2;\nelse\n c = C./n2;\nend\n\nfunction [c,mx,my] = covc(x, y, dim)\n\nif nargin==2\n dim = y;\n y = x;\nend\n\nif islogical(x), x = double(x); end\nif islogical(y), y = double(y); end\n\nif dim==1\n c = x'*y;\nelseif dim==2\n c = x*y';\nend\n\nmx = sum(x,dim);\nmy = sum(y,dim);\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/cellfunction/@cell/cov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.6835783422767783}} {"text": "function overall_mssim = ssim_mscale_new(img1, img2, K, window, level, weight, method)\n\n% Multi-scale Structural Similarity Index (MS-SSIM)\n% Z. Wang, E. P. Simoncelli and A. C. Bovik, \"Multi-scale structural similarity\n% for image quality assessment,\" Invited Paper, IEEE Asilomar Conference on\n% Signals, Systems and Computers, Nov. 2003\n\nif (nargin < 2 | nargin > 7)\n overall_mssim = -Inf;\n return;\nend\n\nif (~exist('K'))\n K = [0.01 0.03];\nend\n\nif (~exist('window'))\n window = fspecial('gaussian', 11, 1.5);\nend\n\nif (~exist('level'))\n level = 5;\nend\n\nif (~exist('weight'))\n weight = [0.0448 0.2856 0.3001 0.2363 0.1333];\nend\n\nif (~exist('method'))\n method = 'product';\nend\n\nif (size(img1) ~= size(img2))\n overall_mssim = -Inf;\n return;\nend\n\n[M N] = size(img1);\nif ((M < 11) | (N < 11))\n overall_mssim = -Inf;\n return\nend\n\nif (length(K) ~= 2)\n overall_mssim = -Inf;\n return;\nend\n\nif (K(1) < 0 | K(2) < 0)\n overall_mssim = -Inf;\n return;\nend\n \n[H W] = size(window);\n\nif ((H*W)<4 | (H>M) | (W>N))\n overall_mssim = -Inf;\n return;\nend\n \nif (level < 1)\n overall_mssim = -Inf;\n return\nend\n\n\nmin_img_width = min(M, N)/(2^(level-1));\nmax_win_width = max(H, W);\nif (min_img_width < max_win_width)\n overall_mssim = -Inf;\n return;\nend\n\nif (length(weight) ~= level | sum(weight) == 0)\n overall_mssim = -Inf;\n return;\nend\n\nif (method ~= 'wtd_sum' & method ~= 'product')\n overall_mssim = -Inf;\n return;\nend\n\ndownsample_filter = ones(2)./4;\nim1 = img1;\nim2 = img2;\nfor l = 1:level\n [mssim_array(l) ssim_map_array{l} mcs_array(l) cs_map_array{l}] = ssim_index_new(im1, im2, K, window);\n [M N] = size(im1);\n filtered_im1 = filter2(downsample_filter, im1, 'valid');\n filtered_im2 = filter2(downsample_filter, im2, 'valid');\n clear im1, im2;\n im1 = filtered_im1(1:2:M-1, 1:2:N-1);\n im2 = filtered_im2(1:2:M-1, 1:2:N-1);\n ds_img_array1{l} = im1;\n ds_img_array2{l} = im2;\nend\n\nif (method == 'product')\n% overall_mssim = prod(mssim_array.^weight);\n overall_mssim = prod(mcs_array(1:level-1).^weight(1:level-1))*mssim_array(level);\nelse\n weight = weight./sum(weight);\n overall_mssim = sum(mcs_array(1:level-1).*weight(1:level-1)) + mssim_array(level);\nend\n", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/qualityMeasures/msssim/ssim_mscale_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6835783336328956}} {"text": "function h = draw_line_clip(m,b,a, linespec, varargin)\n%DRAW_LINE_CLIP Draw a line defined by an equation.\n% DRAW_LINE_CLIP(M,B,A) draws a line, clipped to the current axes, \n% defined by a*y = m*x + b.\n% DRAW_LINE_CLIP(M,B,A,LINESPEC) also specifies the line style and color.\n\nif nargin < 4\n linespec = 'b';\nend\nv = axis;\nx1 = v(1);\nx2 = v(2);\nwarning off\ny1 = (m*x1 + b)/a;\ny2 = (m*x2 + b)/a;\nwarning on\nif y1 < v(3)\n y1 = v(3);\n x1 = (a*y1 - b)/m;\nend \nif y1 > v(4)\n y1 = v(4);\n x1 = (a*y1 - b)/m;\nend \nif y2 < v(3);\n y2 = v(3);\n x2 = (a*y2 - b)/m;\nend\nif y2 > v(4);\n y2 = v(4);\n x2 = (a*y2 - b)/m;\nend\nh = line([x1 x2], [y1 y2]);\nset_linespec(h,linespec);\nif length(varargin) > 0\n set(h,varargin{:});\nend\nif nargout < 1\n clear h\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/+lightspeed/graphics/draw_line_clip.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6835689085158303}} {"text": "function X = pinv(A, tol)\n%PINV Pseudoinverse of a column CHEBFUN.\n% X = PINV(A) produces a row CHEBFUN X so that A*X*A = A and X*A*X = X.\n%\n% X = PINV(A, TOL) uses the tolerance TOL. The computation uses SVD(A) and any\n% singular value less than the tolerance TOL is treated as zero.\n%\n% See also SVD, RANK.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information. \n\nif ( A(1).isTransposed ) \n error('CHEBFUN:CHEBFUN:pinv:row', ...\n 'PINV only defined for column CHEBFUN objects.')\nend\n\n% Compute the SVD:\n[U, S, V] = svd(A, 0);\ns = diag(S);\n\n% Choose a tolerance if none is given:\nif ( nargin == 1 )\n\ttol = max(length(A)*eps(max(s)), vscale(A)*eps);\nend\n\n% Compute the rank:\nr = sum(s > tol);\n\nif ( r == 0 )\n\tX = 0*A';\nelse\n U = extractColumns(U, 1:r);\n S = diag(ones(r,1)./s(1:r));\n V = V(:,1:r);\n\tX = V*S*U';\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun/pinv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.683568903844186}} {"text": "function pde = elasticity3datapoly(para)\n%% ELASTICITYDATA3 data for the elasticity problem in three dimensions\n%\n% Modified from elasticitydata by Huayi Wei.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n%% Lame constants\nif nargin == 0\n lambda = 1;\n mu = 1;\nelse\n if ~isstruct(para)\n exit('we need a struct data');\n end\n if ~isfield(para,'lambda') || isempty(para.lambda)\n lambda = 1;\n else\n lambda = para.lambda;\n end\n if ~isfield(para,'mu') || isempty(para.mu)\n mu = 1;\n else\n mu = para.mu;\n end\nend\n\npde = struct('lambda',lambda,'mu',mu, 'f', @f, 'exactu',@exactu,'g_D',@g_D);\n%%%%%% subfunctions %%%%%%\n function s = f(p)\n% f = - mu \\Delta u - (mu + lambda) grad(div u) \n x = p(:,1); y = p(:,2); z = p(:,2);\n f1 = lambda*(32*y.*z.*(y - 1).*(z - 1) + 64*x.*y.*(2*z - 1).*(y - 1) ...\n + 32*x.*z.*(2*y - 1).*(z - 1) + 64*y.*(2*z - 1).*(x - 1).*(y - 1) ...\n + 32*z.*(2*y - 1).*(x - 1).*(z - 1)) + 32*mu*z.*(z - 1).*(4*x.*y - 2*y - 3*x + x.^2 + 1) ...\n + 32*mu*y.*(y - 1).*(8*x.*z - 4*z - 5*x + x.^2 + 2) + 64*mu*y.*z.*(y - 1).*(z - 1);\n f2 = lambda*(64*x.*z.*(x - 1).*(z - 1) + 64*x.*y.*(2*z - 1).*(x - 1) ...\n + 16*y.*z.*(2*x - 1).*(z - 1) + 64*x.*(2*z - 1).*(x - 1).*(y - 1) ...\n + 16*z.*(2*x - 1).*(y - 1).*(z - 1)) + 64*mu*x.*(x - 1).*(4*y.*z - 2*z - 3*y + y.^2 + 1) ...\n + 16*mu*z.*(z - 1).*(4*x.*y - 6*y - 2*x + 4*y.^2 + 1) + 128*mu*x.*z.*(x - 1).*(z - 1);\n f3 = lambda*(128*x.*y.*(x - 1).*(y - 1) + 32*x.*z.*(2*y - 1).*(x - 1) ...\n + 16*y.*z.*(2*x - 1).*(y - 1) + 32*x.*(2*y - 1).*(x - 1).*(z - 1) ...\n + 16*y.*(2*x - 1).*(y - 1).*(z - 1)) + 32*mu*x.*(x - 1).*(4*y.*z - 6*z - 2*y + 4*z.^2 + 1) ...\n + 16*mu*y.*(y - 1).*(4*x.*z - 10*z - 2*x + 8*z.^2 + 1) + 256*mu*x.*y.*(x - 1).*(y - 1);\n s = [f1 f2 f3]; \n end\n function u = exactu(p)\n x = p(:,1); y = p(:,2); z = p(:,2);\n u1 = 16*x.*(1-x).*y.*(1-y).*z.*(1-z);\n u2 = 32*x.*(1-x).*y.*(1-y).*z.*(1-z);\n u3 = 64*x.*(1-x).*y.*(1-y).*z.*(1-z);\n u = [u1 u2 u3];\n end\n function s = g_D(p)\n s = exactu(p); \n end\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/data/elasticity3datapoly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740728, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6835688968899402}} {"text": "function value = r8_gamma_01_sample ( a )\n\n%*****************************************************************************80\n%\n%% R8_GAMMA_01_SAMPLE samples the standard Gamma distribution.\n%\n% Discussion:\n%\n% This procedure corresponds to algorithm GD in the reference.\n%\n% pdf ( a; x ) = 1/gamma(a) * x^(a-1) * exp ( - x )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 June 2013\n%\n% Author:\n%\n% Original FORTRAN77 version by Barry Brown, James Lovato.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Joachim Ahrens, Ulrich Dieter,\n% Generating Gamma Variates by a Modified Rejection Technique,\n% Communications of the ACM,\n% Volume 25, Number 1, January 1982, pages 47-54.\n%\n% Parameters:\n%\n% Input, real A, the parameter of the standard gamma\n% distribution. 0.0 < A < 1.0.\n%\n% Output, real VALUE, a random deviate from the distribution.\n%\n a1 = 0.3333333;\n a2 = -0.2500030;\n a3 = 0.2000062;\n a4 = -0.1662921;\n a5 = 0.1423657;\n a6 = -0.1367177;\n a7 = 0.1233795;\n\n e1 = 1.0;\n e2 = 0.4999897;\n e3 = 0.1668290;\n e4 = 0.0407753;\n e5 = 0.0102930;\n\n q1 = 0.04166669;\n q2 = 0.02083148;\n q3 = 0.00801191;\n q4 = 0.00144121;\n q5 = -0.00007388;\n q6 = 0.00024511;\n q7 = 0.00024240;\n\n sqrt32 = 5.656854;\n\n if ( 1.0 <= a )\n\n s2 = a - 0.5;\n s = sqrt ( s2 );\n d = sqrt32 - 12.0 * s;\n%\n% Immediate acceptance.\n%\n t = r8_normal_01_sample ( );\n x = s + 0.5 * t;\n value = x * x;\n\n if ( 0.0 <= t )\n return\n end\n%\n% Squeeze acceptance.\n%\n u = r8_uniform_01_sample ( );\n if ( d * u <= t * t * t )\n return\n end\n\n r = 1.0 / a;\n q0 = (((((( q7 ...\n * r + q6 ) ...\n * r + q5 ) ...\n * r + q4 ) ...\n * r + q3 ) ...\n * r + q2 ) ...\n * r + q1 ) ...\n * r;\n%\n% Approximation depending on size of parameter A.\n%\n if ( 13.022 < a )\n b = 1.77;\n si = 0.75;\n c = 0.1515 / s;\n elseif ( 3.686 < a )\n b = 1.654 + 0.0076 * s2;\n si = 1.68 / s + 0.275;\n c = 0.062 / s + 0.024;\n else\n b = 0.463 + s + 0.178 * s2;\n si = 1.235;\n c = 0.195 / s - 0.079 + 0.16 * s;\n end\n%\n% Quotient test.\n%\n if ( 0.0 < x )\n\n v = 0.5 * t / s;\n\n if ( 0.25 < abs ( v ) )\n q = q0 - s * t + 0.25 * t * t + 2.0 * s2 * log ( 1.0 + v );\n else\n q = q0 + 0.5 * t * t * (((((( a7 ...\n * v + a6 ) ...\n * v + a5 ) ...\n * v + a4 ) ...\n * v + a3 ) ...\n * v + a2 ) ...\n * v + a1 ) ...\n * v;\n end\n\n if ( log ( 1.0 - u ) <= q )\n return\n end\n\n end\n\n while ( 1 )\n\n e = r8_exponential_01_sample ( );\n u = 2.0 * r8_uniform_01_sample ( ) - 1.0;\n\n if ( 0.0 <= u )\n t = b + abs ( si * e );\n else\n t = b - abs ( si * e );\n end\n%\n% Possible rejection.\n%\n if ( t < -0.7187449 )\n continue\n end\n%\n% Calculate V and quotient Q.\n%\n v = 0.5 * t / s;\n\n if ( 0.25 < abs ( v ) )\n q = q0 - s * t + 0.25 * t * t + 2.0 * s2 * log ( 1.0 + v );\n else\n q = q0 + 0.5 * t * t * (((((( a7 ...\n * v + a6 ) ...\n * v + a5 ) ...\n * v + a4 ) ...\n * v + a3 ) ...\n * v + a2 ) ...\n * v + a1 ) ...\n * v;\n end\n%\n% Hat acceptance.\n%\n if ( q <= 0.0 )\n continue\n end\n\n if ( 0.5 < q )\n w = exp ( q ) - 1.0;\n else\n w = (((( e5 * q + e4 ) * q + e3 ) * q + e2 ) * q + e1 ) * q;\n end\n%\n% May have to sample again.\n%\n if ( c * abs ( u ) <= w * exp ( e - 0.5 * t * t ) )\n break\n end\n\n end\n\n x = s + 0.5 * t;\n value = x * x;\n\n return\n%\n% Method for A < 1.\n%\n else\n\n b = 1.0 + 0.3678794 * a;\n\n while ( 1 )\n\n p = b * r8_uniform_01_sample ( );\n\n if ( p < 1.0 )\n\n value = exp ( log ( p ) / a );\n\n if ( value <= r8_exponential_01_sample ( ) )\n return\n end\n\n continue\n\n end\n\n value = - log ( ( b - p ) / a );\n\n if ( ( 1.0 - a ) * log ( value ) <= r8_exponential_01_sample ( ) )\n break\n end\n\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/pdflib/r8_gamma_01_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6835688968662865}} {"text": "function [f,Ph]=haralick_n(qs,nL,q)\n% Haralick textures measurements\n\nPh = coocurrance_alldir_mod(q);\n% last row an column corresponds to outside ROI!\nPh=Ph(1:end-1,1:end-1);\nnL=nL-1;\n\n%compute features\nR=sum(Ph(:));\nPh=Ph/R;\n% Energy (1)\nf(1)=sum(sum(Ph.^2));\n% Contrast (2)\nf(2)=0.0;\nfor n=0:nL-1\n temp=0;\n for i=1:nL\n for j=1:nL\n if (abs(i-j) == n)\n temp=temp+Ph(i,j);\n end\n end\n end\n f(2)=f(2)+n^2*temp;\nend\n% Correlation\n%using symmetry Ph'=Ph!\nPx=sum(Ph);\nPy=sum(Ph');\nvec=[1:nL];\nux=sum(Px .*vec);\nuy=sum(Py .*vec);\n\nvarx=sum(Px .* vec.^2)-ux^2;\nsigx=sqrt(varx);\nvary=sum(Py .* vec.^2)-uy^2;\nsigy=sqrt(vary);\nu=vec*Ph(i,j)*vec';\nf(3)=(u-ux*uy)/(sigx*sigy);\n\n%Entropy (3)\nf(4)=-sum(sum(Ph.*log(Ph+realmin))); % log????\n \n% variance\nf(5)=0;\nfor i=1:nL\n for j=1:nL\n f(5)=f(5)+(i-u)^2*Ph(i,j);\n end\nend\n% P(x+y)\nf(6)=0; % sum of entropy...\nfor k=2:2*nL\n temp=0.0;\n for i=1:nL\n for j=1:nL\n if ((i+j) == k)\n temp=temp+Ph(i,j);\n end\n end\n end\n Pxpy(k)=temp;\n f(6)=f(6)-temp*log(temp+realmin);\nend\n\n% inverse different moment..\nf(7)=0;\nf(8)=0; %Homogeneity (4)\nfor i=1:nL\n for j=1:nL\n temp1=1/(1+(i-j)^2)*Ph(i,j);\n temp2=1/(1+abs(i-j))*Ph(i,j);\n f(7)=f(7)+temp1;\n f(8)=f(8)+temp2;\n end\nend\n\nreturn", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/heterogenity_metrics/helper_functions/haralick_n_mod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6835688922301228}} {"text": "% Compares the speed of CG implementations\nclc;\nclearvars;\nclose all;\n%rng default;\n\nN = 32;\n\nT = 1000;\nt1 = 0;\nt2 = 0;\nfor i=1:T\n if mod(i, 10) == 0\n fprintf('.');\n end\n A = spx.dict.simple.gaussian_mtx(N, N);\n A = A' * A;\n x = randn(N, 1);\n b = A * x;\n tolerance = 1e-2;\n max_iterations = N * 5;\n\n tic;\n [x, res, iter ] = cgsolve(A, b, tolerance, max_iterations, 0);\n t1 = t1 + toc;\n\n options.tolerance = tolerance;\n options.max_iterations = max_iterations;\n tic;\n result = spx.fast.cg(A, b, options);\n t2 = t2 + toc;\nend\n\nfprintf('\\n');\nfprintf('Time taken by MATLAB implementation: %0.3f\\n', t1);\nfprintf('Time taken by C++ implementation: %0.3f\\n', t2);\nfprintf('Gain: %0.2f\\n', t1/t2);", "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/experiments/optimization/cg/compare_cg_speed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6835688898765596}} {"text": "function [mph] = mach2mph(mach)\n% Convert speed from mach (at standard temp and pressure!) to miles per hour. \n% Chad A. Greene 2012\nmph = mach*767.2691481747;", "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/35258-unit-converters/unit_converters/mach2mph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6835451183502239}} {"text": "% INTERNAL FUNCTION: third-order multivariate chain rule\n% \n% ::\n% \n% res=third_order(dvvv,dvv,dv,vzzz,vzz,vz)\n% res=third_order(dvvv,dvv,dv,vzzz,vzz,vz,options)\n% \n% Args:\n% \n% - **dvvv** [nd x nv^3 matrix]: matrix of third derivatives of the d\n% function with respect to its locations. The derivatives are unfolded\n% columnwise\n% - **dvv** [nd x nv^2 matrix]: matrix of second derivatives of the d\n% function with respect to its locations. The derivatives are unfolded\n% columnwise\n% - **dv** [nd x nv matrix]: jacobian of function with respect to the\n% locations of its arguments\n% - **vzzz** [nv x nz^3 matrix]: third derivatives of the locations with\n% respect to the variables to differentiate. The derivatives are unfolded\n% columnwise\n% - **vzz** [nv x nz^2 matrix]: second derivatives (hessian) of the\n% locations with respect to the variables to differentiate. The derivatives\n% are unfolded columnwise\n% - **vz** [nv x nz matrix]: jacobian of the locations with respect to the\n% variables to differentiate\n% - **options** [empty|struct]: When not empty, options is a structure with\n% fields:\n% \n% - **large** [true|{false}] if true, a computation explicitly using the\n% kronecker product is avoided.\n% - **multiply** [true|{false}]: if true, explicit omega matrices are\n% constructed and then multiplied to other matrices to sum the\n% permutations. Else, a functional form is used instead.\n% \n% Returns:\n% :\n% \n% - **res** [nd x nz^3]: output matrix\n% \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/+utils/+cr/third_order.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6835451166412735}} {"text": "function [ d2q ] = gen_InverseDynamics(q,Pcii,Icii,mcii,dq,taw)\n%% This function is used to calculate the inverse dynamics of the KUKA iiwa 7 R 800\n% This function proposes that the robot is mounted with the base in the\n% horizontal poistion.\n\n% Arreguments:\n%--------------------\n% q: is 1x7 vector, joint nagles vector of the manipulator\n% dq: is 1x7 vector, joint angular velocity vector \n% taw: 1x7 vector, the torques on the joints due to the direct dynamics.\n% Pcii: is 3X7 matrix while each column represents the local coordinates\n% of the center of mass of each link.\n% Icii: is (3x3x7) matrix, each 3x3 matrix of which represnets the\n% associated link inertial tensor represented in its local inertial frame\n% mcii: is (1x7) vector, each element of which specifies a mass of one of\n% the links\n\n% Return value:\n%--------------------\n% d2q: is 7x1 vector, joint angular acceleration vector \n\n% Copyright: Mohammad SAFEEA, 9th-April-2018\n\n[M]=gen_MassMatrix(q,Pcii,Icii,mcii);\n[B]=gen_CoriolisMatrix(q,Pcii,Icii,mcii,dq);\n[ G ] = gen_GravityVector(q,Pcii,mcii);\n% convert angular velocity/acceleration into column vectors\ndq=columnVec(dq);\ntaw=columnVec(taw);\nd2q=M\\(taw-B*dq-G);\nend\n\nfunction y=columnVec(x)\nif(size(x,2)==1)\n y=x;\nelse\n y=x';\nend\nend\n\n", "meta": {"author": "Modi1987", "repo": "KST-Kuka-Sunrise-Toolbox", "sha": "9299bed2b46058aeb4105d7fbff6d2290ce68bba", "save_path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox", "path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox/KST-Kuka-Sunrise-Toolbox-9299bed2b46058aeb4105d7fbff6d2290ce68bba/OtherFlavours/RKST/Matlab_server/gen_InverseDynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6835451165966634}} {"text": "function Spath = Simulate_Jump_Diffusion_func( N_sim, M, T, S_0, r, q, sigma, jumpModel, jumpParams)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% About: Simulates Paths of Jump Diffusion Models with jumps (including simple Black-Scholes, no jumps)\n% Uses log-Euler scheme\n% Returns: paths of dimension (N_sim, M+1), since they include S_0 \n% ... Simulates N_sim paths, each row is a full path starting from S_0, ending with S_M (M+1 points in path)\n% Author: Justin Lars Kirkby\n%\n% -----------------\n% Params\n% -----------------\n% N_sim = # paths\n% M = #time steps on [0,T], time step is dt=T/M, so each path has M+1 points\n% T = time to maturity, ie path is on [0,T]\n% S_0 = initial underlying value (e.g. S_0=100)\n% r = interst rate (e.g. r = 0.05)\n% q = dividend yield (e.g. q = 0.05)\n% sigma = diffusion parameter (e.g. sigma = 0.2)\n%\n%===================================\n% jumpModel: 0 = NoJumps, 1 = NormalJumps, 2 = DEJumps, 3 = MixedNormalJumps\n%===================================\n% jumpParams = paramters container containing all necessary params for models,\n% : if jumpModel = 0, no jump params are needed\n% : if jumpModel > 0, jumpParams must contain lambda, kappa, and any other model specific params (see below)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargin < 8 % Then default is standard diffusion, NO JUMPS\n jumpModel = 0; jumpParams = {};\nend\n\ndt = T/M;\n\n%==============================\n% Initialize Jump Model Params and JumpFunc (function handle)\n%==============================\n%%% NOTE: Jump Model is of the form in LOG space\n%%% X(m+1) = X(m) + drift + Brownian Component + sum(Jumps on [m,m+1])\n%%% By Jump we mean log(Y), e.g. in Merton Model, Jump ~ Normal (since we are in log space )\n\nif jumpModel > 0 %ie if there are jumps in the model\n lambda = jumpParams.lambda;\n kappa = jumpParams.kappa;\n\n Zeta = r - q - lambda*kappa; %NOTE: we are redefining r to include compensation for jump component\n lamdt = lambda*dt;\n \n if jumpModel == 1 %Normal Jumps, e.g. Merton\n muJ = jumpParams.muJ;\n sigJ = jumpParams.sigJ;\n JumpFunc = @(n) sum(muJ +sigJ*randn(n,1)); %Generates n independent jumps and sums them\n \n elseif jumpModel == 2 %Double Exponenial Jumps \n p_up = jumpParams.p_up; \n eta1 = jumpParams.eta1;\n eta2 = jumpParams.eta2; \n JumpFunc = @(n) sum(DoubleExpoRnd(n,p_up, eta1,eta2));\n \n elseif jumpModel == 3 %Mixed normal Jumps\n p_up = jumpParams.p_up;\n a1 = jumpParams.a1; b1 = jumpParams.b1;\n a2 = jumpParams.a2; b2 = jumpParams.b2;\n JumpFunc = @(n) sum(MixedNormalRnd(n, p_up, a1,b1,a2,b2));\n end\nelse \n Zeta = r - q;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n\nSpath = zeros(N_sim,M+1);\nSpath(:,1) = S_0;\nSigsqdt = sigma*sqrt(dt);\ndrift = (Zeta - .5*sigma^2)*dt;\n \nif jumpModel == 0\n for m = 1:M\n W1 = randn(N_sim,1); \n Spath(:,m+1) = Spath(:,m).*exp(drift + Sigsqdt*W1); %log scheme\n end\nelse\n for m = 1:M\n Poi = PoissonRnd(N_sim, lamdt); %Generate Poisson Column Vector of size N_Sim\n sumJumpsVec = zeros(N_sim,1);\n for n = 1:N_sim\n if Poi(n)>0\n sumJumpsVec(n) = JumpFunc(Poi(n)); %JumpFunc(Poi(n)) sums up Poi(n) many jumps from the jump distribution\n end\n end\n\n W1 = randn(N_sim,1); \n Spath(:,m+1) = Spath(:,m).*exp(drift + sumJumpsVec + Sigsqdt*W1); %log scheme\n end\nend\n\n\nend\n\n\n\n\n\n\n", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/Monte_Carlo/Simulate_Jump_Diffusion_func.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6835451062983509}} {"text": "function [z,dz,ymu,ys,fmu,fs,fpi] = acqNegPI(xi,target,gpstruct,optimState,grad_flag)\n%ACQNEGPI Acquisition function for (negative) probability of improvement.\n\nif nargin < 5 || isempty(grad_flag); grad_flag = false; end\n\nn = size(xi,1);\nNhyp = numel(gpstruct.hyp);\n\nif grad_flag && n > 1\n error('acqNegPI:gradient', ...\n 'Gradient of acquisition function is provided only at one test point XI (row vector).');\nend\n\nif grad_flag\n [ymu,ys2,fmu,fs2,hypw,dymu,dys2,dfmu,dfs2] = gppred(xi,gpstruct,'central');\nelse\n [ymu,ys2,fmu,fs2,hypw] = gppred(xi,gpstruct);\nend\nfs = sqrt(fs2);\nys = sqrt(ys2);\n\n% Negative probability of improvement\ngammaz = (target - fmu)./fs;\nz = -0.5*erfc(-gammaz/sqrt(2)); \n\ntry\n z = sum(bsxfun(@times,hypw(~isnan(hypw)),z(~isnan(hypw),:)),1);\ncatch\n z = Inf(1,n);\n dz = NaN(n,size(xi,2));\n return;\nend\n\nif grad_flag\n % Gradient of probability of improvement\n dfs = 0.5*dfs2./fs;\n dgammaz = -(dfmu.*fs + (target - fmu).*dfs)./fs2;\n dz = 0.5*dgammaz/sqrt(2)*(-2*exp(-gammaz.^2/2)/sqrt(pi));\n \n dz = sum(bsxfun(@times,hypw,dz(~isnan(hypw),:)),1); \nelse\n dz = NaN(n,size(xi,2)); % Gradient not estimated\nend\n\nend", "meta": {"author": "acerbilab", "repo": "bads", "sha": "019f0b432b9e157a31defbbd303aadcdf57862e7", "save_path": "github-repos/MATLAB/acerbilab-bads", "path": "github-repos/MATLAB/acerbilab-bads/bads-019f0b432b9e157a31defbbd303aadcdf57862e7/acq/acqNegPI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6835451045894003}} {"text": "function R = create_2d_image_resize_matrix(insz, outsz)\n t1 = (insz(1) - outsz(1)) * repmat(linspace(0, 1, outsz(1))', [1, outsz(2)]);\n t2 = (insz(2) - outsz(2)) * repmat(linspace(0, 1, outsz(2)), [outsz(1), 1]);\n% R = create_2d_bicubic_interp_matrix(cat(3, t1, t2), insz);\n% R = create_2d_bicubic_interp_matrix(cat(3, t1, t2), insz);\n R = create_2d_bilinear_interp_matrix(cat(3, t1, t2), insz);\nend", "meta": {"author": "visva89", "repo": "pTVreg", "sha": "c359620e3c8435392db02354274d6c74d682d437", "save_path": "github-repos/MATLAB/visva89-pTVreg", "path": "github-repos/MATLAB/visva89-pTVreg/pTVreg-c359620e3c8435392db02354274d6c74d682d437/mutils/My/deformation_tools_cpp/create_2d_image_resize_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509862, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6835451010822791}} {"text": "clear; clc;\n%P2.13\nnx = 0:3; % Index for sequence x(n)\nx = 1:4; % Sequence x(n) = {1,2,3,4}\nnh = 0:2; % Index for impulse h(n)\nh = 3:-1:1; % Sequence h(n) = {3,2,1}\n[y,ny] = conv_m(x,nx,h,nh); % Linear Convolution y(n) = h(n)*x(n)\nhtilde = [h';zeros(size(x)-[0,1])'];\n%m = 0:length(htilde)-1;\nHcol = zeros(size(x)+size(h)-[1,1])';\nH = htilde;\nfor k = 1:length(x)-1,\n Hcol=circshift(htilde,k);\n H=[H,Hcol];\nend\nytilde = H*x'; %Performs convolution using Toeplitz matrix", "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/16323-ingle-proakis-chapter-2-solutions/P213.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6835268326621118}} {"text": "function [ H] = Hmatrix( Ix, Iy, SizeBig, alfa )\n\n%At each pyramid level, this function generates the Hessian matrix for the\n%source image\n \nH = zeros([2 2 size(Ix)-SizeBig]);\n\nfor i = 1+SizeBig : size(Ix,1)-SizeBig \n for j = 1+SizeBig : size(Ix,2)-SizeBig \n \n ix = Ix( i-SizeBig:i+SizeBig, j-SizeBig:j+SizeBig ); \n iy = Iy( i-SizeBig:i+SizeBig, j-SizeBig:j+SizeBig );\n H(1,1,i,j) = alfa+sum(sum( ix.^2 )); \n H(2,2,i,j) = alfa+sum(sum( iy.^2 )); \n H(1,2,i,j) = sum(sum( ix .* iy )); \n H(2,1,i,j) = H(1,2,i,j);\n \n end\nend\n\n\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/23142-iterative-pyramidal-lk-optical-flow/LKpyramid Codes/LKpyramid Codes/Hmatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6835268143617593}} {"text": "function h = p25_h ( n, x )\n\n%*****************************************************************************80\n%\n%% P25_H evaluates the Hessian for problem 25.\n%\n% Discussion:\n%\n% Note that, for P = 0, the Hessian matrix should be diagonal.\n% However, if it is estimated using finite differences, off diagonal\n% terms may appear. This occurs when the argument increment dX is\n% too small to be significant in terms such as X**6.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 December 2000\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the values of the variables.\n%\n% Output, real H(N,N), the N by N Hessian matrix.\n%\n h = zeros ( n, n );\n\n for i = 1 : n\n h(i,i) = i * 12.0 * x(i)^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/test_opt/p25_h.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6835139582897926}} {"text": "function fadingcoeff=genh(I,v,Dop,tb)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% %\n%% Name: genh.m %\n%% %\n%% Description: We generate a unique coefficient of fading with \"sum %\n%% of sinusoides\" of the Jakes model. %\n%% %\n%% Parameters: %\n%% I = Length of the plot %\n%% v = Speed of the terminal (m/s) %\n%% Dop = Maximum frequency of the Doppler effect %\n%% tb = Symbol Duration %\n%% %\n%% Authors: Bertrand Muquet, Sebastien Simoens, Shengli Zhou %\n%% October 2000 %\n%% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n fc = 2.3e9; \t\t\t% Carrier Frequency in Hertz (2.5GHz 3.2GHz)\n fdmax = Dop; \n \n N = 100; % Number of incident waves\n t = tb:tb:tb*I; % The variable \"time\"\n\n len = length(t);\n theta = rand(1,N)*2*pi; % Generating the uniform phases\n fd = cos(2*pi*((1:N)/N))*fdmax; % Generate eqaul-spaced frequencies from \"-fdmax\" to \"+fdmax\"\n \n \n E = exp(j.*(2*pi*fd(:)*t(:)'+repmat(theta(:),1,len)));\n E = E/sqrt(N);\n fadingcoeff = sum(E);\n %plot(t,abs(fadingcoeff))\n %xlabel('time (second)');ylabel('Envelope of the fading coefficient');", "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/21494-a-802-16d-system-comments-on-english/genh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013355, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6834942677313762}} {"text": "% sga\n%\n% This script implements the Simple Genetic Algorithm described\n% in the examples section of the GA Toolbox manual.\n%\n\n% Author: Andrew Chipperfield\n% History: 23-Mar-94 file created\n \n\nNIND = 40; % Number of individuals per subpopulations\nMAXGEN = 300; % maximum Number of generations\nGGAP = .9; % Generation gap, how many new individuals are created\nNVAR = 20; % Generation gap, how many new individuals are created\nPRECI = 20; % Precision of binary representation\n\n% Build field descriptor\n FieldD = [rep([PRECI],[1, NVAR]); rep([-512;512],[1, NVAR]);...\n rep([1; 0; 1 ;1], [1, NVAR])];\n\n% Initialise population\n Chrom = crtbp(NIND, NVAR*PRECI);\n\n% Reset counters\n Best = NaN*ones(MAXGEN,1);\t% best in current population\n gen = 0;\t\t\t% generational counter\n\n% Evaluate initial population\n ObjV = objfun1(bs2rv(Chrom,FieldD));\n\n% Track best individual and display convergence\n Best(gen+1) = min(ObjV);\n plot(log10(Best),'ro');xlabel('generation'); ylabel('log10(f(x))');\n text(0.5,0.95,['Best = ', num2str(Best(gen+1))],'Units','normalized'); \n drawnow; \n\n\n% Generational loop\n while gen < MAXGEN,\n\n % Assign fitness-value to entire population\n FitnV = ranking(ObjV);\n\n % Select individuals for breeding\n SelCh = select('sus', Chrom, FitnV, GGAP);\n\n % Recombine selected individuals (crossover)\n SelCh = recombin('xovsp',SelCh,0.7);\n\n % Perform mutation on offspring\n SelCh = mut(SelCh);\n\n % Evaluate offspring, call objective function\n ObjVSel = objfun1(bs2rv(SelCh,FieldD));\n\n % Reinsert offspring into current population\n [Chrom ObjV]=reins(Chrom,SelCh,1,1,ObjV,ObjVSel);\n\n % Increment generational counter\n gen = gen+1;\n\n % Update display and record current best individual\n Best(gen+1) = min(ObjV);\n plot(log10(Best),'ro'); xlabel('generation'); ylabel('log10(f(x))');\n text(0.5,0.95,['Best = ', num2str(Best(gen+1))],'Units','normalized');\n drawnow;\n end \n% End of GA\n\u001a", "meta": {"author": "sfvsfv", "repo": "Mathematical-modeling", "sha": "cef1a3688246851f067777b3599b1b3831d3d948", "save_path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling", "path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling/Mathematical-modeling-cef1a3688246851f067777b3599b1b3831d3d948/\u7f8e\u8d5bA\u9898\u5e38\u89c1\u4ee3\u7801/\u591a\u79cd\u7fa4\u9057\u4f20\u7b97\u6cd5\u7684\u51fd\u6570\u4f18\u5316\u7b97\u6cd5\u4ee3\u7801/gatbx/sga.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7577943767446201, "lm_q1q2_score": 0.6834704209393454}} {"text": "function [count] = countall3graphlets(L)\n\n% Count all 3-node subgraphs in an undirected graph\n% without node labels and with unweighted edges\n% Author: Nino Shervashidze - nino.shervashidze@tuebingen.mpg.de\n% Copyright 2012 Nino Shervashidze\n% Input: L - 1xn cell array - adjacency list\n% Output: count - 1x4 vector of integers. count(i)= number of graphlets with \n% 3-i+1 edges (see 3graphlets.pdf)\n\nn=length(L); % number of nodes\ncount=zeros(1,4);\nw=[1/6, 1/4, 1/2];\nfor v1=1:n\n for v2=L{v1}\n cardinalities=card_inter(L{v1}, L{v2}, length(L{v1}), length(L{v2}));\n count(1)=count(1)+w(1)*cardinalities(3);\n count(2)=count(2)+w(2)*(cardinalities(1)+cardinalities(2)-2);\n count(3)=count(3)+w(3)*(n-sum(cardinalities));\n end\nend\ncount(4)=n*(n-1)*(n-2)/6-sum(count(1:3));\nend\n\nfunction [n] = card_inter(o_set1, o_set2, l1, l2)\n% Find the cardinality of the intersection of two ordered sets of lengths l1 and l2 respectively\n% n(1)=o_set1\\o_set2, n(2)=o_set2\\o_set1, n(3)=(o_set2 inter o_set1)\nn=zeros(1,3);\ni=1; j=1;\n\nwhile i<=l1 && j <=l2\n if o_set1(i)o_set2(j) n(2)=n(2)+1; j=j+1;\n else i=i+1; j=j+1; n(3)=n(3)+1;\n end\n end\nend\nn(1)=n(1)+l1-i+1;\nn(2)=n(2)+l2-j+1;\nend\n", "meta": {"author": "muhanzhang", "repo": "DGCNN", "sha": "7d3663b49561e57fe518f37af0023a364285eee1", "save_path": "github-repos/MATLAB/muhanzhang-DGCNN", "path": "github-repos/MATLAB/muhanzhang-DGCNN/DGCNN-7d3663b49561e57fe518f37af0023a364285eee1/software/graphkernels/unlabeled/allgraphlets/countall3graphlets.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.683470415067926}} {"text": "function [ids, ids_com] = pickRandomSubsetIndex(n, k)\n\t%% ================== File info ==========================\n\t% Author\t\t: Tiep Vu (http://www.personal.psu.edu/thv102/)\n\t% Time created\t: Tue Jan 26 22:59:40 2016\n\t% Last modified\t: Tue Jan 26 22:59:41 2016\n\t% Description\t: pick a k-element subset of the set 1: n \n\t% \tINPUT:\n\t%\t\tn: number of elements\n\t%\t\tk: number of picked elements\n\t% \tOUTPUT: \n\t%\t\tids: vector of picked indices \n\t% \t\tids_com: vector of unpicked indices\n\t%\n\t%% ================== end File info ==========================\n id_mixed = randperm(n);\n ids = id_mixed(1: k);\n if nargout == 2 \n \tids_com = setdiff(1:n, ids);\n end \nend ", "meta": {"author": "tiepvupsu", "repo": "DICTOL", "sha": "1a0361aa35c32d70525d06910d0e9b87997ff246", "save_path": "github-repos/MATLAB/tiepvupsu-DICTOL", "path": "github-repos/MATLAB/tiepvupsu-DICTOL/DICTOL-1a0361aa35c32d70525d06910d0e9b87997ff246/utils/pickRandomSubsetIndex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.6834524045740124}} {"text": "function [vdiv,vcurl]=crldivxyz(vx,vy,vz)\n% [vdiv,vcurl]=crldivxyz(vx,vy,vz)\n% computes the divergence and curl of a\n% vector expressed in x,y,z coordinates\nsyms x y z real\nif ischar(vx), vx=sym(vx); end\nif ischar(vy), vy=sym(vy); end\nif ischar(vz), vz=sym(vz); end\nvdiv=diff(vx,x)+diff(vy,y)+diff(vz,z);\ncx=diff(vz,y)-diff(vy,z); \ncy=diff(vx,z)-diff(vz,x); \ncz=diff(vy,x)-diff(vx,y); \nvcurl=[cx;cy;cz];", "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/15903-curvilinear-coordinates/cc/crldivxyz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.683448910488489}} {"text": "function [ center, radii, evecs, v, chi2 ] = ellipsoid_fit_new( X, equals )\n%\n% Fit an ellispoid/sphere/paraboloid/hyperboloid to a set of xyz data points:\n%\n% [center, radii, evecs, pars ] = ellipsoid_fit( X )\n% [center, radii, evecs, pars ] = ellipsoid_fit( [x y z] );\n% [center, radii, evecs, pars ] = ellipsoid_fit( X, 1 );\n% [center, radii, evecs, pars ] = ellipsoid_fit( X, 2, 'xz' );\n% [center, radii, evecs, pars ] = ellipsoid_fit( X, 3 );\n%\n% Parameters:\n% * X, [x y z] - Cartesian data, n x 3 matrix or three n x 1 vectors\n% * flag - '' or empty fits an arbitrary ellipsoid (default),\n% - 'xy' fits a spheroid with x- and y- radii equal\n% - 'xz' fits a spheroid with x- and z- radii equal\n% - 'xyz' fits a sphere\n% - '0' fits an ellipsoid with its axes aligned along [x y z] axes\n% - '0xy' the same with x- and y- radii equal\n% - '0xz' the same with x- and z- radii equal\n%\n% Output:\n% * center - ellispoid or other conic center coordinates [xc; yc; zc]\n% * radii - ellipsoid or other conic radii [a; b; c]\n% * evecs - the radii directions as columns of the 3x3 matrix\n% * v - the 10 parameters describing the ellipsoid / conic algebraically: \n% Ax^2 + By^2 + Cz^2 + 2Dxy + 2Exz + 2Fyz + 2Gx + 2Hy + 2Iz + J = 0\n% * chi2 - residual sum of squared errors (chi^2), this chi2 is in the \n% coordinate frame in which the ellipsoid is a unit sphere.\n%\n% Author:\n% Yury Petrov, Oculus VR\n% Date:\n% September, 2015\n%\n\n%reference \nnarginchk( 1, 3 ) ; % check input arguments\nif nargin == 1\n equals = ''; % no constraints by default\nend\n \nif size( X, 2 ) ~= 3\n error( 'Input data must have three columns!' );\nelse\n x = X( :, 1 );\n y = X( :, 2 );\n z = X( :, 3 );\nend\n\n% need nine or more data points\nif length( x ) < 9 && strcmp( equals, '' ) \n error( 'Must have at least 9 points to fit a unique ellipsoid' );\nend\nif length( x ) < 8 && ( strcmp( equals, 'xy' ) || strcmp( equals, 'xz' ) )\n error( 'Must have at least 8 points to fit a unique ellipsoid with two equal radii' );\nend\nif length( x ) < 6 && strcmp( equals, '0' )\n error( 'Must have at least 6 points to fit a unique oriented ellipsoid' );\nend\nif length( x ) < 5 && ( strcmp( equals, '0xy' ) || strcmp( equals, '0xz' ) )\n error( 'Must have at least 5 points to fit a unique oriented ellipsoid with two equal radii' );\nend\nif length( x ) < 4 && strcmp( equals, 'xyz' );\n error( 'Must have at least 4 points to fit a unique sphere' );\nend\n\n% fit ellipsoid in the form Ax^2 + By^2 + Cz^2 + 2Dxy + 2Exz + 2Fyz + 2Gx +\n% 2Hy + 2Iz + J = 0 and A + B + C = 3 constraint removing one extra\n% parameter\nif strcmp( equals, '' )\n D = [ x .* x + y .* y - 2 * z .* z, ...\n x .* x + z .* z - 2 * y .* y, ...\n 2 * x .* y, ...\n 2 * x .* z, ...\n 2 * y .* z, ...\n 2 * x, ...\n 2 * y, ...\n 2 * z, ...\n 1 + 0 * x ]; % ndatapoints x 9 ellipsoid parameters\nelseif strcmp( equals, 'xy' )\n D = [ x .* x + y .* y - 2 * z .* z, ...\n 2 * x .* y, ...\n 2 * x .* z, ...\n 2 * y .* z, ...\n 2 * x, ...\n 2 * y, ...\n 2 * z, ...\n 1 + 0 * x ]; % ndatapoints x 8 ellipsoid parameters\nelseif strcmp( equals, 'xz' )\n D = [ x .* x + z .* z - 2 * y .* y, ...\n 2 * x .* y, ...\n 2 * x .* z, ...\n 2 * y .* z, ...\n 2 * x, ...\n 2 * y, ...\n 2 * z, ...\n 1 + 0 * x ]; % ndatapoints x 8 ellipsoid parameters\n % fit ellipsoid in the form Ax^2 + By^2 + Cz^2 + 2Gx + 2Hy + 2Iz = 1\nelseif strcmp( equals, '0' )\n D = [ x .* x + y .* y - 2 * z .* z, ...\n x .* x + z .* z - 2 * y .* y, ...\n 2 * x, ...\n 2 * y, ... \n 2 * z, ... \n 1 + 0 * x ]; % ndatapoints x 6 ellipsoid parameters\n % fit ellipsoid in the form Ax^2 + By^2 + Cz^2 + 2Gx + 2Hy + 2Iz = 1,\n % where A = B or B = C or A = C\nelseif strcmp( equals, '0xy' )\n D = [ x .* x + y .* y - 2 * z .* z, ...\n 2 * x, ...\n 2 * y, ... \n 2 * z, ... \n 1 + 0 * x ]; % ndatapoints x 5 ellipsoid parameters\nelseif strcmp( equals, '0xz' )\n D = [ x .* x + z .* z - 2 * y .* y, ...\n 2 * x, ...\n 2 * y, ... \n 2 * z, ... \n 1 + 0 * x ]; % ndatapoints x 5 ellipsoid parameters\n % fit sphere in the form A(x^2 + y^2 + z^2) + 2Gx + 2Hy + 2Iz = 1\nelseif strcmp( equals, 'xyz' )\n D = [ 2 * x, ...\n 2 * y, ... \n 2 * z, ... \n 1 + 0 * x ]; % ndatapoints x 4 ellipsoid parameters\nelse\n error( [ 'Unknown parameter value ' equals '!' ] );\nend\n\n% solve the normal system of equations\nd2 = x .* x + y .* y + z .* z; % the RHS of the llsq problem (y's)\nu = ( D' * D ) \\ ( D' * d2 ); % solution to the normal equations\n\n% find the residual sum of errors\n% chi2 = sum( ( 1 - ( D * u ) ./ d2 ).^2 ); % this chi2 is in the coordinate frame in which the ellipsoid is a unit sphere.\n\n% find the ellipsoid parameters\n% convert back to the conventional algebraic form\nif strcmp( equals, '' )\n v(1) = u(1) + u(2) - 1;\n v(2) = u(1) - 2 * u(2) - 1;\n v(3) = u(2) - 2 * u(1) - 1;\n v( 4 : 10 ) = u( 3 : 9 );\nelseif strcmp( equals, 'xy' )\n v(1) = u(1) - 1;\n v(2) = u(1) - 1;\n v(3) = -2 * u(1) - 1;\n v( 4 : 10 ) = u( 2 : 8 );\nelseif strcmp( equals, 'xz' )\n v(1) = u(1) - 1;\n v(2) = -2 * u(1) - 1;\n v(3) = u(1) - 1;\n v( 4 : 10 ) = u( 2 : 8 );\nelseif strcmp( equals, '0' )\n v(1) = u(1) + u(2) - 1;\n v(2) = u(1) - 2 * u(2) - 1;\n v(3) = u(2) - 2 * u(1) - 1;\n v = [ v(1) v(2) v(3) 0 0 0 u( 3 : 6 )' ];\n\nelseif strcmp( equals, '0xy' )\n v(1) = u(1) - 1;\n v(2) = u(1) - 1;\n v(3) = -2 * u(1) - 1;\n v = [ v(1) v(2) v(3) 0 0 0 u( 2 : 5 )' ];\nelseif strcmp( equals, '0xz' )\n v(1) = u(1) - 1;\n v(2) = -2 * u(1) - 1;\n v(3) = u(1) - 1;\n v = [ v(1) v(2) v(3) 0 0 0 u( 2 : 5 )' ];\nelseif strcmp( equals, 'xyz' )\n v = [ -1 -1 -1 0 0 0 u( 1 : 4 )' ];\nend\nv = v';\n\n% form the algebraic form of the ellipsoid\nA = [ v(1) v(4) v(5) v(7); ...\n v(4) v(2) v(6) v(8); ...\n v(5) v(6) v(3) v(9); ...\n v(7) v(8) v(9) v(10) ];\n% find the center of the ellipsoid\ncenter = -A( 1:3, 1:3 ) \\ v( 7:9 );\n% form the corresponding translation matrix\nT = eye( 4 );\nT( 4, 1:3 ) = center';\n% translate to the center\nR = T * A * T';\n% solve the eigenproblem\n[ evecs, evals ] = eig( R( 1:3, 1:3 ) / -R( 4, 4 ) );\nradii = sqrt( 1 ./ diag( abs( evals ) ) );\nsgns = sign( diag( evals ) );\nradii = radii .* sgns;\n\n% calculate difference of the fitted points from the actual data normalized by the conic radii\nd = [ x - center(1), y - center(2), z - center(3) ]; % shift data to origin\nd = d * evecs; % rotate to cardinal axes of the conic;\nd = [ d(:,1) / radii(1), d(:,2) / radii(2), d(:,3) / radii(3) ]; % normalize to the conic radii\nchi2 = sum( abs( 1+0*x - sum( d.^2, 2 ) ) );\n \nif abs( v(end) ) > 1e-6\n v = -v / v(end); % normalize to the more conventional form with constant term = -1\nelse\n v = -sign( v(end) ) * v;\nend\n\n\n\n\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/lib/calbiration/ellipsoid_fit_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6834488980682465}} {"text": "function r = sinvchi2rand(nu, s2, M, N)\n% SINVCHI2RAND Random matrices from scaled inverse-chi distribution\n%\n% R = SINVCHI2RAND(NU, S2)\n% R = SINVCHI2RAND(NU, S2, M, N)\n%\n% Returns a randon number/matrix R from scaled inverse-chi square \n% distribution. Nu is the degrees of freedom and S2 is the scale \n% squared. Parametrisation is according to Gelman et. al. (2004).\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 < 2\n error('Too few arguments');\nend\nif nargin==2\n [M,N]=size(s2);\nelse\n if numel(s2)>1 || numel(nu)>1\n error('Arguments M and N can only be used if nu and s2 are scalars');\n end\n if nargin < 4\n N=1;\n end\nend\nr=nu.*s2./chi2rnd(nu,M,N);\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/sinvchi2rand.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110511888304, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6833891441196082}} {"text": "function [n,f,a,b]=lpcar2fm(ar,t)\n%LPCAR2RF Convert autoregressive coefficients to formant freq+amp+bw [N,F,A,B]=(AR,T)\n%\n% Input: ar(:,p+1) Autoregressive coefficients\n% t Threshold (see below)\n% Output: n Number of formants found\n% f Formant frequencies in normalized Hz (in increasing order)\n% a Formant amplitudes\n% b Formant bandwidths in normalized Hz\n%\n% The number of columns in the output arrays f, a and b is max(n); surplus positions\n% in any given row have f=b=0.\n%\n% In determining formants, poles are ignored if any of the following hold:\n% (a) they are on the real axis\n% (b) they have bandwidth > t*frequency (if t>0)\n% (c) they have bandwidth > -t (if t<=0)\n\n% Copyright (C) Mike Brookes 1997\n% Version: $Id: lpcar2fm.m 713 2011-10-16 14:45:43Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\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 can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[nf,p1]=size(ar);\np=p1-1;\nd=(1:nf)';\nzz=lpcar2zz(ar);\nig=imag(zz)<=0;\nn=p1-1-sum(ig,2);\nmn=max(n);\n\n% remove redundant columns\n\nif mn 1\n if t>0\n ig=ig | b>t*f;\n else\n ig=ig | b+t>0;\n end\nend\nf(ig)=0;\nb(ig)=0;\nn=mn-sum(ig,2);\nm=max(n);\n\n% remove redundant columns\n\n[igf,ix]=sort(ig+f,2);\ndd=d(:,ones(1,m))+nf*(ix(:,1:m)-1);\nzz=reshape(zz(dd),nf,m);\nf=reshape(f(dd),nf,m);\nb=reshape(b(dd),nf,m);\nig=reshape(ig(dd),nf,m);\n\n% now calculate gain\nap=permute(ar,[1 3 2]);\npw=permute(-2*pi*1i*(0:p),[1 3 2]);\na=abs(sum(ap(:,ones(1,m),:).*exp(pw(ones(1,nf),ones(1,m),:).*f(:,:,ones(1,p1))),3)).^(-1);\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/lpcar2fm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110483133801, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6833891323965688}} {"text": "function [dst,shear_f]=nsst_dec1e(x,shear_parameters,lpfilt)\n% This function computes the (local) nonsubsampled shearlet transform as given\n% in G. Easley, D. Labate and W. Lim, \"Sparse Directional Image Representations\n% using the Discrete Shearlet Transform\", Appl. Comput. Harmon. Anal. 25 pp.\n% 25-46, (2008). This is the more efficient version. Efficiency increases\n% if shearing filters (shear_f) are previously stored. \n%\n% Inputs:\n%\n% x - input image \n%\n% shear_parameters has the following fields:\n%\n% shear_parameters.dcomp - a vector such that .dcomp(i) indicates that the\n% ith decomposition level has 2^decomp(i)\n% directions. The length of the vector plus 1 is\n% total the number of decompostions. \n%\n% shear_parameters.dsize - a vector indicating the local support of the \n% shearing filter is .dsize(i) for 2^dcomp(i)\n% directions. This vector is same size as .dcomp.\n%\n% lpfilt - lpfilt is the filter to be used for the Laplacian\n% Pyramid/ATrous decomposition using the codes\n% written by Arthur L. Cunha\n%\n% Output:\n%\n% dst - the cell array containing the discrete shearlet \n% tranform coefficients\n%\n% Code contributors: Glenn R. Easley, Demetrio Labate, and Wang-Q Lim.\n% Copyright 2011 by Glenn R. Easley. All Rights Reserved.\n%\n\n[L,L]=size(x);\nlevel=length(shear_parameters.dcomp);\n\n% LP decomposition\ny = atrousdec(x,lpfilt,level);\n\ndst = cell(1,level+1);\ndst{1}=y{1}; % assign low-pass coefficients to first decomposition index\n\nshear_f=cell(1,level); % declare cell array containing shearing filters\nfor i=1:level, \n shear_f{i}=shearing_filters_Myer(shear_parameters.dsize(i),shear_parameters.dcomp(i)).*sqrt(shear_parameters.dsize(i));\n for k=1:2^shear_parameters.dcomp(i),\n dst{i+1}(:,:,k)=conv2(y{i+1},shear_f{i}(:,:,k),'same');\n end\nend\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/Shearlet/Toolbox/nsst_dec1e.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6833891283426111}} {"text": "function errors = test_gsp_estimate_vertex_time_psd\n \nerrors = 0;\n\n%Time parameter\nT = 200;fs=1;\n% Graph parameters\nN = 100;\n%Graph\nG = gsp_sensor(N);\n% G1 = gsp_2dgrid(10);\nG = gsp_jtv_graph(G,T,fs);\nG = gsp_compute_fourier_basis(G);\n\n\n%wave filter\nalpha=1;\nbeta = 0.7;\n[g, ft] = gsp_jtv_design_damped_wave(G, alpha,beta);\n\n\nNx = 5;\nx2 = (rand(N,T,1,Nx)>0.99).*randn(N,T,1,Nx);\nX2 = gsp_jtv_filter_synthesis(G,g,ft,x2);\n\nparam.L = 100;\nparam.use_fast = 0;\nt1 = tic;\nparam.estimator = 'TVA';\npsd_TVA1 = gsp_estimate_vertex_time_psd(G,X2,param);\ntime1 = toc(t1)\n\nt2 = tic;\nparam.estimator = 'TVA';\nparam.use_fast = 1;\npsd_TVA2 = gsp_estimate_vertex_time_psd(G,X2,param);\ntime2 = toc(t2)\n\nA1 = gsp_filter_evaluate(psd_TVA1,G.e);\nA2 = gsp_filter_evaluate(psd_TVA2,G.e);\n\ngsp_assert_test(A1,A2,1e-10,'ESTIMATE_PSD: TVA')\n\n\n\nend", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/test_gsptoolbox/test_gsp_estimate_vertex_time_psd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6833891254333293}} {"text": "function h=m_range_ring(long,lat,range,varargin)\n% M_RANGE_RING Creates range rings on a map\n% M_RANGE_RING(LONG,LAT,RANGE) creates a range ring of range RANGE\n% km centered at the position specified by LONG and LAT. Range rings\n% will generally appear as small (almost) circles for short ranges,\n% but will be distorted at longer ranges.\n%\n% If RANGE is a vector, concentric rings at the specified ranges\n% are drawn. If LONG,LAT are vectors, rings are drawn around\n% all specified locations.\n%\n% The appearance of lines can be modified using the usual\n% line properties thus:\n% M_RANGE_RING(LONG,LAT,RANGE, )\n%\n% Sometimes you may need to adjust the number of points plotted\n% in each range ring (this can happen if the ring is at the extreme\n% edge of certian projections). THis can be done using\n% M_RANGE_RING(LONG,LAT,RANGE,NPTS, )\n%\n% NB: Earth radius is assumed to 6378.137km (WGS-84 value), and\n% calculations are for spherical geometry.\n\n% Rich Pawlowicz (rich@ocgy.ubc.ca) 18/Dec/1998\n%\n% This software is provided \"as is\" without warranty of any kind. But\n% it's mine, so you can't sell it.\n\n% 6/Nov/00 - eliminate returned stuff if ';' neglected (thx to D Byrne)\n\nglobal MAP_VAR_LIST\n\npi180=pi/180;\nearth_radius=6378.137;\nn=72;\n\nif ~isempty(varargin) && ~ischar(varargin{1})\n n=varargin{1};varargin(1)=[];\nend\n\n\n\nc=range(:)'/earth_radius;\n\nh=[];\nfor k=1:length(long)\n rlat=lat(k)*pi180;\n rlong=long(k)*pi180;\n if long(k)MAP_VAR_LIST.longs(2), rlong=rlong-2*pi; end\n\n x=sin([0:n-1]'/(n-1)*2*pi)*c;\n y=cos([0:n-1]'/(n-1)*2*pi)*c;\n on=ones(n,1);\n\n Y=(asin(on*cos(c)*sin(rlat) + (on*cos(rlat)*(sin(c)./c)).*y))/pi180;\n switch lat(k)\n case 90\n X=(rlong+atan2(x,-y))/pi180;\n case -90\n X=(rlong+atan2(x,y))/pi180;\n otherwise\n X=(rlong+atan2(x.*(on*sin(c)),on*(cos(rlat)*cos(c).*c) - (on*sin(rlat)*sin(c)).*y ) )/pi180;\n end\n\n nz=zeros(1,length(range(:)));\n X=X+cumsum([nz;diff(X)<-300]-[nz;diff(X)>300])*360;\n\n kk=find(X(1,:)~=X(end,:));\n X2=X(:,kk)+360;X2(X2>MAP_VAR_LIST.longs(2))=NaN;\n X3=X(:,kk)-360;X3(X3-0.1');\nfigure\nplotmesh(node,elem,'x>0 | y>0');\nfigure;\nplotmesh(node,face,'x>0 | y>0');\n", "meta": {"author": "fangq", "repo": "iso2mesh", "sha": "556f4c321467a3ee042d4c559b4edc11e01dc574", "save_path": "github-repos/MATLAB/fangq-iso2mesh", "path": "github-repos/MATLAB/fangq-iso2mesh/iso2mesh-556f4c321467a3ee042d4c559b4edc11e01dc574/sample/demo_directplc_ex1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.6833606561889611}} {"text": "function swave=smoothwavelet(wave,dt,period,dj,scale)\n% Smoothing as in the appendix of Torrence and Webster \"Inter decadal changes in the ENSO-Monsoon System\" 1998\n%\n% used in wavelet coherence calculations\n%\n%\n% Only applicable for the Morlet wavelet.\n%\n% (C) Aslak Grinsted 2002-2014\n% http://www.glaciology.net/wavelet-coherence\n\n% -------------------------------------------------------------------------\n%The MIT License (MIT)\n%\n%Copyright (c) 2014 Aslak Grinsted\n%\n%Permission is hereby granted, free of charge, to any person obtaining a copy\n%of this software and associated documentation files (the \"Software\"), to deal\n%in the Software without restriction, including without limitation the rights\n%to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n%copies of the Software, and to permit persons to whom the Software is\n%furnished to do so, subject to the following conditions:\n%\n%The above copyright notice and this permission notice shall be included in\n%all copies or substantial portions of the Software.\n%\n%THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n%IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n%FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n%AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n%LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n%OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n%THE SOFTWARE.\n%---------------------------------------------------------------------------\n\n\n% TODO: take mother argument\n%\n\n\nn=size(wave,2);\n\n%swave=zeros(size(wave));\ntwave=zeros(size(wave));\n\n% %filter in time:....\n% for i=1:size(wave,1)\n% sc=period(i)/dt; % time/cycle / time/sample = samples/cycle\n% t=(-round(sc*3):round(sc*3))*dt;\n% f=exp(-t.^2/(2*scale(i)^2));\n% f=f/sum(f); %filter must have unit weight\n%\n% smooth=conv(wave(i,:),f); %slowest line of code in the wtcsig calculation. should be done like in wavelet with fft and ifft.\n% cutlen=(length(t)-1)*.5;\n% twave(i,:)=smooth((cutlen+1):(end-cutlen)); %remove paddings\n% end\n%\n%filter in time:....\n%\n% qwave=twave;\n\n%zero-pad to power of 2... Speeds up fft calcs if n is large\nnpad=2.^ceil(log2(n));\n\nk = 1:fix(npad/2);\nk = k.*((2.*pi)/npad);\nk = [0., k, -k(fix((npad-1)/2):-1:1)];\n\nk2=k.^2;\nsnorm=scale./dt;\nfor ii=1:size(wave,1)\n F=exp(-.5*(snorm(ii)^2)*k2); %Thanks to Bing Si for finding a bug here.\n smooth=ifft(F.*fft(wave(ii,:),npad));\n twave(ii,:)=smooth(1:n);\nend\n\nif isreal(wave)\n twave=real(twave); %-------hack-----------\nend\n\n%scale smoothing (boxcar with width of .6)\n\n%\n% TODO: optimize. Because this is done many times in the monte carlo run.\n%\n\n\ndj0=0.6;\ndj0steps=dj0/(dj*2);\n% for ii=1:size(twave,1)\n% number=0;\n% for l=1:size(twave,1);\n% if ((abs(ii-l)+.5)<=dj0steps)\n% number=number+1;\n% swave(ii,:)=swave(ii,:)+twave(l,:);\n% elseif ((abs(ii-l)+.5)<=(dj0steps+1))\n% fraction=mod(dj0steps,1);\n% number=number+fraction;\n% swave(ii,:)=swave(ii,:)+twave(l,:)*fraction;\n% end\n% end\n% swave(ii,:)=swave(ii,:)/number;\n% end\n\nkernel=[mod(dj0steps,1); ones(2 * round(dj0steps)-1,1); ...\n mod(dj0steps,1)]./(2*round(dj0steps)-1+2*mod(dj0steps,1));\nswave=conv2(twave,kernel,'same'); %thanks for optimization by Uwe Graichen\n\n%swave=twave;\n", "meta": {"author": "grinsted", "repo": "wavelet-coherence", "sha": "b8c3925f54c8d113620925070eb1ac572fbcac05", "save_path": "github-repos/MATLAB/grinsted-wavelet-coherence", "path": "github-repos/MATLAB/grinsted-wavelet-coherence/wavelet-coherence-b8c3925f54c8d113620925070eb1ac572fbcac05/smoothwavelet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6833606537276964}} {"text": "function [q,N] = quantile2(X,p,dim,method)\n% Quantiles of a sample via various methods.\n% \n% Q = QUANTILE2(X,P) returns quantiles of the values in X. P is a scalar\n% or a vector of cumulative probability values. When X is a vector, Q is\n% the same size as P, and Q(i) contains the P(i)-th quantile. When X is\n% a matrix, the i-th row of Q contains the P(i)-th quantiles of each\n% column of X. For N-D arrays, QUANTILE2 operates along the first\n% non-singleton dimension.\n% \n% Q = QUANTILE2(X,P,DIM) calculates quantiles along dimension DIM. The\n% DIM'th dimension of Q has length LENGTH(P).\n% \n% Q = QUANTILE2(X,P,DIM,METHOD) calculates quantiles using one of the\n% methods described in http://en.wikipedia.org/wiki/Quantile. The method\n% are designated 'R-1'...'R-9'; the default is R-8 as described in\n% http://bit.ly/1kX4NcT, whereas Matlab uses 'R-5'.\n% \n% Q = QUANTILE2(X,P,DIM,METHOD) calculates quantiles using one of the\n% methods described in http://en.wikipedia.org/wiki/Quantile. The method\n% are designated 'R-1'...'R-9'; the default is 'R-8' as described in\n% http://bit.ly/1kX4NcT, whereas Matlab uses 'R-5'.\n% \n% Q = QUANTILE2(X,P,[],METHOD) uses the specified METHOD, but calculates\n% quantiles along the first non-singleton dimension.\n% \n% [Q,N] = QUANTILE2(...) returns an array that is the same size as Q such\n% that N(i) is the number of points used to calculate Q(i).\n% \n% Further reading\n% \n% Hyndman, R.J.; Fan, Y. (November 1996). \"Sample Quantiles in\n% Statistical Packages\". The American Statistician 50 (4): 361-365.\n% Frigge, Michael; Hoaglin, David C.; Iglewicz, Boris (February 1989).\n% \"Some Implementations of the Boxplot\". The American Statistician 43\n% (1): 50-54.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% LICENSE FILE:\n% -----------------------------------------------------------------------\n% Copyright (c) 2015, Christopher Hummersone\n% All rights reserved.\n% \n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are\n% met:\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% \n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n% POSSIBILITY OF SUCH DAMAGE.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% =========================================================================\n% Last changed: $Date: 2015-06-16 13:50:46 +0100 (Tue, 16 Jun 2015) $\n% Last committed: $Revision: 385 $\n% Last changed by: $Author: ch0022 $\n% =========================================================================\n\n %% Check input and make default assignments\n\n assert(isnumeric(X),'X must be a numeric');\n assert(isvector(p) & isnumeric(p),'P must be a numeric vector');\n assert(all(p>=0 & p<=1),'Values in P must be in the interval [0,1].')\n\n if nargin<2\n error('Not enough input arguments.')\n end\n\n dims = size(X);\n if nargin<3 || isempty(dim)\n dim = find(dims>1,1,'first'); % default dim\n else % validate input\n assert(isnumeric(dim) | isempty(dim),'DIM must be an integer or empty');\n assert(isint(dim) | isempty(dim),'DIM must be an integer or empty');\n assert(dim>0,'DIM must be greater than 0')\n end\n\n if nargin<4\n method = 'r-8'; % default method\n else % validate input\n assert(ischar(method),'METHOD must be a character array')\n end\n\n %% choose method\n\n % See http://en.wikipedia.org/wiki/Quantile#Estimating_the_quantiles_of_a_population\n\n switch lower(method)\n case 'r-1'\n min_con = @(N,p)(p==0);\n max_con = @(N,p)(false);\n h = @(N,p)((N*p)+.5);\n Qp = @(x,h)(x(ceil(h-.5)));\n case 'r-2'\n min_con = @(N,p)(p==0);\n max_con = @(N,p)(p==1);\n h = @(N,p)((N*p)+.5);\n Qp = @(x,h)((x(ceil(h-.5))+x(floor(h+.5)))/2);\n case 'r-3'\n min_con = @(N,p)(p<=(.5/N));\n max_con = @(N,p)(false);\n h = @(N,p)(N*p);\n Qp = @(x,h)(x(round(h)));\n case 'r-4'\n min_con = @(N,p)(p<(1/N));\n max_con = @(N,p)(p==1);\n h = @(N,p)(N*p);\n Qp = @(x,h)(x(floor(h)) + ((h-floor(h))*(x(floor(h)+1)-x(floor(h)))));\n case 'r-5'\n min_con = @(N,p)(p<(.5/N));\n max_con = @(N,p)(p>=((N-.5)/N));\n h = @(N,p)((N*p)+.5);\n Qp = @(x,h)(x(floor(h)) + ((h-floor(h))*(x(floor(h)+1)-x(floor(h)))));\n case 'r-6'\n min_con = @(N,p)(p<(1/(N+1)));\n max_con = @(N,p)(p>=(N/(N+1)));\n h = @(N,p)((N+1)*p);\n Qp = @(x,h)(x(floor(h)) + ((h-floor(h))*(x(floor(h)+1)-x(floor(h)))));\n case 'r-7'\n min_con = @(N,p)(false);\n max_con = @(N,p)(p==1);\n h = @(N,p)(((N-1)*p)+1);\n Qp = @(x,h)(x(floor(h)) + ((h-floor(h))*(x(floor(h)+1)-x(floor(h)))));\n case 'r-8'\n min_con = @(N,p)(p<((2/3)/(N+(1/3))));\n max_con = @(N,p)(p>=((N-(1/3))/(N+(1/3))));\n h = @(N,p)(((N+(1/3))*p)+(1/3));\n Qp = @(x,h)(x(floor(h)) + ((h-floor(h))*(x(floor(h)+1)-x(floor(h)))));\n case 'r-9'\n min_con = @(N,p)(p<((5/8)/(N+.25)));\n max_con = @(N,p)(p>=((N-(3/8))/(N+.25)));\n h = @(N,p)(((N+.25)*p)+(3/8));\n Qp = @(x,h)(x(floor(h)) + ((h-floor(h))*(x(floor(h)+1)-x(floor(h)))));\n otherwise\n error(['Method ''' method ''' does not exist'])\n end\n\n %% calculate quartiles\n\n % reshape data so function works down columns\n order = mod(dim-1:dim+length(dims)-2,length(dims))+1;\n dims_shift = dims(order);\n x = rearrange(X,order,[dims_shift(1) prod(dims_shift(2:end))]);\n\n % pre-allocate q\n q = zeros([length(p) prod(dims_shift(2:end))]);\n N = zeros([length(p) prod(dims_shift(2:end))]);\n for m = 1:length(p)\n for n = 1:numel(q)/length(p)\n x2 = sort(x(~isnan(x(:,n)),n)); % sort\n N(m,n) = length(x2); % sample size\n switch N(m,n)\n case 0\n q(m,n) = NaN;\n case 1\n q(m,n) = x2;\n otherwise\n if min_con(N(m,n),p(m)) % at lower limit\n q(m,n) = x2(1);\n elseif max_con(N(m,n),p(m)) % at upper limit\n q(m,n) = x2(N(m,n));\n else % everything else\n q(m,n) = Qp(x2,h(N(m,n),p(m)));\n end\n end\n end\n end\n\n % restore dims of q to equate to those of input\n q = irearrange(q,order,[length(p) dims_shift(2:end)]);\n N = irearrange(N,order,[length(p) dims_shift(2:end)]);\n\n % if q is a vector, make same shape as p\n if numel(p)==numel(q)\n q=reshape(q,size(p));\n N=reshape(N,size(p));\n end\n\nend\n\nfunction y = isint(x)\n%ISINT check if input is whole number\n y = x==round(x);\nend\n\nfunction y = rearrange(x,order,shape)\n%REARRANGE reshape and permute to make target dim column\n y = permute(x,order);\n y = reshape(y,shape);\nend\n\nfunction y = irearrange(x,order,shape)\n%IREARRANGE reshape and permute to original size\n y = reshape(x,shape);\n y = ipermute(y,order);\nend\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/external/other/quantile2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.6833567834792217}} {"text": "function pC = prtUtilConfusion2PercentCorrect(confusionMat)\n% prtUtilConfusion2PercentCorrect Calculates the percent correct from a confunsion matrix.\n% This is done by summing the percentages allong the diagonal. If the\n% confusion matrix lists number of responses and not percentages, this\n% this is accounted for.\n%\n% Syntax: pC = prtUtilConfusion2PercentCorrect(confusionMat)\n%\n% Inputs:\n% confusionMat - nClass x nClass matrix listing the number of responses \n% for a given truth. Truths are listed vertically moving downward.\n% Responses are listed horizontally moving right.\n%\n% Outputs:\n% pC - The percent correct for the confusion matrix\n%\n% Example 1: \n% Example 2: \n% confusionMat = [4 1 0 0; 0 2 1 0; 0 1 2 1; 0 1 2 3];\n% prtUtilConfusion2PercentCorrect(confusionMat)\n%\n% Other m-files required: none\n% Subfunctions: none\n% MAT-files required: none\n%\n\n\n\n\n\n\n\nif any(~prtUtilIsNaturalNumber(confusionMat(:)))\n error('requires counting number - confusionCountMatrix, not confusionPercentMatrix');\nend\n\nassert(ndims(confusionMat)==2 && size(confusionMat,1)==size(confusionMat,2),'prt:prtUtilConfusion2PercentCorrect:BadInput','prtUtilConfusion2PercentCorrect requires a square confusion matrix. A non square confusion matrix possible implies a mismatch between the true targets and the assigned targets. This is ambiguous.')\n\n% The confusion matrix lists the number of responses not percentages.\n% We must change the matrix to a percentage matrix.\noccurances = repmat(sum(confusionMat,2),1,size(confusionMat,2));\n\n%For normalization, set 0 --> inf; this discounts rows where we had no\n%examples in truth\nnormOccurances = occurances;\nnormOccurances(occurances == 0) = inf;\nconfusionMat = confusionMat./normOccurances;\n\npC = sum(diag(confusionMat).*occurances(:,1))./sum(occurances(:,1));\n\nfunction is = prtUtilIsNaturalNumber(x)\n\nis = (x == round(x) & x >= 0);\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/util/prtUtilConfusion2PercentCorrect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.683356778412083}} {"text": "function value = h_03 ( x )\n\n%*****************************************************************************80\n%\n%% H_03 evaluates x^3+x^2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 April 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the point at which F is to be evaluated.\n%\n% Output, real VALUE, the value of the function at X.\n%\n value = x .* x .* ( x + 1.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/brent/h_03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.6833567777738508}} {"text": "clear; clf;\n\t\t% Incarcarea vetorului x\nx=-2.5:0.01:2.5;\n\t\t% Evaluarea functiei date\ny=funct2(x);\n\t\t% Calcularea aproximativa a derivatei\ndf=diff(y)./diff(x);\n\t\t% Reprezentarea grafica a functiei de derivat \nplot(x,y,'g:')\nhold on\n\t\t% Incarcarea vectorului xd cu n-1 elemente \n\t\t% din vectorul x\nxd=x(2:length(x));\n\t\t% Reprezentarea grafica a derivatei \nplot(xd,df,'m-')\n\t\t% Calcularea elementelor vectorului produs\nprodus=df(1:length(df)-1).*df(2:length(df));\n\t\t% Incarcarea punctelor critice in vectorul minmax\nminmax=xd(find(produs<0));\n\t\t% Evaluarea functiei in punctele critice\nfminmax=y(find(produs<0)+1);\n\t\t% Reprezentarea grafica a maximelor si minimelor\n % locale ale functiei initiale \nplot(minmax,fminmax,'kx','MarkerSize',14)\ngrid on\n % Trasarea liniilor de grid prin punctele gasite\n % - obtinerea valorilor la care se plaseaza \n % liniutele de divizare implicite\nxtick=get(gca,'XTick');\n % - gasirea valorilor minime si maxime ale acestora \nxtickmin=min(xtick); xtickmax=max(xtick);\n % - generarea vectorului noilor linii de divizare pe axa x \nxtick=[xtickmin,minmax,xtickmax];\n % - setarea noilor liniute de divizare \nset(gca,'XTick',xtick);\nset(gca,'YTick',0);\n \t% Plasarea unei legende\nlegend('Functia','Derivata');\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/8416-widely-used-programming-environments-in-electrical-engineering-matlab/9/Ex_9_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564152, "lm_q2_score": 0.7520125793176223, "lm_q1q2_score": 0.6832920938692405}} {"text": "function [densfield] = denserfocalv2(rho,theta,radius)\n% Determine a density field in a stereonet type plot\n%\n% [densfield] = denserfocalv2(rho,theta,radius)\n%\n%input in polar coordinates\n%rho: the distance of the points\n%theta: angle of the points\n%radius: radius of the countercircle, kind of grid size\n%output is a matrix cartesian coordinates (x,y,density)\n\n%get the number of events\ntotalev=length(rho);\nrhotor=rho;\n\n%first do the middle circle (densR=0)\n\n%find the values lower than radius and count\nindi=find(rhotor(:,1)<=radius);\ncounting=length(indi);\n\nif counting>0\n densfield(1,1)=0;\n densfield(1,2)=0;\n densfield(1,3)=counting/totalev;\n rhotor(indi,1)=NaN;\nelse\n densfield(1,3) = NaN;\n densfield(1,1) = 0;\n densfield(1,2) = 0;\nend\n\n\n%set densR to start value radius\ndensR=radius;\n\n%set the counters for the result matrix\nj=2;\n\n%loop for the distance\nwhile densR<=1+radius\n\n %calculate stepwidth for the angle\n dalpha=2*asin(radius/(2*densR));\n\n %set angle to 0\n densalpha=0;\n\n %second loop for the angle\n while densalpha<=2*pi\n %calculate the distance between the middle of the circle and\n %the points\n distery=(rhotor.^2+densR^2-2.*rhotor.*densR.*cos(abs(densalpha-theta))).^0.5;\n\n %find the values lower than radius and count\n indi=find(distery(:,1)<=radius);\n counting=length(indi);\n\n %write values if counting>0\n if counting>0\n densfield(j,3) = counting/totalev;\n densfield(j,1) = densR * cos(densalpha);\n densfield(j,2) = densR * sin(densalpha);\n rhotor(indi,:)=NaN;\n else\n densfield(j,3) = NaN;\n densfield(j,1) = densR * cos(densalpha);\n densfield(j,2) = densR * sin(densalpha);\n\n end\n\n %increase j\n j=j+1;\n %increase densalpha\n densalpha=densalpha+dalpha;\n\n end\n\n %increase densR\n densR=densR+radius;\nend\n\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/jochen/stressinv/denserfocalv2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564152, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.683292088819301}} {"text": "% SUMMARY: This is a Discrete Hidden Markov code\n% This code is inspired by Murphy's PMTK3 toolbox. Using EM\n% algorithm. Details are from PRML\n% AUTHOR: QIUQIANG KONG, Queen Mary University of London\n% Created: 17-09-2015\n% Modified: 17-11-2015\n% Ref Chap 13. \n% -----------------------------------------------------------\n% input\n% Data cell of data\n% state_num state num\n% mix_num multinominal num\n% varargin input:\n% p_start0 p(z1), size: Q*1\n% A p(zn|zn-1), transform matrix, size: Q*Q\n% phi0: emission probability para \n% B p(xn|zn), emission matrix, size: p*Q\n% iter_num how many time the EM should run (default: 100)\n% converge (default: 1+1e-4)\n% output\n% p_start p(z1), dim 1: Q\n% A p(zn|zn-1), transform matrix, size: Q*Q\n% mu p(xn|zn), emission matrix, size: p*Q\n% ===========================================================\nfunction [p_start, A, phi, loglik] = Dhmm(Data, state_num, mix_num, varargin)\nfor i1 = 1:2:length(varargin)\n switch varargin{i1}\n case 'p_start0'\n p_start = varargin{i1+1};\n case 'A0'\n A = varargin{i1+1};\n case 'phi0'\n phi = varargin{i1+1};\n case 'iter_num'\n iter_num = varargin{i1+1};\n case 'converge'\n converge = varargin{i1+1};\n end\nend\nQ = state_num;\nM = mix_num;\nif (~exist('p_start'))\n tmp = rand(1,Q);\n p_start = tmp / sum(tmp);\nend\nif (~exist('A'))\n tmp = rand(Q,Q);\n A = bsxfun(@rdivide, tmp, sum(tmp,2));\nend\nif (~exist('phi'))\n phi.B = ones(M,Q) / M;\nend\nif (~exist('iter_num'))\n iter_num = 100;\nend\nif (~exist('converge'))\n converge = 1 + 1e-4;\nend\n\nobj_num = length(Data); % sequences num\n[M,Q] = size(phi.B); % multimominal num, state num\npre_ll = -inf;\n\nfor k = 1:iter_num\n % E STEP\n for r = 1:obj_num\n logp_xn_given_zn = Discrete_logp_xn_given_zn(Data{r}, phi);\n [LogGamma{r}, LogKsi{r}, Loglik{r}] = LogForwardBackward(logp_xn_given_zn, p_start, A);\n end\n \n % convert loggamma to gamma, logksi to ksi, substract the max\n [Gamma, Ksi] = UniformLogGammaKsi(LogGamma, LogKsi);\n\n % M STEP common\n [p_start, A] = M_step_common(Gamma, Ksi);\n \n % M STEP for Multinominal distribution\n B_numer = zeros(M,Q);\n B_denom = zeros(1,Q);\n for r = 1:obj_num\n xr = Data{r};\n Nr = length(xr);\n Xr = zeros(Nr,M);\n Xr(sub2ind([Nr,M], 1:Nr, xr')) = 1;\n B_numer = B_numer + Xr' * Gamma{r};\n B_denom = B_denom + sum(Gamma{r},1);\n end\n phi.B = bsxfun(@rdivide, B_numer, B_denom);\n \n % calculate loglik\n loglik = 0;\n for r = 1:obj_num\n loglik = loglik + Loglik{r};\n end\n if (loglik-pre_ll1)\n color = color/255;\n end\n line(c(1,:), -c(2,:),'Color',color,'LineWidth',weight);\nelseif strcmp(CB_MAP_OUTPUT, 'java')\n %line(c(1,:), c(2,:),'Color',color,'LineWidth',weight);\n % fill in code\n setDataBezier(mapHandle,c(1,:),c(2,:));\nelseif strcmp(CB_MAP_OUTPUT, 'svg') \n %determine type of color input\n if ischar(color)\n colorStroke = color;\n else if isvector(color)\n colorStroke = strcat('rgb(',num2str(color(1)),',',num2str(color(2)),',',num2str(color(3)),')');\n end\n end\n fprintf(mapHandle,'\\n',colorStroke,ceil(weight));\n% fprintf(mapHandle,'\\n');\n %fprintf(mapHandle,'\\n',p2(1),-p2(2),p2(1),-p2(2),ptemp(1),-ptemp(2),p1(1),-p1(2));\n fprintf(mapHandle,'\\n',p(1,3),p(2,3) ,p(1,3),p(2,3),p(1,2),p(2,2),p(1,1),p(2,1));\n fprintf(mapHandle,'\\n');\nelse\n display('error CB_MAP_OUTPUT in bezier');\nend\n\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/deprecated/_maps_old/tools/drawBezier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6832910895310247}} {"text": "function e = legendre_monomial_quadrature ( n, x, w, p )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_MONOMIAL_QUADRATURE applies a quadrature rule to a monomial.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 February 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of points in the rule.\n%\n% Input, real X(N), the quadrature points.\n%\n% Input, real W(N), the quadrature weights.\n%\n% Input, integer P, the exponent.\n%\n% Output, real E, the quadrature error.\n%\n\n%\n% Get the exact value of the integral.\n%\n t = legendre_integral ( p );\n%\n% Evaluate the monomial at the quadrature points.\n%\n v(1:n,1) = x(1:n).^p;\n%\n% Compute the weighted sum.\n%\n q = w' * v;\n%\n% Error:\n%\n if ( t == 0.0 )\n e = abs ( q - t );\n else\n e = abs ( ( q - t ) / t );\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/cc_project/legendre_monomial_quadrature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.68329107543308}} {"text": "%COMPUTEEXACTMARGINALSBP Runs exact inference and returns the marginals\n%over all the variables (if isMax == 0) or the max-marginals (if isMax == 1). \n%\n% M = COMPUTEEXACTMARGINALSBP(F, E, isMax) takes a list of factors F,\n% evidence E, and a flag isMax, runs exact inference and returns the\n% final marginals for the variables in the network. If isMax is 1, then\n% it runs exact MAP inference, otherwise exact inference (sum-prod).\n% It returns an array of size equal to the number of variables in the \n% network where M(i) represents the ith variable and M(i).val represents \n% the marginals of the ith variable. \n%\n% Copyright (C) Daphne Koller, Stanford University, 2012\n\n\nfunction M = ComputeExactMarginalsBP(F, E, isMax)\n\n% initialization\n% you should set it to the correct value in your code\nM = [];\nvars = unique([F.var]);\n\nN = length(vars);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% YOUR CODE HERE\n%\n% Implement Exact and MAP Inference.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nCliqTree = CreateCliqueTree(F,E);\nP = CliqueTreeCalibrate(CliqTree,isMax);\nM = repmat(struct('var',[],'card',[],'val',[]),1,N);\nfor i = 1:N\n\tfor j = 1:length(CliqTree.cliqueList)\n\t\tinter = intersect(vars(i),CliqTree.cliqueList(j).var);\n\t\tif length(inter)==1\n\t\t\tV = setdiff(CliqTree.cliqueList(j).var,vars(i));\n\t\t\tif isMax == 0\n\t\t\t\tM(i) = FactorMarginalization(P.cliqueList(j),V);\n\t\t\telse\n\t\t\t\tM(i) = FactorMaxMarginalization(P.cliqueList(j),V);\n\t\t\tend\n\t\t\tbreak;\n\t\tend\n\tend\nend\nif isMax==0\nfor i=1:N\n\tM(i).val = M(i).val/sum(M(i).val);\nend\nend\nend\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/4.Exact Inference/ComputeExactMarginalsBP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.6832910676873416}} {"text": "function linplus_test572 ( )\n\n%*****************************************************************************80\n%\n%% TEST572 tests R8SP_MXV, R8SP_VXM.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n m = 7;\n n = 5;\n nz_num = 10;\n col = [ 2, 5, 1, 5, 1, 2, 3, 4, 4, 1 ];\n row = [ 1, 1, 2, 2, 4, 4, 4, 5, 6, 7 ];\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST572\\n' );\n fprintf ( 1, ' R8SP_MXV multiplies a R8SP matrix by a vector;\\n' );\n fprintf ( 1, ' R8SP_VXM multiplies a vector by a R8SP matrix;\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix rows M = %d\\n', m );\n fprintf ( 1, ' Matrix columns N = %d\\n', n );\n fprintf ( 1, ' Matrix nonzeros = %d\\n', nz_num );\n%\n% Set the matrix.\n%\n [ a, seed ] = r8sp_random ( m, n, nz_num, row, col, seed );\n%\n% Make a R8GE copy.\n%\n c = r8sp_to_r8ge ( m, n, nz_num, row, col, a );\n%\n% Print the R8GE copy.\n%\n r8ge_print ( m, n, c, ' The R8SP matrix, in R8GE form:' );\n\n x(1) = 1.0E+00;\n x(2:n-1) = 0.0E+00;\n x(n) = -1.0E+00;\n\n r8vec_print ( n, x, ' The vector x:' );\n\n b = r8sp_mxv ( m, n, nz_num, row, col, a, x );\n\n r8vec_print ( m, b, ' The product A * x:' );\n\n x(1) = 1.0E+00;\n x(2:m-1) = 0.0E+00;\n x(m) = -1.0E+00;\n\n r8vec_print ( m, x, ' The vector x:' );\n\n b = r8sp_vxm ( m, n, nz_num, row, col, a, x );\n\n r8vec_print ( n, b, ' The product A'' * x:' );\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/linplus_test572.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.6832372874399535}} {"text": "function [x,state] = struct_band(z,task,size_mat,band)\n%STRUCT_BAND Band matrix.\n% [x,state] = struct_band(z,[],size_mat,band) generates a band matrix x\n% of size size_mat, where the diagonals band(1) to band(2) are filled\n% column by column with entries from the vector z. For example, if x is a\n% square matrix of order n, the vector z should have length\n% sum(n-abs(band(1):band(2))). The structure state stores information\n% which is reused in computing the right and left Jacobian-vector\n% products.\n%\n% struct_band(z,task,size_mat,band) computes the right or left\n% Jacobian-vector product of this transformation, depending on the\n% structure task. Use the structure state and add the field 'r' of the\n% same shape as z or the field 'l' of the same shape as x to obtain the\n% structure task for computing the right and left Jacobian-vector\n% products\n% \n% (dF(:)/dz(:).')*task.r(:) and\n% (dF(:)/dz(:).')'*task.l(:) + conj((dF(:)/dconj(z(:)).')'*task.l(:)),\n%\n% respectively. Here, F(z) represents this transormation, (:) signifies\n% vectorization and the derivative w.r.t. z (conj(z)) is a partial\n% derivative which treats conj(z) (z) as constant. The output has the\n% same shape as x or z for the right and left Jacobian-vector products,\n% respectively.\n% \n% See also struct_diag, struct_tridiag, struct_tril, struct_triu.\n\n% Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)\n% Marc Van Barel (Marc.VanBarel@cs.kuleuven.be)\n% Lieven De Lathauwer (Lieven.DeLathauwer@kuleuven-kulak.be)\n%\n% References:\n% [1] L. Sorber, M. Van Barel, L. De Lathauwer, \"Structured data fusion,\"\n% ESAT-SISTA Internal Report 13-177, KU Leuven, 2013.\n\nif nargin < 2, task = []; end\nif nargin < 3 || ~isvector(size_mat)\n error('struct_band:size_mat','Missing integer matrix order.');\nend\nif nargin < 4 || ~isvector(band)\n error('struct_band:band','Missing definition of band.');\nend\n\nif isempty(task) || (isempty(task.l) && isempty(task.r))\n state.idx = bsxfun(@plus,(size_mat(1)-1:-1:0).', ...\n (0:size_mat(2)-1)-size_mat(1)+1);\n state.idx = find(state.idx >= band(1) & state.idx <= band(2));\n x = zeros(size_mat);\n x(state.idx) = z;\nelseif ~isempty(task.r)\n x = zeros(size_mat);\n x(task.idx) = task.r;\n state = [];\nelseif ~isempty(task.l)\n x = task.l(task.idx);\n state = [];\nend\n\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/+tensorlab/struct_band.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.6832372755614637}} {"text": "%% Basis Pursuit with Douglas Rachford\n% Test for DR algorithm for L1 minimization (BP).\n% We do here a compressed sensing resolution\n% (random matrix).\n\n%%\n% Add the toolbox.\n\naddpath('../');\naddpath('../toolbox/');\n\n%% \n% Dimensionality of the signal and number of measurements.\n\nn = 200;\np = n/4;\n\n%%\n% Sensing matrix.\n\nA = randn(p,n);\n\n%%\n% Measurements.\n\ny = randn(p,1);\n\n%%\n% We aim at solving \n\n%%\n% |min_{A*x=y} norm(x,1)|\n\n%%\n% This can be rewriten as the minimization of |F(x)+G(x)|\n% where |F=norm(x,1)| and |G=i_{A*x=y}| is the indicator function.\n\n\n%%\n% The proximity operator of the L1 norm is the soft thresholding.\n\nProxF = @(x,tau)perform_soft_thresholding(x, tau);\n\n%%\n% The proximity operator of the indicator of |A*x=y| is the orthogonal\n% projection on A*x=y.\n\npA = A'*(A*A')^(-1);\nProxG = @(x,tau)x + pA*(y-A*x);\n\n%%\n% Create a function to record the values of F and the constraint at each iteration.\n\nF = @(x)norm(x,1);\nConstr = @(x)1/2*norm(y-A*x)^2;\noptions.report = @(x)struct('F', F(x), 'Constr', Constr(x));\n\n%%\n% Run the algorithm. \n\noptions.gamma = 5;\noptions.niter = 5000;\n[x,R] = perform_dr(zeros(n,1), ProxF, ProxG, options);\n\n%%\n% Display the solution. At convergence, it should be of sparsity |p|.\n\nclf;\nplot(x);\naxis tight;\n\n%%\n% Retrieve the F and constraint function values.\n\nf = s2v(R,'F');\nconstr = s2v(R,'Constr');\n\n%%\n% Display.\n\nclf;\nsubplot(2,1,1);\nplot(f(2:end));\naxis tight; title('Objective');\nsubplot(2,1,2);\nplot(constr(2:end));\naxis tight; title('Constraint');\n", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_optim/tests/test_l1_constraint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6832099282990751}} {"text": "function [beta_median beta_std beta_lbound beta_ubound sigma_median sigma_t_median sigma_t_lbound sigma_t_ubound]=stvol3estimates(beta_gibbs,sigma_gibbs,sigma_t_gibbs,n,T,cband)\n\n\n\n\n\n\n% compute the median, variance, and credibility intervals for the posterior distribution of beta\nbeta_median=quantile(beta_gibbs,0.5,2);\nbeta_std=std(beta_gibbs,0,2);\nbeta_lbound=quantile(beta_gibbs,(1-cband)/2,2);\nbeta_ubound=quantile(beta_gibbs,1-(1-cband)/2,2);\n\n\n% compute the results for sigma (long-run value)\nsigma_median=reshape(quantile(sigma_gibbs,0.5,2),n,n);\n\n\n% compute the rsults for sigma (sample values)\nsigma_t_median=cell(n,n);\nsigma_t_lbound=cell(n,n);\nsigma_t_ubound=cell(n,n);\n% loop over periods and entries\nfor ii=1:T\n for jj=1:n\n for kk=1:jj\n sigma_t_median{jj,kk}(ii,1)=quantile(sigma_t_gibbs{ii,1}(jj,kk,:),0.5,3);\n sigma_t_lbound{jj,kk}(ii,1)=quantile(sigma_t_gibbs{ii,1}(jj,kk,:),(1-cband)/2,3);\n sigma_t_ubound{jj,kk}(ii,1)=quantile(sigma_t_gibbs{ii,1}(jj,kk,:),1-(1-cband)/2,3);\n end\n end\nend\n\n\n\n\n \n\n\n\n\n\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/stvol3estimates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.68320992359802}} {"text": "function [ y ] = FFT2D( x )\n%FFT2D Summary of this function goes here\n% Detailed explanation goes here\n\ny = fftshift(fft2(ifftshift(x)));\n\nend\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_Proximal/FFT2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6832099183076473}} {"text": "%% Example 8.15: Duffing van der Pol oscillator\n%\n% Copyright: \n% 2018 - Simo S\u00e4rkk\u00e4 and Arno Solin\n%\n% License:\n% This software is provided under the MIT License. See the accompanying \n% LICENSE file for details.\n\n%% Duffing van der Pol\n\n % Time-span\n tspan = 0:2^-5:20;\n\n % Parameters\n alpha = 1;\n\n % Define arrow (for visalization)\n arrow1 = [-1 1 0 -1; -.5 -.5 2 -.5]';\n \n % The model\n f = @(x,t) [x(2,:); x(1,:).*(alpha - x(1,:).^2)-x(2,:)];\n L = @(x,t) [zeros(1,size(x,2)); x(1,:)];\n\n \n%% ODE \n \n figure(1); clf; hold on\n \n for j=1:10\n %x = rk4(f,tspan,[-2-.2*j; 0]);\n x = rk4simple(f,tspan,[-2-.2*j; 0]);\n %[~,x] = ode45(@(t,x) f(x,t),tspan,[-2-.2*j; 0]); x = x';\n \n % Plot trajectory\n plot(x(1,:),x(2,:),'-k','LineWidth',.25)\n \n % Plot direction\n uv = f(x,[]); ind = 10;\n newquiver(x(1,ind),x(2,ind),uv(2,ind),-uv(1,ind), ...\n 'X',arrow1,'scale',.04*[1 14.8/8.8])\n \n end\n \n % Set axis limits\n axis([-4.4 4.4 -4.8 10]), axis square\n %set(gca,'XTick',-4:2:4,'YTick',-4:2:8)\n xlabel('$x_1$'); ylabel('$x_2$')\n box on\n\n%% SDE \n \n figure(2); clf; hold on\n figure(3); clf; hold on\n \n for j=1:10\n \n figure(2); \n \n % Lock random seed\n if exist('rng') % Octave doesn't have rng\n rng(3,'twister') \n else\n randn('state',2);\n rand('state',2);\n end\n \n % Use the strong order 1.0 method\n x = srkS10scalarnoise(f,L,tspan,[-2-.2*j; 0],.5^2);\n \n % Plot trajectory\n plot(x(1,:),x(2,:),'-k','LineWidth',.25)\n \n % Plot direction\n uv = f(x,[]); ind = 10;\n newquiver(x(1,ind),x(2,ind),uv(2,ind),-uv(1,ind), ...\n 'X',arrow1,'scale',.04*[1 14.8/8.8])\n \n figure(3);\n plot(tspan,x(1,:),'-k')\n plot(tspan,x(2,:),'-','Color',[.7 .7 .7])\n \n end\n \n % Set axis limits\n figure(2)\n axis([-4.4 4.4 -4.8 10]), axis square\n %set(gca,'XTick',-4:2:4,'YTick',-4:2:8)\n xlabel('$x_1$'); ylabel('$x_2$')\n box on\n \n % Set axis limits\n figure(3)\n xlim([0 20])\n xlabel('Time, $t$'); ylabel('$x$')\n legend('$x_1(t)$','$x_2(t)$')\n box on\n \n \n%% Weak approximation\n\n % Time-span\n tspan = 0:2^-4:20;\n\n % Reset random seed\n % Lock random seed\n if exist('rng') % Octave doesn't have rng\n rng(1,'twister') \n else\n randn('state',2);\n rand('state',2);\n end\n\n % Initial point\n x0 = [-3;0];\n\n % Number of smaples\n x = zeros(2,10000);\n \n % Iterate\n for j=1:size(x,2)\n \n % Weak SRK scheme\n foo = srkW20(f,L,tspan,x0,.5^2,true); \n \n % Store\n x(:,j) = foo(:,end);\n \n % Report\n if rem(j,100)==0,\n figure(4); clf\n hist(x(1,1:j),ceil(sqrt(j)))\n drawnow\n j\n end\n \n end\n \n \n%% Histogram\n \n % Bins for histogram\n t = linspace(min(x(1,:)),max(x(1,:)),64);\n \n figure(5); clf\n\n % Show solution w2.0\n n = histc(x(1,:),t);\n stairs(t-(t(2)-t(1))/2,n/size(x,2),'-k')\n\n % Label\n xlabel('$x_1$')\n \n % Ticks\n box off\n xlim([-2.2 2.2])\n %set(gca,'XTick',0:.2:1.2)\n \n figure(6); clf\n\n % Show solution w2.0\n plot(x(1,:),x(2,:),'.k')\n\n % Label\n xlabel('$x_1$')\n ylabel('$x_2$')\n \n % Ticks\n box on\n ", "meta": {"author": "AaltoML", "repo": "SDE", "sha": "91111b0f1849ef0a0540c683bb2cf454ab4f2aff", "save_path": "github-repos/MATLAB/AaltoML-SDE", "path": "github-repos/MATLAB/AaltoML-SDE/SDE-91111b0f1849ef0a0540c683bb2cf454ab4f2aff/matlab/ch08_ex15_duffing_van_der_pol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.6831645283003444}} {"text": "% function F = det_F_gold(x1,x2,L_COST,SAMPSON_APPROXIMATION,NORMALIZE)\n% Determines the F by iteratively minimizing the geometric error\n% Algorithm 11.2 in Hartley & Zisserman, Multiple View Geometry in Computer\n% Vision\n% Inputs:\n% x1 3xN coordinates of matched points in image 1(homogeneous)\n% x2 3xN coordinates of matched points in image 2(homogeneous)\n% L_COST 1x1 (optional) controls penalization scheme\n% for the cost function: L_COST 1 leads to L_1 minimization of\n% the average geometric cost (the one mentioned in the book)\n% SAMPSON_APPROXIMATION 1x1 (optional) if enabled,\n% approximates the geometric mean with the sampson cost\n% NORMALIZE 1x1 (optional)determines if the algorithm \n% should use the normalized points\n% Outputs:\n% F 3x3 the fundamental matrix \n% \n% Author: Omid Aghazadeh, KTH(Royal Institute of Technology), 2010/05/09\nfunction F = det_F_gold(x1,x2,L_COST,SAMPSON_APPROXIMATION,NORMALIZE)\nif sum(size(x1)~=size(x2)), error('size of correspondences do not match!'), end\nif size(x1,1) ~= 3, error('invalid points'), end\nglobal MAX_FUN_EVAL MAX_ITER TOL_X TOL_FUN;\nif nargin<3, L_COST = 1; end;\nif nargin<4, SAMPSON_APPROXIMATION = 0; end\nif nargin<5, NORMALIZE = 1; end;\nif NORMALIZE\n nmat1 = get_normalization_matrix(x1); % isotropic normalization (translation/scaling)\n nmat2 = get_normalization_matrix(x2);\n x1n = nmat1*x1; \n x2n = nmat2*x2;\nelse\n nmat1 = eye(3); nmat2 = eye(3); x1n = x1; x2n = x2;\nend\nx1n = x1n./repmat(x1n(3,:),3,1); x2n = x2n./repmat(x2n(3,:),3,1); % normalizing points so their last coordinate is 1\nF_0 = det_F_normalized_8point(x1n,x2n);\n%% (ii)\n\n[e,e_prime] = get_epipole(F_0);\ne_prime_cross = get_x_cross(e_prime);\nP2 = [e_prime_cross*F_0 e_prime];\n\n%% (iii) minimze the cost\n\nif ~ SAMPSON_APPROXIMATION\n [P2] = lsqnonlin(@(p2)costGold(x1n,x2n,p2,L_COST),P2,[],[],optimset('Display','off','TolX',TOL_X,'TolFun',TOL_FUN,'MaxFunEval',MAX_FUN_EVAL,'MaxIter',MAX_ITER,'Algorithm',{'levenberg-marquardt' 0.01}));\nelse\n [P2] = lsqnonlin(@(p2)costSampson(x1n,x2n,p2),P2,[],[],optimset('Display','off','TolX',TOL_X,'TolFun',TOL_FUN,'MaxFunEval',MAX_FUN_EVAL,'MaxIter',MAX_ITER,'Algorithm',{'levenberg-marquardt' 0.01}));\nend\n\nFhat = get_x_cross(P2(:,4))*P2(:,1:3);\n\nF= nmat2' * Fhat* nmat1; % denormalization\n\nend\n\n%% function scost = costGold(x1,x2,P2,L_COST)\n% this is the cost function for the Gold Standard algoritghm. The\n% triangulation method is the inhomogeneous one(chapter 12 of the book)\nfunction scost = costGold(x1,x2,P2,L_COST)\nXhat = triangulate(x1,x2,P2,1);\nxhat1 = Xhat(1:3,:)./repmat(Xhat(3,:),3,1); % the first camera is assumed to be [I|0]\nxhat2 = P2 * Xhat;\nxhat2 = xhat2./repmat(xhat2(3,:),3,1);\ncost = ((x1(:)-xhat1(:)).^2 + (x2(:)-xhat2(:)).^2);\nscost = sqrt(sum(cost))^L_COST;\nend\n\n%% function scost = costSampson(x1,x2,P2)\n% this is the cost function for the sampson approximation. It implements an\n% over-parametrization of F, however the minimal solution can be easily\n% integrated here.\nfunction scost = costSampson(x1,x2,P2)\nF = get_x_cross(P2(:,4))*P2(:,1:3);\nFx1 = F*x1;\nFtx2 = F'*x2;\nnum = sum(x2 .* Fx1,1).^2;\ndenum= sum(Fx1(1:2,:).^2,1) + sum(Ftx2(1:2,:).^2,1);\ncost = num./denum;\nscost = sqrt(sum(cost));\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/27541-fundamental-matrix-computation/det_F_gold.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.6831645283003442}} {"text": "function D = prtDistanceLNorm(dataSet1,dataSet2,Lnorm)\n% prtDistanceLNorm L Norm distance function.\n% \n% DIST = prtDistanceCityBlock(DS1,DS2) calculates the LNorm distance\n% from all the observations in datasets DS1 to DS2, and ouputs a distance\n% matrix of size DS1.nObservations x DS2.nObservations. DS1 and DS2\n% should have the same number of features. DS1 and DS2 should be\n% prtDataSet objects.\n% \n% For more information, see:\n% \n% http://en.wikipedia.org/wiki/Norm_(mathematics)#p-norm\n%\n% Example:\n%\n% % Create 2 data sets\n% dsx = prtDataSetStandard('Observations', [0 0; 1 1]);\n% dsy = prtDataSetStandard('Observations', [1 0;2 2; 3 3]);\n% % Compute distance\n% distance = prtDistanceLnorm(dsx,dsy)\n%\n% See also: prtDistanceCityBlock, prtDistanceChebychev\n% prtDistanceMahalanobis, prtDistanceSquare, prtDistanceEuclidean\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% A portion of IPDM from MATLAB Central is used in this function see\n% prtExternal.IPDM.ipdm(). The license information from that file is below.\n%\n% Copyright (c) 2009, John D'Errico\n% All rights reserved.\n% \n% Redistribution and use in source and binary forms, with or without \n% modification, are permitted provided that the following conditions are \n% met:\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% \n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE \n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n% POSSIBILITY OF SUCH DAMAGE.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[data1,data2] = prtUtilDistanceParseInputs(dataSet1,dataSet2);\n\n% Used to handle memory efficiency paths see IPDM\nchunkSize = 2^25;\n\n[nSamples1, nDim1] = size(data1);\n[nSamples2, nDim2] = size(data2);\n\nif nDim1 ~= nDim2\n error('Dimensionality of data1 and data2 must be equal')\nend\n\nif (nDim1>1) && ((nSamples1*nSamples2*nDim1)<=chunkSize)\n switch Lnorm\n case 1\n D = sum(abs(bsxfun(@minus,reshape(data1,[nSamples1,1,nDim1]),reshape(data2,[1,nSamples2,nDim1]))),3);\n case inf\n D = max(abs(bsxfun(@minus,reshape(data1,[nSamples1,1,nDim1]),reshape(data2,[1,nSamples2,nDim1]))),[],3);\n case 0\n D = min(abs(bsxfun(@minus,reshape(data1,[nSamples1,1,nDim1]),reshape(data2,[1,nSamples2,nDim1]))),[],3);\n \n % This code has overflow problems for large data1 and data2\n % case 2\n % %un-rolled((x-y)^2)) - sqrt below; this takes less time than\n % %the generic code below for the most common L-norm (2)\n %\n % %D = repmat(sum((data1.^2), 2), [1 nSamples2]) + repmat(sum((data2.^2),2), [1 nSamples1]).' - 2*data1*(data2.');\n %\n % % %Handle overflow issues for large data2\n % % muData2 = prtUtilNanMean(data2);\n % % data2 = bsxfun(@minus,data2,muData2);\n % % data1 = bsxfun(@minus,data1,muData2);\n %\n % D = bsxfun(@minus,bsxfun(@plus,sum((data1.^2), 2),sum((data2.^2),2).'),2*data1*(data2.'));\n otherwise\n D = sum(bsxfun(@minus,reshape(data1,[nSamples1,1,nDim1]),reshape(data2,[1,nSamples2,nDim1])).^Lnorm,3);\n end\nelse\n % too big, so that the ChunkSize will have been exceeded, or just 1-d\n if isfinite(Lnorm) && Lnorm ~= 1\n D = bsxfun(@minus,data1(:,1),data2(:,1)').^Lnorm;\n else\n D = abs(bsxfun(@minus,data1(:,1),data2(:,1)'));\n end\n for i=2:nDim1\n switch Lnorm\n case 1\n D = D + abs(bsxfun(@minus,data1(:,i),data2(:,i)'));\n case inf\n D = max(D,abs(bsxfun(@minus,data1(:,i),data2(:,i)')));\n case 0\n D = min(D,abs(bsxfun(@minus,data1(:,i),data2(:,i)')));\n otherwise\n D = D + bsxfun(@minus,data1(:,i),data2(:,i)').^Lnorm;\n end\n end\nend\n\nif isfinite(Lnorm) && Lnorm ~= 1\n if Lnorm == 2\n D = sqrt(D);\n if isreal(data1) && isreal(data2)\n D = real(D);\n end\n else\n D = D.^(1./Lnorm);\n end\nend\n\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/distance/prtDistanceLNorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.6831645196649494}} {"text": "% KM_DEMO_KRLS_WIENER1 Wiener system identification using Kernel Recursive \n% Least Square (KRLS) regression.\n%\n% This program implements a regression example similar to the channel\n% estimation example published in \n% S. Van Vaerenbergh, J. Via, and I. Santamaria. \"A sliding-window \n% kernel RLS algorithm and its application to nonlinear channel \n% identification\", 2006 IEEE International Conference on Acoustics, Speech,\n% and Signal Processing (ICASSP), Toulouse, France, 2006.\n%\n% Author: Steven Van Vaerenbergh (steven *at* gtas.dicom.unican.es), 2010.\n%\n% This file is part of the Kernel Methods Toolbox for MATLAB.\n% https://github.com/steven2358/kmbox\n\nclose all\nclear\n\n%% PARAMETERS\n\nNtrain = 1500;\t\t% number of total train data points\nNtest = 200;\t\t% number of test data points\nNswitch = 500;\t\t% abrupt switch from model 1 to model 2 after N1 iterations\nB1 = [1,.8668,-0.4764,0.2070]';\t% model 1 linear filter\nB2 = [1,-.8326,.6656,-.7153]';\t% model 2 linear filter\nf = @(x) tanh(x);\t\t\t% Wiener system nonlinearity\nSNR = 40;\t\t% SNR in dB\n\npars.kernel.type = 'gauss';\t% kernel type\npars.kernel.par = 2;\t\t\t% kernel parameter (width in case of Gaussian kernel)\npars.M = 150;\t\t% dictionary size\n\n% % parameters for ALD-KRLS\n% pars.algo = 'ald-krls';\n% pars.thresh = 0.01;\n\n% % parameters for SW-KRLS\n% pars.algo = 'sw-krls';\n% pars.c = 1E-4;\n\n% parameters for KRLS-T\npars.algo = 'krls-t';\npars.lambda = .999;\npars.c = 1E-4;\n\nd = 4;\t\t\t% time-embedding\n\n%% PROGRAM\ntic\n\n% generate data\nfprintf('Generating Wiener system data...\\n');\nN = Ntrain+Ntest;\ns = randn(N,1);\t% Gaussian input, all data\ns_mem = zeros(N,d);\nfor i = 1:d,\n\ts_mem(i:N,i) = s(1:N-i+1);\t% time-embedding\nend\ns_train = s_mem(1:Ntrain,:);\t% input train data, stored in columns\ns_test = s_mem(Ntrain+1:Ntrain+Ntest,:);\t% input test data, stored in columns\n\nx1 = s_mem(1:Nswitch,:)*B1;\nx2 = s_mem(Nswitch+1:Ntrain,:)*B2;\nx = [x1;x2];\ny = f(x);\nvary = var(y);\nnoisevar = 10^(-SNR/10)*vary;\nnoise_train = sqrt(noisevar)*randn(Ntrain,1);\ny_train = y + noise_train;\t\t\t\t% noisy output train data\n\nx_test1 = s_mem(Ntrain+1:Ntrain+Ntest,:)*B1;\nx_test2 = s_mem(Ntrain+1:Ntrain+Ntest,:)*B2;\nnoise_test1 = sqrt(noisevar)*randn(Ntest,1);\nnoise_test2 = sqrt(noisevar)*randn(Ntest,1);\ny_test1 = f(x_test1) + noise_test1;\t% noisy output test data, model 1\ny_test2 = f(x_test2) + noise_test2;\t% noisy output test data, model 2\n\n% apply KRLS\nfprintf('Applying KRLS for Wiener system identification...\\n');\nvars = [];\nMSE = zeros(Ntrain,1);\nfor i=1:Ntrain-1,\n\tif ~mod(i,Ntrain/10), fprintf('.'); end\n\tvars.t = i;\n\t\n\t% perform KRLS regression and get regression output of test signal\n\tswitch pars.algo\n\t\tcase 'ald-krls'\n\t\t\tvars = km_aldkrls(vars,pars,s_train(i,:),y_train(i));\t% train\n\t\t\ty_est = km_aldkrls(vars,pars,s_test);\t\t\t\t% evaluate\n\t\tcase 'sw-krls'\n\t\t\tvars = km_swkrls(vars,pars,s_train(i,:),y_train(i));\t% train\n\t\t\ty_est = km_swkrls(vars,pars,s_test);\t\t\t\t% evaluate\n\t\tcase 'krls-t'\n\t\t\tvars = km_krlst(vars,pars,s_train(i,:),y_train(i));\t% train\n\t\t\ty_est = km_krlst(vars,pars,s_test);\t\t\t\t% evaluate\n\t\totherwise\n\t\t\terror('wrong algorithm')\n\tend\n\t\n\t% calcalate test error\n\tif i<=Nswitch, y_test = y_test1; else y_test = y_test2; \tend\n\tMSE(i) = mean((y_test-y_est).^2);\nend\nfprintf('\\n');\n\ntoc\n%% OUTPUT\n\nfprintf('Mean MSE over last 500 steps = %.2d\\n',mean(MSE(Ntrain-499:Ntrain)))\n\nfigure;semilogy(MSE)\ntitle('MSE')\n\nfigure; hold on\nplot(y_test,'b')\nplot(y_est,'g')\nlegend({'Test output','Estimated output'})\ntitle(sprintf('%s, m=%d',pars.algo,pars.M))\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/toolboxes/kmbox/demo/km_demo_krls_wiener.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6831645131540981}} {"text": "function [Int, Noise] = regEstFilIntGrad(inp, PbyPflag, lpf);\n% regEstFilIntGrad - Estimates the intensity gradient, using local mean\n%\n% [Int, Noise] = regEstFilIntGrad(inp, , );\n%\n% Inputs:\n% inp - input inplanes affected by the intensity gradient\n% PbyPflag - operates plane by plane if activated (default 0)\n% lpf - low pass filter (applied separably to x,y,z) used to\n% compute the local mean\n%\n% Outputs:\n% Int - Estimated intensity\n% Noise - Estimated power-spatial distribution of the noise, as the\n% local variance\n%\n% Oscar Nestares - 5/99\n%\n\n% default low-pass filter\nif ~exist('lpf')\n lpf = conv([1 4 6 4 1]/16, [1 4 6 4 1]/16);\nend\n\nlpfZ = lpf;\nif exist('PbyPflag')\n if PbyPflag\n lpfZ = 1;\n end\nend\n\nB = (length(lpf)-1)/2;\n\n% adding border to the original inplanes\nfor k=1:size(inp,3)\n inpB(:,:,k) = regPutBorde(inp(:,:,k), B, B, 2);\nend\n\n% estimates the intensity as the local mean\nInt = regConvXYZsep(inpB, 'repeat', lpf, lpf, lpfZ);\n\n% estimates the noise as the mean local variance\nfor k=1:size(Int,3) % adding border to the estimated intensity\n IntB(:,:,k) = regPutBorde(Int(:,:,k), B, B, 2);\nend\nNoise = regConvXYZsep((inpB-IntB).^2, 'repeat', lpf, lpf, lpfZ);\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAlign/registrationOscar/regEstFilIntGrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.6831645120575206}} {"text": "function [mm2] = km22mm2(km2)\n% Convert area from square kilometers to square millimeters.\n% Chad A. Greene 2012\nmm2 = km2*1000000000000;", "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/35258-unit-converters/unit_converters/km22mm2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6831572232738374}} {"text": "function visible_probability = hidden_state_to_visible_probabilities(rbm_w, hidden_state)\n % is a matrix of size