{"text": "function [ H_output ] = homography_linearization( H, point, anchor_points )\nvega = 5;\n\n% Obtain kernel: Student’s 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": "function [C,t,err] = cubic_vertex_removal(C1,C2,varargin)\n % CUBIC_VERTEX_REMOVAL Given a G¹ continuous sequence of cubic Bézier 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,…)\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\" → 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(…,'AlreadyGenerated',false)` onces to\n % generate the files and the call\n % `cubic_vertex_removal(…,'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₀ 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₁ 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₁\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₀ and G₁\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 [ 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": "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/增强算法/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": "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 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 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": "%\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": "% 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 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": "function [ n, a, seed ] = tree_rb_yule ( n, a, seed )\n\n%*****************************************************************************80\n%\n%% TREE_RB_YULE adds two nodes to a rooted binary tree using the Yule model.\n%\n% Discussion:\n%\n% The Yule model is a simulation of how an evolutionary family tree\n% develops. We start with a root node. The internal nodes of the tree \n% are inactive and never change. Each pendant or leaf node of the\n% tree represents a biological family that can spontaneously \"fission\",\n% developing two new distinct sub families. In graphical terms, the node\n% becomes internal, with two new leaf nodes depending from it.\n%\n% The tree is stored in inorder traversal form.\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/output, integer N, the number of nodes in the input\n% tree. On output, this number has been increased, usually by 2.\n%\n% Input/output, integer A(*), the preorder traversal form \n% for the rooted binary tree. The number of entries in A is N.\n%\n% Input/output, integer SEED, a seed for the random number\n% generator.\n%\n if ( n <= 0 )\n n = 1;\n a(1) = 0;\n return\n end\n%\n% Count the expected number of leaves, which are the 0 values.\n%\n nleaf = floor ( ( n + 1 ) / 2 );\n%\n% Choose a random number between 1 and NLEAF.\n%\n ileaf = i4_uniform_ab ( 1, nleaf, seed );\n%\n% Locate leaf number ILEAF.\n%\n j = 0;\n jleaf = 0;\n for i = 1 : n\n if ( a(i) == 0 )\n jleaf = jleaf + 1;\n end\n if ( jleaf == ileaf )\n j = i;\n break\n end\n end\n%\n% Replace '0' by '100'\n%\n a(n+2:-1:j+2) = a(n:-1:j);\n a(j) = 1;\n a(j+1) = 0;\n\n n = n + 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/treepack/tree_rb_yule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8152324871074607, "lm_q1q2_score": 0.6992804255925357}} {"text": "function value = r8_gmit ( a, x, algap1, sgngam, alx )\n\n%*****************************************************************************80\n%\n%% R8_GMIT: Tricomi's incomplete gamma function for small X.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 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 A, the parameter.\n%\n% Input, real X, the argument.\n%\n% Input, real ALGAP1, the logarithm of Gamma ( A + 1 ).\n%\n% Input, real SGNGAM, the sign of Gamma ( A + 1 ).\n%\n% Input, real ALX, the logarithm of X.\n%\n% Output, real VALUE, the Tricomi incomplete gamma function.\n%\n persistent bot\n persistent eps\n\n if ( isempty ( eps ) )\n eps = 0.5 * r8_mach ( 3 );\n bot = log ( r8_mach ( 1 ) );\n end\n\n if ( x <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_GMIT - Fatal error!\\n' );\n fprintf ( 1, ' X <= 0.\\n' );\n error ( 'R8_GMIT - Fatal error!' )\n end\n\n if ( a < 0.0 )\n ma = r8_aint ( a - 0.5 );\n else\n ma = r8_aint ( a + 0.5 );\n end\n\n aeps = a - ma;\n\n if ( a < - 0.5 )\n ae = aeps;\n else\n ae = a;\n end\n\n t = 1.0;\n te = ae;\n s = t;\n converged = 0;\n for k = 1 : 200\n fk = k;\n te = - x * te / fk;\n t = te / ( ae + fk );\n s = s + t;\n if ( abs ( t ) < eps * abs ( s ) )\n converged = 1;\n break\n end\n end\n\n if ( ~ converged )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_GMIT - Fatal error!\\n' );\n fprintf ( 1, ' No convergence in 200 iterations.\\n' );\n error ( 'R8_GMIT - Fatal error!' )\n end\n\n if ( - 0.5 <= a )\n algs = - algap1 + log ( s );\n value = exp ( algs );\n return\n end\n\n algs = - r8_lngam ( 1.0 + aeps ) + log ( s );\n s = 1.0;\n m = - ma - 1;\n t = 1.0;\n for k = 1 : m\n t = x * t / ( aeps - ( m + 1 - k ) );\n s = s + t;\n if ( abs ( t ) < eps * abs ( s ) )\n break\n end\n end\n\n value = 0.0;\n algs = - ma * log ( x ) + algs;\n\n if ( s == 0.0 || aeps == 0.0 )\n value = exp ( algs );\n return\n end\n\n sgng2 = sgngam * r8_sign ( s );\n alg2 = - x - algap1 + log ( abs ( s ) );\n\n if ( bot < alg2 )\n value = sgng2 * exp ( alg2 );\n end\n\n if ( bot < algs )\n value = value + exp ( algs );\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_gmit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.6992409139247364}} {"text": "function [VAR, VARopt] = VARmodel(ENDO,nlag,const,EXOG,nlag_ex)\n% =======================================================================\n% Perform vector autogressive (VAR) estimation with OLS \n% =======================================================================\n% [VAR, VARopt] = VARmodel(ENDO,nlag,const,EXOG,nlag_ex)\n% -----------------------------------------------------------------------\n% INPUT\n%\t- ENDO: an (nobs x nvar) matrix of y-vectors\n%\t- nlag: lag length\n% -----------------------------------------------------------------------\n% OPTIONAL INPUT\n%\t- const: 0 no constant; 1 constant; 2 constant and trend; 3 constant, \n% trend, and trend^2 [dflt = 0]\n%\t- EXOG: optional matrix of variables (nobs x nvar_ex)\n%\t- nlag_ex: number of lags for exogeonus variables [dflt = 0]\n% -----------------------------------------------------------------------\n% OUTPUT\n% - VAR: structure including VAR estimation results\n% - VARopt: structure including VAR options (see VARoption)\n% =======================================================================\n% Ambrogio Cesa Bianchi, March 2015\n% ambrogio.cesabianchi@gmail.com\n\n% Note: this code is a modified version of of the vare.m function of James \n% P. LeSage\n\n% Representation --> 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": "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 [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": "% 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": "% 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 [ p2, dp2, p1 ] = gegenbauer_recur ( x, n, alpha, c )\n\n%*****************************************************************************80\n%\n%% GEGENBAUER_RECUR finds the value and derivative of a Gegenbauer polynomial.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 March 2008\n%\n% Author:\n%\n% Original FORTRAN77 version by Arthur Stroud, Don Secrest,\n% MATLAB version by John Burkardt,\n%\n% Reference:\n%\n% Arthur Stroud, Don Secrest,\n% Gaussian Quadrature Formulas,\n% Prentice Hall, 1966,\n% LC: QA299.4G3S7.\n%\n% Parameters:\n%\n% Input, real X, the point at which polynomials are evaluated.\n%\n% Input, integer N, the order of the polynomial to be computed.\n%\n% Input, real ALPHA, the exponent of (1-X^2) in the quadrature rule.\n%\n% Input, real C(N), the recursion coefficients.\n%\n% Output, real P2, the value of J(N)(X).\n%\n% Output, real DP2, the value of J'(N)(X).\n%\n% Output, real P1, the value of J(N-1)(X).\n%\n p1 = 1.0;\n dp1 = 0.0;\n\n p2 = x;\n dp2 = 1.0;\n\n for i = 2 : n\n\n p0 = p1;\n dp0 = dp1;\n\n p1 = p2;\n dp1 = dp2;\n\n p2 = x * p1 - c(i) * p0;\n dp2 = x * dp1 + p1 - c(i) * dp0;\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/gegenbauer_recur.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.6990416010541387}} {"text": "function [ vX ] = ProjectL1BallDual( vY, ballRadius, vLowerBound, vUpperBound )\n% ----------------------------------------------------------------------------------------------- %\n% [ vX ] = ProjectL1Ball( vY, ballRadius, vLowerBound, vUpperBound )\n% Solving the Orthogonal Porjection Problem of the input vector onto the\n% L1 Ball with Box Constraints using Dual Function.\n% Input:\n% - vY - Input Vector.\n% Structure: Vector (Column).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - ballRadius - Ball Radius.\n% Sets the Radius of the L1 Ball. For Unit L1 Ball\n% set to 1.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: (0, inf).\n% - vLowerBound - Lower Bound Vector.\n% Sets the lower bound values of the solution\n% (Element wise).\n% Structure: Vector.\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - vUpperBound - Upper Bound Vector.\n% Sets the upper bound values of the solution\n% (Element wise).\n% Structure: Vector.\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% Output:\n% - vX - Output Vector.\n% The projection of the Input Vector onto the L1\n% Ball.\n% Structure: Vector (Column).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% References\n% 1. https://math.stackexchange.com/a/2830242/33.\n% Remarks:\n% 1. S\n% TODO:\n% 1. U.\n% Release Notes:\n% - 1.0.000 24/06/2018 Royi Avital\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\nFALSE = 0;\nTRUE = 1;\n\nOFF = 0;\nON = 1;\n\nDEBUG_MODE = OFF;\n\nparamLambda = 0; % 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 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 © 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 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 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": "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": "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": "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 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": "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": "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": "function g = gauss(x, m, P)\n\n% GAUSS Gaussian distribution value\n% GAUSS(X, M, P) gives the probability density at point X, following a\n% Gaussian or Normal distribution with mean M and covariances matrix P.\n%\n% For X vector, the evaluation happens at a single point denoted by X,\n% and the result is a positive scalar in the range [0 , 1].\n%\n% For X matrix, the evaluation happens at each row of X, and the result\n% is a row-vector of scalars, one for each column of X.\n\n% Copyright 2013 Joan Sola\n\nd = size(x,1);\nn = size(x,2);\nMD2 = zeros(1,n);\n\nif (size(m,1) == d) && (size(P,1) == d) && (size(P,2) == d)\n \n z = x - repmat(m, 1, n);\n for i = 1:n\n MD2(1,i) = z(:,i)' * P^-1 * z(:,i);\n end\n a = sqrt((2*pi)^d * det(P));\n g = exp(-0.5 * MD2) / a;\n \nelse\n error ('Input sizes don''t match')\nend\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/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": "% 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": "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": "% 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 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 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 [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": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\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 [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/去噪算法/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": "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": "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": "% 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 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": "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 [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 [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 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": "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/《Matlab编程》源码/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 [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": "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 [ 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[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": "% 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": "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 [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": "function at = auct(crit,y,z,tt)\n%AUCS Compute area under curve for survival model at given time\n%\n% Description\n% A = AUCT(CRIT,Z) Compute are under curve for survival model at\n% given time using criteria vector CRIT (where larger value\n% means larger risk of incidence), observed time vector Y,\n% censoring indicator matrix Z at times TT (0=event, 1=censored)\n% and a time vector TT.\n%\n% Reference\n% L. E. Chambless, C. P. Cummiskey, and G. Cui (2011). Several\n% methods to assess improvement in risk prediction models:\n% Extension to survival analysis. Statistics in Medicine\n% 30(1):22-38.\n\n% Copyright (C) 2012 Ernesto Ulloa, 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\nip=inputParser;\nip.addRequired('crit',@(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addRequired('y', @(x) isreal(x) && all(isfinite(x(:))))\nip.addRequired('z', @(x) isreal(x) && all(isfinite(x(:))))\nip.addRequired('tt', @(x) isreal(x) && all(isfinite(x(:))))\nip.parse(crit,y,z,tt)\n\nfor i=1:size(tt,2)\n comp=bsxfun(@times,bsxfun(@and,y(:,i)<=tt(i),1-z(:,i)),bsxfun(@or,bsxfun(@and,y(:,i)<=tt(i),z(:,i)),y(:,i)>=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": "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és-Hernández, Alejandro Ojeda, Eduardo Martínez-Montes, Agustín\n% Lage-Castellanos, Trinidad Virués-Alba, Lourdes Valdés-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–2339\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": "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 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 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 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 [ 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 [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 © 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 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": "% 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�92 (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 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": "%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": "% 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": "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/《Matlab编程》源码/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": "% 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": "% 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": "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": "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": "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 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 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_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øndergaard.\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 [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 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": "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": "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 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": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\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 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": "%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": "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 [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 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,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 = 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ël 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 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": "function determ = carry_determinant ( n, alpha )\n\n%*****************************************************************************80\n%\n%% CARRY_DETERMINANT returns the determinant of the CARRY matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 October 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 DETERM, the determinant.\n%\n power = ( n * ( n - 1 ) ) / 2;\n determ = 1.0 / alpha^power;\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_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.6945396096878634}} {"text": "function x = uniform_01_cdf_inv ( cdf )\n\n%*****************************************************************************80\n%\n%% UNIFORM_01_CDF_INV inverts the Uniform 01 CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real CDF, the value of the CDF.\n% 0.0 <= CDF <= 1.0.\n%\n% Output, real X, the corresponding argument.\n%\n if ( cdf < 0.0 | 1.0 < cdf )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'UNIFORM_01_CDF_INV - Fatal error!\\n' );\n fprintf ( 1, ' CDF < 0 or 1 < CDF.\\n' );\n error ( 'UNIFORM_01_CDF_INV - Fatal error!' );\n end\n\n x = cdf;\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/uniform_01_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.6945396081435898}} {"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 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 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 [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 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": "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 [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 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 © 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 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 [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 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": "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) = ∑L(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": "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 [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 [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": "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": "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": "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": "% 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 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 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 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": "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": "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": "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 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": "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": "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 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 [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 [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 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 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 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 [ 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 [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": "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 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% 输入:\n% a0 a1 a2 toc: 卫星时钟校正模型方程中3个参数, toc: 第一数据块参考时间, 被用作时钟校正模型中时间参考点\n\n% dtr: 卫星时钟偏差\n\ndtr = a0+a1*(t-toc)+a2*(t-toc).^2;%t为未做钟差改正的观测时刻\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 时间为s\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 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": "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 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": "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ón 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": "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": "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 [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/《MATLAB 神经网络30个案例分析》源程序 数据/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 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/《Matlab编程》源码/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/去噪算法/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% 作用:使用离散傅里叶变换对输入的 JPG 图片 image 按照指定的滤波比例 ratio 进行压缩\n% 返回值:返回低通滤波之后的频率分布和压缩之后的图片\nfunction [z, k] = fft_compress(image, ratio)\n\n % 对原 JPG 图片在三个颜色上分别做二维离散傅里叶变换,得到频率分布\n z(:,:,1) = fft2(image(:,:,1));\n z(:,:,2) = fft2(image(:,:,2));\n z(:,:,3) = fft2(image(:,:,3));\n\n % 获取图片的尺寸大小\n [a, b, ~] = size(image);\n\n % 低通滤波\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 % 对过滤之后的结果在三个颜色上分别做进行二维反离散傅里叶变换\n k(:,:,1) = ifft2(z(:,:,1));\n k(:,:,2) = ifft2(z(:,:,2));\n k(:,:,3) = ifft2(z(:,:,3));\n\n % 类型转换,转换为 0-255 范围内的颜色值\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 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": "%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 = 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 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": "% 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": "% 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": "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 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 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/支持向量机分类——基于乳腺组织电阻抗特性的乳腺癌诊断/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 [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 [ 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 [ 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 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) 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": "% 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 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": "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": "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 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": "%% 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": "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": "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 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 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": "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 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": "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 [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 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/第2章 SISO信道模型/IEEE802.11信道模型/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": "% 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 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": "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 [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 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čkar, 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)0)\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": "%% 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łaszczyszyn 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": "% 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 [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 [ 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": "%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": "% this script plots the tire figure \nalpha = -0.2:0.001:0.2; \n\nfigure; grid on; hold on; box on; \nPacParam = [40, 1, 4500, 0];\nPacParam2 = [25, 40/25, 4500, 0];\nFyF_linear = PacParam(1)*PacParam(2)*PacParam(3).*alpha; \nFyF_nonlinear1 = PacParam(3).*sin(PacParam(2).*atan(PacParam(1).*alpha - PacParam(4).*(PacParam(1).*alpha - atan(PacParam(1).*alpha)))); \nFyF_nonlinear2 = PacParam2(3).*sin(PacParam2(2).*atan(PacParam2(1).*alpha - PacParam2(4).*(PacParam2(1).*alpha - atan(PacParam2(1).*alpha)))); \nplot(alpha, FyF_linear); \nplot(alpha, FyF_nonlinear1); \nplot(alpha, FyF_nonlinear2); \nxlabel('Side slip angle $\\alpha$ in rad'); \nylabel('Force $F_y$ in N'); \nylim([-10000, 10000]); \nlegend('Linear', 'Pacejka 1', 'Pacejka 2'); \nmatlab2tikz('TireModelComparison.tex', 'standalone', true);", "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/scripts/TMPCPaper/plotTireFigure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6894547267013785}} {"text": "function pdf = empirical_discrete_pdf ( x, a, b, c )\n\n%*****************************************************************************80\n%\n%% EMPIRICAL_DISCRETE_PDF evaluates the Empirical Discrete PDF.\n%\n% Discussion:\n%\n% A set of A values C(1:A) are assigned nonnegative weights B(1:A),\n% with at least one B nonzero. The probability of C(I) is the\n% value of B(I) divided by the sum of the weights.\n%\n% The C's must be distinct, and given in ascending order.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the PDF.\n%\n% Input, integer A, the number of values.\n% 0 < A.\n%\n% Input, real B(A), the weights of each value.\n% 0 <= B(1:A) and at least one value is nonzero.\n%\n% Input, real C(A), the values.\n% The values must be distinct and in ascending order.\n%\n% Output, real PDF, the value of the PDF.\n%\n for i = 1 : a\n if ( x == c(i) )\n pdf = b(i) / sum ( b(1:a) );\n return\n end\n end\n\n pdf = 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/prob/empirical_discrete_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7826624890918021, "lm_q1q2_score": 0.6893668383329399}} {"text": "function [x, funVal, ValueL, res]=overlapping_LeastR(A, y, z, opts)\n%\n%%\n% Function overlapping_LeastR\n% Least Squares Loss with the \n% overlapping group Lasso\n%\n%% Problem\n%\n% min 1/2 || A x - y||^2 + z_1 \\|x\\|_1 + z_2 * sum_i w_i ||x_{G_i}||\n%\n% G_i's are nodes \n%\n% we have L1 for each element\n% and the L2 for the overlapping group \n%\n% The overlapping group information is contained in\n% \n% opts.G- a row vector containing the indices of all the overlapping\n% groups G_1, G_2, ..., G_groupNum\n% \n% opts.ind- a 3 x groupNum matrix\n% opts.ind(1,i): the starting index of G_i in opts.G\n% opts.ind(2,i): the ending index of G_i in opts.G\n% opts.ind(3,i): the weight for the i-th group\n%\n% For better illustration, we consider the following example of four groups:\n% G_1={1,2,3}, G_2={2,4}, G_3={3,5}, G_4={1,5}. \n% Let us assume the weight for each group is 123.\n% \n% opts.G=[1,2,3,2,4,3,5,1,5];\n% opts.ind=[ [1, 3, 123]', [4,5,123]',[6,7,123]',[8,9,123]' ];\n%\n%\n%% Input parameters:\n%\n% A- Matrix of size m x n\n% A can be a dense matrix\n% a sparse matrix\n% or a DCT matrix\n% y - Response vector (of size mx1)\n% z - The regularization parameter (z=[z_1,z_2] >=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": "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 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": "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 [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 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": "%% (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": "%% 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 [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": "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 [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": "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": "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 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.od 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(补分启发式算法,包括神经网络、模拟退火、遗传算法)/遗传算法/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": "% 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": "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": "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": "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": "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": "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": "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": "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": "% 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 [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 [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 [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 [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 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 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": "% [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%% ∂ ∂ ∂\n%% ───(f(x, y, z)) + ───(f(x, y, z)) + ───(f(x, y, z))\n%% 2 2 2\n%% ∂x ∂y ∂z\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⋅x + 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": "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": "%%% 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": " 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 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 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 [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øndergaard.\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 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": "% \"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 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": "% 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 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": "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": "%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 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": "% 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 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": "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 [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 [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": "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 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 [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 [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 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)\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 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": "function [L,E] = facet_laplacian(V,F)\n % FACET_LAPLACIAN Builds an \"edge-based\" Laplacian L, which is an #E by #V\n % rectangular matrix which maps scalar functions living at vertices to\n % Laplacian values living at edges. For tets, edges are now facets.\n %\n % [L,E] = facet_laplacian(V,F)\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 % L #E by #V edge-based Laplacian\n % E #E by 2 list of edges\n %\n % Examples:\n % % load some non-convex shape (V,F)\n % [L,E] = facet_laplacian(V,F);\n % % find boundary edges\n % B = is_boundary_edge(E,F);\n % % Construct mass matrix\n % [M,mE] = crouzeix_raviart_massmatrix(V,F);\n % % Be sure same edges are being used.\n % assert(all(E(:)==mE(:)));\n % % \"Kill\" boundary edges\n % L(B,:) = 0;\n % % Linear functions are now in the spectrum\n % [~,~,U] = svd(full(L));\n % tsurf(F,[V(:,1:2) U(:,end-1)])\n %\n % % mesh in (V,F)\n % [Le] = facet_laplacian(V,F);\n % [Lcr,E,EMAP] = crouzeix_raviart_cotmatrix(V,F);\n % V2E = sparse(E(:),repmat(1:size(E,1),1,size(E,2))',1,size(V,1),size(E,1))';\n % V2E = bsxfun(@rdivide,V2E,sum(V2E,2));\n % LcrV2E = Lcr*V2E;\n % max(max(abs(LcrV2E--2*Le)))\n %\n %\n % See also: crouzeix_raviart_massmatrix, is_boundary_edge\n %\n\n %% check for non-manifold edges\n %S = statistics(V,F,'Fast',true);\n %if S.num_nonmanifold_edges > 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 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 [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 [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 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 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": "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 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": "%[ 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 [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 [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 [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": "%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 [ 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 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": "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": "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 [ 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 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 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 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": "% 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": "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": "% 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": "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": "% 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 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": "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": "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 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": "% 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�cation 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 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": "%% 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": "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": "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 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": "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 [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": "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 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": "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ér-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 [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": "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": "% 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 [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": "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 [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 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 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 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 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": "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 [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 [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 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 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": "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": "function [xi,w]=eighthOrderTriangleCubPoints(algorithm)\n%%EIGHTHORDERTRIANGLECUBPOINTS Obtain eighth-order cubature points for\n% integration over a triangle in 2D. The points and weights are for the\n% triangle with vertices (1,0), (0,1), (0,0), but can be transformed to\n% any triangle using transformSimplexTriPoints.\n%\n%INPUTS: algorithm An optional parameter selecting the algorithm for the\n% specific point set. Possible values are:\n% 0 (The default if omitted or an empty matrix is passed)\n% Use the algorithm of [1] (16 points).\n% 1 Use the 8th order points found using the algorithm of\n% [2], given in the supplementary material of [2] (16\n% points).\n%\n%OUTPUTS: xi A 2XnumCubPoints set of points for the standard triangle.\n% w A 1XnumCubPoints set of cubature weights. This sums to the\n% volume of the triangle (1/2).\n%\n%This function implements the points given in [1] and [2].\n%\n%EXAMPLE:\n%Given the vertices of the simplex, we compare an eighth-order moment\n%computed using these cubature points to one computed using\n%monomialIntSimplex. The results are the same within typical finite\n%precision limits.\n% [xi,w]=eighthOrderTriangleCubPoints();\n% alpha=[6;2];\n% theMoment=findMomentFromSamp(alpha,xi,w)\n% intVal=monomialIntSimplex(alpha)\n%\n%REFERENCES:\n%[1]L. Zhang and T. Cui, \"A set of symmetric quadrature rules on triangles\n% and tetrahedra,\" Journal of Computational Mathematics, vol. 27, no. 1,\n% pp. 89-96, Jan. 2009.\n%[2] F. D. Witherden and P. E. Vincent, \"On the identification of symmetric\n% quadrature rules for finite element methods,\" Computer and Mathematics\n% with Applications, vol. 69, no. 10, pp. 1232-1241, May 2015.\n%\n%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<1||isempty(algorithm))\n algorithm=0;\nend\n\nswitch(algorithm)\n case 0\n w1=0.1443156076777871682510911104890646;\n w2=0.1032173705347182502817915502921290;\n w3=0.0324584976231980803109259283417806;\n w4=0.0950916342672846247938961043885843;\n w5=0.0272303141744349942648446900739089;\n w=[w1;w2;w2;w2;w3;w3;w3;w4;w4;w4;w5;w5;w5;w5;w5;w5];\n \n p1=0.3333333333333333333333333333333333;\n p2=0.1705693077517602066222935014914645;\n p3=0.0505472283170309754584235505965989;\n p4=0.4592925882927231560288155144941693;\n p5a=0.2631128296346381134217857862846436;\n p5b=0.0083947774099576053372138345392944;\n \n xiBary=zeros(3,16);\n xiBary(:,1)=[p1;p1;p1];\n xiBary(:,2:4)=genAllMultisetPermutations([p2;p2;1-2*p2]);\n xiBary(:,5:7)=genAllMultisetPermutations([p3;p3;1-2*p3]);\n xiBary(:,8:10)=genAllMultisetPermutations([p4;p4;1-2*p4]);\n xiBary(:,11:16)=genAllMultisetPermutations([p5a;p5b;1-p5a-p5b]);\n \n %Adjust w for the area of the standard triangle.\n w=w/2;\n \n %Convert the barycentric points into normal cubature points for the\n %standard triangle given the vertices.\n vertices=[1,0,0;\n 0,1,0];\n xi=barycentricCoords2Pt(xiBary,vertices);\n case 1\n M=[-0.33333333333333333333333333333333333333, -0.33333333333333333333333333333333333333, 0.2886312153555743365021822209781292496;\n -0.081414823414553687942368971011661355879, -0.83717035317089262411526205797667728824, 0.1901832685345692495877922087771686332;\n -0.83717035317089262411526205797667728824, -0.081414823414553687942368971011661355879, 0.1901832685345692495877922087771686332;\n -0.081414823414553687942368971011661355879, -0.081414823414553687942368971011661355879, 0.1901832685345692495877922087771686332;\n -0.65886138449647958675541299701707099796, 0.31772276899295917351082599403414199593, 0.20643474106943650056358310058425806003;\n 0.31772276899295917351082599403414199593, -0.65886138449647958675541299701707099796, 0.20643474106943650056358310058425806003;\n -0.65886138449647958675541299701707099796, -0.65886138449647958675541299701707099796, 0.20643474106943650056358310058425806003;\n -0.89890554336593804908315289880680210631, 0.79781108673187609816630579761360421262, 0.064916995246396160621851856683561193593;\n 0.79781108673187609816630579761360421262, -0.89890554336593804908315289880680210631, 0.064916995246396160621851856683561193593;\n -0.89890554336593804908315289880680210631, -0.89890554336593804908315289880680210631, 0.064916995246396160621851856683561193593;\n -0.98321044518008478932557233092141110162, 0.45698478591080856248200075835212392604, 0.05446062834886998852968938014781784832;\n 0.45698478591080856248200075835212392604, -0.98321044518008478932557233092141110162, 0.05446062834886998852968938014781784832;\n -0.47377434073072377315642842743071282442, 0.45698478591080856248200075835212392604, 0.05446062834886998852968938014781784832;\n 0.45698478591080856248200075835212392604, -0.47377434073072377315642842743071282442, 0.05446062834886998852968938014781784832;\n -0.47377434073072377315642842743071282442, -0.98321044518008478932557233092141110162, 0.05446062834886998852968938014781784832;\n -0.98321044518008478932557233092141110162, -0.47377434073072377315642842743071282442, 0.05446062834886998852968938014781784832];\n\n w=M(:,3);\n xi=M(:,1:2)';\n %Transform the points to the standard triangle.\n v1=[-1,-1, 1;\n -1, 1,-1];\n v2=[1,0,0;\n 0,1,0];\n [A,d]=affineTransBetweenTriangles(v1,v2);\n xi=bsxfun(@plus,A*xi,d);\n w=w/4;\n otherwise\n error('Unknown Algorithm Specified')\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Numerical_Integration/Cubature_Points/Simplex/Triangles/eighthOrderTriangleCubPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6832920744649775}} {"text": "function X = traj_opt3c(path, total_time, ts)\n% 3rd order trajectory optimization (minimum acceleration)\n% by solving 4m linear equations. Assumes constant speed\n% @author Yiren Lu\n% @email luyiren [at] seas [dot] upenn [dot] edu\n% \n% @input: path (m+1) by 3 planning trajectory\n% total_time total time\n% @output X 4mx3 solution vector, where\n% X(4*(k-1)+1:4*k,d) is the coefficients\n% of x_k(t), i.e., \n% x_k(t)=X(4*(k-1)+1:4*k,d)'*[t^3;t^2,t,1]\n% where d \\in [1,2,3] to indicate dimension xyz\n path0 = path;\n % generate the trajectory here, and decide the total_time\n [m,n] = size(path0); % n == 3\n % there we set m = m - 1 for convenience\n m = m-1;\n % there are now in total m+1 points in the path, which seperate the path into\n % m subpaths.\n\n % ts(k) = t_{k+1}, e.g. ts(1) = t_0,\n % time planning according to the segment length\n\n % ts(m+1) = t_m\n % In 3rd order trajectory optimization, for each subpath there are 4\n % parameters\n % x_k(t) = c_{k,3}*t^3 + c_{k,2}*t^2 + c_{k,1}*t^1 + c_{k,0}\n % for k = 1..(m-1)\n \n % X contains the parameters\n X = zeros(4*m,n);\n A = zeros(4*m, 4*m, n);\n Y = zeros(4*m,n);\n\n for i = 3\n A(:,:,i) = eye(4*m)*eps;\n % constraint 1: x_k(t_k) = x_{k+1}(t_k) = p_k, where p_k is a\n % waypoint\n % x_k(t) = c_{k,3}*t^3 + c_{k,2}*t^2 + c_{k,1}*t^1 + c_{k,0}\n % for k = 1..(m-1)\n % e.g. x_1(t_1) = x_2(t_1) = p_1;\n % there are in total 2*(m-1) constraints\n idx = 1; % constraint counter\n for k = 1:(m-1)\n A(idx, 4*(k-1)+1:4*k, i) = [ts(k+1)^3, ts(k+1)^2, ts(k+1), 1];\n Y(idx,i) = path0(k+1,i);\n idx = idx + 1;\n A(idx, 4*(k)+1:4*(k+1), i) = [ts(k+1)^3, ts(k+1)^2, ts(k+1), 1];\n Y(idx,i) = path0(k+1,i);\n idx = idx + 1;\n end\n % constraint 2: \\dot{x}_k(t_k) = \\dot{x}_{k+1}(t_k)\n % \\dot{x}_k(t) = 3*c_{k,3}*t^2 + 2*c_{k,2}*t + c_{k,1}\n % e.g. \\dot{x}_1(t_1) = \\dot{x}_2(t_1)\n % there are in total m-1 constraints\n for k = 1:(m-1)\n A(idx, 4*(k-1)+1:4*k, i) = [3*ts(k+1)^2, 2*ts(k+1), 1, 0];\n% A(idx, 4*(k)+1:4*(k+1), i) = -[3*ts(k+1)^2, 2*ts(k+1), 1, 0];\n Y(idx,i) = 0;\n idx = idx + 1;\n A(idx, 4*(k)+1:4*(k+1), i) = [3*ts(k+1)^2, 2*ts(k+1), 1, 0];\n Y(idx,i) = 0;\n idx = idx + 1;\n end\n \n% % constraint 3: \\ddot{x}_k(t_k) = \\ddot{x}_{k+1}(t_k)\n% % \\ddot{x}_k(t) =6*c_{k,3}*t + 2*c_{k,2}\n% % e.g. \\ddot{x}_1(t_1) = \\ddot{x}_2(t_1)\n% % there are in total m-1 constraints\n% for k = 1:(m-1)\n% A(idx, 4*(k-1)+1:4*k, i) = [6*ts(k+1), 2, 0, 0];\n% A(idx, 4*(k)+1:4*(k+1), i) = -[6*ts(k+1), 2, 0, 0];\n% Y(idx,i) = 0;\n% idx = idx + 1;\n% end\n \n % so far there are 2*(m-1) + (m-1) + (m-1) = 4m - 4 constraints\n % there are 4 left:\n % x_1(t_0) = p_0\n % x_T(t_T) = p_T\n % \\dot{x}_0(t_0) = 0\n % \\dot{x}_T(t_T) = 0\n k = 1;\n A(idx, 4*(k-1)+1:4*k, i) = [ts(k)^3, ts(k)^2, ts(k), 1];\n Y(idx,i) = path0(k,i);\n idx = idx + 1;\n A(idx, 4*(k-1)+1:4*k, i) = [3*ts(k)^2, 2*ts(k), 1, 0];\n Y(idx,i) = 0;\n idx = idx + 1;\n k = m;\n A(idx, 4*(k-1)+1:4*k, i) = [ts(k+1)^3, ts(k+1)^2, ts(k+1), 1];\n Y(idx,i) = path0(k+1,i);\n idx = idx + 1;\n A(idx, 4*(k-1)+1:4*k, i) = [3*ts(k+1)^2, 2*ts(k+1), 1, 0];\n Y(idx,i) = 0;\n idx = idx + 1;\n% assert(rank(A(:,:,i))==4*m);\n X(:,i) = A(:,:,i)\\Y(:,i);\n end\n% for i = 1:n\n% A(:,:,i) = eye(4*m)*eps;\n% % constraint 1: x_k(t_k) = x_{k+1}(t_k) = p_k, where p_k is a\n% % waypoint\n% % x_k(t) = c_{k,3}*t^3 + c_{k,2}*t^2 + c_{k,1}*t^1 + c_{k,0}\n% % for k = 1..(m-1)\n% % e.g. x_1(t_1) = x_2(t_1) = p_1;\n% % there are in total 2*(m-1) constraints\n% idx = 1; % constraint counter\n% for k = 1:(m-1)\n% A(idx, 4*(k-1)+1:4*k, i) = [ts(k+1)^3, ts(k+1)^2, ts(k+1), 1];\n% Y(idx,i) = path0(k+1,i);\n% idx = idx + 1;\n% A(idx, 4*(k)+1:4*(k+1), i) = [ts(k+1)^3, ts(k+1)^2, ts(k+1), 1];\n% Y(idx,i) = path0(k+1,i);\n% idx = idx + 1;\n% end\n% % constraint 2: \\dot{x}_k(t_k) = \\dot{x}_{k+1}(t_k)\n% % \\dot{x}_k(t) = 3*c_{k,3}*t^2 + 2*c_{k,2}*t + c_{k,1}\n% % e.g. \\dot{x}_1(t_1) = \\dot{x}_2(t_1)\n% % there are in total m-1 constraints\n% for k = 1:(m-1)\n% A(idx, 4*(k-1)+1:4*k, i) = [3*ts(k+1)^2, 2*ts(k+1), 1, 0];\n% A(idx, 4*(k)+1:4*(k+1), i) = -[3*ts(k+1)^2, 2*ts(k+1), 1, 0];\n% Y(idx,i) = 0;\n% idx = idx + 1;\n% end\n% \n% % constraint 3: \\ddot{x}_k(t_k) = \\ddot{x}_{k+1}(t_k)\n% % \\ddot{x}_k(t) =6*c_{k,3}*t + 2*c_{k,2}\n% % e.g. \\ddot{x}_1(t_1) = \\ddot{x}_2(t_1)\n% % there are in total m-1 constraints\n% for k = 1:(m-1)\n% A(idx, 4*(k-1)+1:4*k, i) = [6*ts(k+1), 2, 0, 0];\n% A(idx, 4*(k)+1:4*(k+1), i) = -[6*ts(k+1), 2, 0, 0];\n% Y(idx,i) = 0;\n% idx = idx + 1;\n% end\n% \n% % so far there are 2*(m-1) + (m-1) + (m-1) = 4m - 4 constraints\n% % there are 4 left:\n% % x_1(t_0) = p_0\n% % x_T(t_T) = p_T\n% % \\dot{x}_0(t_0) = 0\n% % \\dot{x}_T(t_T) = 0\n% k = 1;\n% A(idx, 4*(k-1)+1:4*k, i) = [ts(k)^3, ts(k)^2, ts(k), 1];\n% Y(idx,i) = path0(k,i);\n% idx = idx + 1;\n% A(idx, 4*(k-1)+1:4*k, i) = [3*ts(k)^2, 2*ts(k), 1, 0];\n% Y(idx,i) = 0;\n% idx = idx + 1;\n% k = m;\n% A(idx, 4*(k-1)+1:4*k, i) = [ts(k+1)^3, ts(k+1)^2, ts(k+1), 1];\n% Y(idx,i) = path0(k+1,i);\n% idx = idx + 1;\n% A(idx, 4*(k-1)+1:4*k, i) = [3*ts(k+1)^2, 2*ts(k+1), 1, 0];\n% Y(idx,i) = 0;\n% idx = idx + 1;\n% % assert(rank(A(:,:,i))==4*m);\n% X(:,i) = A(:,:,i)\\Y(:,i);\n% end\n\nend", "meta": {"author": "yrlu", "repo": "quadrotor", "sha": "a7d951902567d75996d7b30cff7b2bc05e993602", "save_path": "github-repos/MATLAB/yrlu-quadrotor", "path": "github-repos/MATLAB/yrlu-quadrotor/quadrotor-a7d951902567d75996d7b30cff7b2bc05e993602/traj_planning/traj_opt3c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347124, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6832920707432234}} {"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 [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": "%% Example 8.15: Duffing van der Pol oscillator\n%\n% Copyright: \n% 2018 - Simo Särkkä 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": "function visible_probability = hidden_state_to_visible_probabilities(rbm_w, hidden_state)\n % is a matrix of size